diff --git a/rest/accounts/V1.ts b/rest/accounts/V1.ts new file mode 100644 index 000000000..b88289b50 --- /dev/null +++ b/rest/accounts/V1.ts @@ -0,0 +1,101 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Accounts + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import AccountsBase from "../AccountsBase"; +import Version from "../../base/Version"; +import { AuthTokenPromotionListInstance } from "./v1/authTokenPromotion"; +import { AwsListInstance } from "./v1/aws"; +import { BulkConsentsListInstance } from "./v1/bulkConsents"; +import { BulkContactsListInstance } from "./v1/bulkContacts"; +import { MessagingGeopermissionsListInstance } from "./v1/messagingGeopermissions"; +import { PublicKeyListInstance } from "./v1/publicKey"; +import { SafelistListInstance } from "./v1/safelist"; +import { SecondaryAuthTokenListInstance } from "./v1/secondaryAuthToken"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Accounts + * + * @param domain - The Twilio (Twilio.Accounts) domain + */ + constructor(domain: AccountsBase) { + super(domain, "v1"); + } + + /** authTokenPromotion - { Twilio.Accounts.V1.AuthTokenPromotionListInstance } resource */ + protected _authTokenPromotion?: AuthTokenPromotionListInstance; + /** aws - { Twilio.Accounts.V1.AwsListInstance } resource */ + protected _aws?: AwsListInstance; + /** bulkConsents - { Twilio.Accounts.V1.BulkConsentsListInstance } resource */ + protected _bulkConsents?: BulkConsentsListInstance; + /** bulkContacts - { Twilio.Accounts.V1.BulkContactsListInstance } resource */ + protected _bulkContacts?: BulkContactsListInstance; + /** messagingGeopermissions - { Twilio.Accounts.V1.MessagingGeopermissionsListInstance } resource */ + protected _messagingGeopermissions?: MessagingGeopermissionsListInstance; + /** publicKey - { Twilio.Accounts.V1.PublicKeyListInstance } resource */ + protected _publicKey?: PublicKeyListInstance; + /** safelist - { Twilio.Accounts.V1.SafelistListInstance } resource */ + protected _safelist?: SafelistListInstance; + /** secondaryAuthToken - { Twilio.Accounts.V1.SecondaryAuthTokenListInstance } resource */ + protected _secondaryAuthToken?: SecondaryAuthTokenListInstance; + + /** Getter for authTokenPromotion resource */ + get authTokenPromotion(): AuthTokenPromotionListInstance { + this._authTokenPromotion = this._authTokenPromotion || AuthTokenPromotionListInstance(this); + return this._authTokenPromotion; + } + + /** Getter for aws resource */ + get aws(): AwsListInstance { + this._aws = this._aws || AwsListInstance(this); + return this._aws; + } + + /** Getter for bulkConsents resource */ + get bulkConsents(): BulkConsentsListInstance { + this._bulkConsents = this._bulkConsents || BulkConsentsListInstance(this); + return this._bulkConsents; + } + + /** Getter for bulkContacts resource */ + get bulkContacts(): BulkContactsListInstance { + this._bulkContacts = this._bulkContacts || BulkContactsListInstance(this); + return this._bulkContacts; + } + + /** Getter for messagingGeopermissions resource */ + get messagingGeopermissions(): MessagingGeopermissionsListInstance { + this._messagingGeopermissions = this._messagingGeopermissions || MessagingGeopermissionsListInstance(this); + return this._messagingGeopermissions; + } + + /** Getter for publicKey resource */ + get publicKey(): PublicKeyListInstance { + this._publicKey = this._publicKey || PublicKeyListInstance(this); + return this._publicKey; + } + + /** Getter for safelist resource */ + get safelist(): SafelistListInstance { + this._safelist = this._safelist || SafelistListInstance(this); + return this._safelist; + } + + /** Getter for secondaryAuthToken resource */ + get secondaryAuthToken(): SecondaryAuthTokenListInstance { + this._secondaryAuthToken = this._secondaryAuthToken || SecondaryAuthTokenListInstance(this); + return this._secondaryAuthToken; + } + +} diff --git a/rest/accounts/v1/authTokenPromotion.ts b/rest/accounts/v1/authTokenPromotion.ts new file mode 100644 index 000000000..d29880cf7 --- /dev/null +++ b/rest/accounts/v1/authTokenPromotion.ts @@ -0,0 +1,257 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Accounts + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +export interface AuthTokenPromotionContext { + + /** + * Update a AuthTokenPromotionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthTokenPromotionInstance + */ + update(callback?: (error: Error | null, item?: AuthTokenPromotionInstance) => any): Promise + + /** + * Update a AuthTokenPromotionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthTokenPromotionInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AuthTokenPromotionContextSolution { +} + +export class AuthTokenPromotionContextImpl implements AuthTokenPromotionContext { + protected _solution: AuthTokenPromotionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/AuthTokens/Promote`; + } + + update(callback?: (error: Error | null, item?: AuthTokenPromotionInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new AuthTokenPromotionInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AuthTokenPromotionInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AuthTokenPromotionPayload extends AuthTokenPromotionResource {} + +interface AuthTokenPromotionResource { + account_sid: string; + auth_token: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class AuthTokenPromotionInstance { + protected _solution: AuthTokenPromotionContextSolution; + protected _context?: AuthTokenPromotionContext; + + constructor(protected _version: V1, payload: AuthTokenPromotionResource) { + + this.accountSid = (payload.account_sid); + this.authToken = (payload.auth_token); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the secondary Auth Token was created for. + */ + accountSid: string; + /** + * The promoted Auth Token that must be used to authenticate future API requests. + */ + authToken: string; + /** + * The date and time in UTC when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The URI for this resource, relative to `https://accounts.twilio.com` + */ + url: string; + + private get _proxy(): AuthTokenPromotionContext { + this._context = this._context || new AuthTokenPromotionContextImpl(this._version); + return this._context; + } + + /** + * Update a AuthTokenPromotionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthTokenPromotionInstance + */ + update(callback?: (error: Error | null, item?: AuthTokenPromotionInstance) => any): Promise + + { + return this._proxy.update(callback); + } + + /** + * Update a AuthTokenPromotionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthTokenPromotionInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.updateWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + authToken: this.authToken, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AuthTokenPromotionSolution { +} + +export interface AuthTokenPromotionListInstance { + _version: V1; + _solution: AuthTokenPromotionSolution; + _uri: string; + + (): AuthTokenPromotionContext; + get(): AuthTokenPromotionContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AuthTokenPromotionListInstance(version: V1): AuthTokenPromotionListInstance { + const instance = (() => instance.get()) as AuthTokenPromotionListInstance; + + instance.get = function get(): AuthTokenPromotionContext { + return new AuthTokenPromotionContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/accounts/v1/aws.ts b/rest/accounts/v1/aws.ts new file mode 100644 index 000000000..5938ee308 --- /dev/null +++ b/rest/accounts/v1/aws.ts @@ -0,0 +1,901 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Accounts + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a AwsInstance + */ +export interface AwsContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a AwsInstance + */ +export interface AwsListInstanceCreateOptions { + /** A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` */ + "credentials": string; + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. */ + "accountSid"?: string; +} + +/** + * Options to pass to each + */ +export interface AwsListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AwsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AwsListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AwsListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AwsContext { + + /** + * Remove a AwsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AwsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a AwsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance + */ + fetch(callback?: (error: Error | null, item?: AwsInstance) => any): Promise + + /** + * Fetch a AwsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a AwsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance + */ + update(callback?: (error: Error | null, item?: AwsInstance) => any): Promise; + /** + * Update a AwsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance + */ + update(params: AwsContextUpdateOptions, callback?: (error: Error | null, item?: AwsInstance) => any): Promise; + + /** + * Update a AwsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AwsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance with HTTP metadata + */ + updateWithHttpInfo(params: AwsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AwsContextSolution { + "sid": string; +} + +export class AwsContextImpl implements AwsContext { + protected _solution: AwsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Credentials/AWS/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AwsInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AwsInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AwsInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: AwsContextUpdateOptions | ((error: Error | null, item?: AwsInstance) => any),callback?: (error: Error | null, item?: AwsInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AwsInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: AwsContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AwsInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AwsPayload extends TwilioResponsePayload { + credentials: AwsResource[]; +} + +interface AwsResource { + sid: string; + account_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class AwsInstance { + protected _solution: AwsContextSolution; + protected _context?: AwsContext; + + constructor(protected _version: V1, payload: AwsResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the AWS resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AWS resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The URI for this resource, relative to `https://accounts.twilio.com` + */ + url: string; + + private get _proxy(): AwsContext { + this._context = this._context || new AwsContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a AwsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AwsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AwsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance + */ + fetch(callback?: (error: Error | null, item?: AwsInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AwsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a AwsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance + */ + update(callback?: (error: Error | null, item?: AwsInstance) => any): Promise; + /** + * Update a AwsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance + */ + update(params: AwsContextUpdateOptions, callback?: (error: Error | null, item?: AwsInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: AwsInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a AwsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AwsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance with HTTP metadata + */ + updateWithHttpInfo(params: AwsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AwsSolution { +} + +export interface AwsListInstance { + _version: V1; + _solution: AwsSolution; + _uri: string; + + (sid: string, ): AwsContext; + get(sid: string, ): AwsContext; + + + + + + + + + /** + * Create a AwsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance + */ + create(params: AwsListInstanceCreateOptions, callback?: (error: Error | null, item?: AwsInstance) => any): Promise; + + /** + * Create a AwsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AwsInstance with HTTP metadata + */ + createWithHttpInfo(params: AwsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams AwsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AwsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AwsInstance, done: (err?: Error) => void) => void): void; + each(params: AwsListInstanceEachOptions, callback?: (item: AwsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AwsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AwsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AwsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AwsListInstanceEachOptions, callback?: (item: AwsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AwsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AwsPage) => any): Promise; + /** + * Retrieve a single target page of AwsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AwsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AwsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AwsInstance[]) => any): Promise; + list(params: AwsListInstanceOptions, callback?: (error: Error | null, items: AwsInstance[]) => any): Promise; + /** + * Lists AwsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AwsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AwsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AwsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AwsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AwsPage) => any): Promise; + page(params: AwsListInstancePageOptions, callback?: (error: Error | null, items: AwsPage) => any): Promise; + /** + * Retrieve a single page of AwsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AwsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AwsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AwsListInstance(version: V1): AwsListInstance { + const instance = ((sid, ) => instance.get(sid, )) as AwsListInstance; + + instance.get = function get(sid, ): AwsContext { + return new AwsContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Credentials/AWS`; + + instance.create = function create(params: AwsListInstanceCreateOptions, callback?: (error: Error | null, items: AwsInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["credentials"] === null || params["credentials"] === undefined) { + throw new Error('Required parameter "params[\'credentials\']" missing.'); + } + + let data: any = {}; + + + + data["Credentials"] = params["credentials"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AwsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AwsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["credentials"] === null || params["credentials"] === undefined) { + throw new Error('Required parameter "params[\'credentials\']" missing.'); + } + + let data: any = {}; + + + + data["Credentials"] = params["credentials"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AwsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AwsListInstancePageOptions | ((error: Error | null, items: AwsPage) => any), callback?: (error: Error | null, items: AwsPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AwsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AwsPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AwsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AwsListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AwsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AwsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AwsPage extends Page { +/** +* Initialize the AwsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: AwsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AwsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AwsResource): AwsInstance { + + return new AwsInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/accounts/v1/bulkConsents.ts b/rest/accounts/v1/bulkConsents.ts new file mode 100644 index 000000000..08b0e4f19 --- /dev/null +++ b/rest/accounts/v1/bulkConsents.ts @@ -0,0 +1,195 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Accounts + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a BulkConsentsInstance + */ +export interface BulkConsentsListInstanceCreateOptions { + /** This is a list of objects that describes a contact\\\'s opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]; `date_of_consent`, an optional datetime string field in ISO-8601 format that captures the exact date and time when the user gave or revoked consent. If not provided, it will be empty. */ + "items": Array; +} + + +export interface BulkConsentsSolution { +} + +export interface BulkConsentsListInstance { + _version: V1; + _solution: BulkConsentsSolution; + _uri: string; + + + + /** + * Create a BulkConsentsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkConsentsInstance + */ + create(params: BulkConsentsListInstanceCreateOptions, callback?: (error: Error | null, item?: BulkConsentsInstance) => any): Promise; + + /** + * Create a BulkConsentsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkConsentsInstance with HTTP metadata + */ + createWithHttpInfo(params: BulkConsentsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BulkConsentsListInstance(version: V1): BulkConsentsListInstance { + const instance = {} as BulkConsentsListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Consents/Bulk`; + + instance.create = function create(params: BulkConsentsListInstanceCreateOptions, callback?: (error: Error | null, items: BulkConsentsInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["items"] === null || params["items"] === undefined) { + throw new Error('Required parameter "params[\'items\']" missing.'); + } + + let data: any = {}; + + + + data["Items"] = serialize.map(params["items"], (e: any) => serialize.object(e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BulkConsentsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: BulkConsentsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["items"] === null || params["items"] === undefined) { + throw new Error('Required parameter "params[\'items\']" missing.'); + } + + let data: any = {}; + + + + data["Items"] = serialize.map(params["items"], (e: any) => serialize.object(e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new BulkConsentsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface BulkConsentsPayload extends BulkConsentsResource {} + +interface BulkConsentsResource { + items: any; +} + +export class BulkConsentsInstance { + + constructor(protected _version: V1, payload: BulkConsentsResource) { + + this.items = (payload.items); + + } + + /** + * A list of objects where each object represents the result of processing a `correlation_id`. Each object contains the following fields: `correlation_id`, a unique 32-character UUID that maps the response to the original request; `error_code`, an integer where 0 indicates success and any non-zero value represents an error; and `error_messages`, an array of strings describing specific validation errors encountered. If the request is successful, the error_messages array will be empty. + */ + items: any; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + items: this.items, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/accounts/v1/bulkContacts.ts b/rest/accounts/v1/bulkContacts.ts new file mode 100644 index 000000000..984d96460 --- /dev/null +++ b/rest/accounts/v1/bulkContacts.ts @@ -0,0 +1,195 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Accounts + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a BulkContactsInstance + */ +export interface BulkContactsListInstanceCreateOptions { + /** A list of objects where each object represents a contact\\\'s details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code. */ + "items": Array; +} + + +export interface BulkContactsSolution { +} + +export interface BulkContactsListInstance { + _version: V1; + _solution: BulkContactsSolution; + _uri: string; + + + + /** + * Create a BulkContactsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkContactsInstance + */ + create(params: BulkContactsListInstanceCreateOptions, callback?: (error: Error | null, item?: BulkContactsInstance) => any): Promise; + + /** + * Create a BulkContactsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkContactsInstance with HTTP metadata + */ + createWithHttpInfo(params: BulkContactsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BulkContactsListInstance(version: V1): BulkContactsListInstance { + const instance = {} as BulkContactsListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Contacts/Bulk`; + + instance.create = function create(params: BulkContactsListInstanceCreateOptions, callback?: (error: Error | null, items: BulkContactsInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["items"] === null || params["items"] === undefined) { + throw new Error('Required parameter "params[\'items\']" missing.'); + } + + let data: any = {}; + + + + data["Items"] = serialize.map(params["items"], (e: any) => serialize.object(e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BulkContactsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: BulkContactsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["items"] === null || params["items"] === undefined) { + throw new Error('Required parameter "params[\'items\']" missing.'); + } + + let data: any = {}; + + + + data["Items"] = serialize.map(params["items"], (e: any) => serialize.object(e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new BulkContactsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface BulkContactsPayload extends BulkContactsResource {} + +interface BulkContactsResource { + items: any; +} + +export class BulkContactsInstance { + + constructor(protected _version: V1, payload: BulkContactsResource) { + + this.items = (payload.items); + + } + + /** + * A list of objects where each object represents the result of processing a `correlation_id`. Each object contains the following fields: `correlation_id`, a unique 32-character UUID that maps the response to the original request; `error_code`, an integer where 0 indicates success and any non-zero value represents an error; and `error_messages`, an array of strings describing specific validation errors encountered. If the request is successful, the error_messages array will be empty. + */ + items: any; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + items: this.items, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/accounts/v1/messagingGeopermissions.ts b/rest/accounts/v1/messagingGeopermissions.ts new file mode 100644 index 000000000..98f4e6d69 --- /dev/null +++ b/rest/accounts/v1/messagingGeopermissions.ts @@ -0,0 +1,306 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Accounts + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a MessagingGeopermissionsInstance + */ +export interface MessagingGeopermissionsListInstanceFetchOptions { + /** The country code to filter the geo permissions. If provided, only the geo permission for the specified country will be returned. */ + "countryCode"?: string; +} + +/** + * Options to pass to update a MessagingGeopermissionsInstance + */ +export interface MessagingGeopermissionsListInstanceUpdateOptions { + /** A list of objects where each object represents the Geo Permission to be updated. Each object contains the following fields: `country_code`, unique code for each country of Geo Permission; `type`, permission type of the Geo Permission i.e. country; `enabled`, configure true for enabling the Geo Permission, false for disabling the Geo Permission. */ + "permissions": Array; +} + + +export interface MessagingGeopermissionsSolution { +} + +export interface MessagingGeopermissionsListInstance { + _version: V1; + _solution: MessagingGeopermissionsSolution; + _uri: string; + + + + /** + * Fetch a MessagingGeopermissionsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingGeopermissionsInstance + */ + fetch(callback?: (error: Error | null, item?: MessagingGeopermissionsInstance) => any): Promise; + /** + * Fetch a MessagingGeopermissionsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingGeopermissionsInstance + */ + fetch(params: MessagingGeopermissionsListInstanceFetchOptions, callback?: (error: Error | null, item?: MessagingGeopermissionsInstance) => any): Promise; + + /** + * Fetch a MessagingGeopermissionsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingGeopermissionsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a MessagingGeopermissionsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingGeopermissionsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: MessagingGeopermissionsListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Update a MessagingGeopermissionsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingGeopermissionsInstance + */ + update(params: MessagingGeopermissionsListInstanceUpdateOptions, callback?: (error: Error | null, item?: MessagingGeopermissionsInstance) => any): Promise; + + /** + * Update a MessagingGeopermissionsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingGeopermissionsInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessagingGeopermissionsListInstanceUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessagingGeopermissionsListInstance(version: V1): MessagingGeopermissionsListInstance { + const instance = {} as MessagingGeopermissionsListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Messaging/GeoPermissions`; + + instance.fetch = function fetch(params?: MessagingGeopermissionsListInstanceFetchOptions | ((error: Error | null, items: MessagingGeopermissionsInstance) => any), callback?: (error: Error | null, items: MessagingGeopermissionsInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["countryCode"] !== undefined) + data["CountryCode"] = params["countryCode"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new MessagingGeopermissionsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params?: MessagingGeopermissionsListInstanceFetchOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["countryCode"] !== undefined) + data["CountryCode"] = params["countryCode"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessagingGeopermissionsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.update = function update(params: MessagingGeopermissionsListInstanceUpdateOptions, callback?: (error: Error | null, items: MessagingGeopermissionsInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permissions"] === null || params["permissions"] === undefined) { + throw new Error('Required parameter "params[\'permissions\']" missing.'); + } + + let data: any = {}; + + + + data["Permissions"] = serialize.map(params["permissions"], (e: any) => serialize.object(e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new MessagingGeopermissionsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.updateWithHttpInfo = function updateWithHttpInfo(params: MessagingGeopermissionsListInstanceUpdateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permissions"] === null || params["permissions"] === undefined) { + throw new Error('Required parameter "params[\'permissions\']" missing.'); + } + + let data: any = {}; + + + + data["Permissions"] = serialize.map(params["permissions"], (e: any) => serialize.object(e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessagingGeopermissionsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface MessagingGeopermissionsPayload extends MessagingGeopermissionsResource {} + +interface MessagingGeopermissionsResource { + permissions: any; +} + +export class MessagingGeopermissionsInstance { + + constructor(protected _version: V1, payload: MessagingGeopermissionsResource) { + + this.permissions = (payload.permissions); + + } + + /** + * A list of objects where each object represents the result of processing a messaging Geo Permission. Each object contains the following fields: `country_code`, the country code of the country for which the permission was updated; `type`, the type of the permission i.e. country; `enabled`, true if the permission is enabled else false; `error_code`, an integer where 0 indicates success and any non-zero value represents an error; and `error_messages`, an array of strings describing specific validation errors encountered. If the request is successful, the error_messages array will be empty. + */ + permissions: any; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + permissions: this.permissions, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/accounts/v1/publicKey.ts b/rest/accounts/v1/publicKey.ts new file mode 100644 index 000000000..b211a92be --- /dev/null +++ b/rest/accounts/v1/publicKey.ts @@ -0,0 +1,901 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Accounts + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a PublicKeyInstance + */ +export interface PublicKeyContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a PublicKeyInstance + */ +export interface PublicKeyListInstanceCreateOptions { + /** A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` */ + "publicKey": string; + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request */ + "accountSid"?: string; +} + +/** + * Options to pass to each + */ +export interface PublicKeyListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PublicKeyInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PublicKeyListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PublicKeyListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PublicKeyContext { + + /** + * Remove a PublicKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a PublicKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a PublicKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance + */ + fetch(callback?: (error: Error | null, item?: PublicKeyInstance) => any): Promise + + /** + * Fetch a PublicKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a PublicKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance + */ + update(callback?: (error: Error | null, item?: PublicKeyInstance) => any): Promise; + /** + * Update a PublicKeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance + */ + update(params: PublicKeyContextUpdateOptions, callback?: (error: Error | null, item?: PublicKeyInstance) => any): Promise; + + /** + * Update a PublicKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a PublicKeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance with HTTP metadata + */ + updateWithHttpInfo(params: PublicKeyContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PublicKeyContextSolution { + "sid": string; +} + +export class PublicKeyContextImpl implements PublicKeyContext { + protected _solution: PublicKeyContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Credentials/PublicKeys/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: PublicKeyInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PublicKeyInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new PublicKeyInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: PublicKeyContextUpdateOptions | ((error: Error | null, item?: PublicKeyInstance) => any),callback?: (error: Error | null, item?: PublicKeyInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PublicKeyInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: PublicKeyContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PublicKeyInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PublicKeyPayload extends TwilioResponsePayload { + credentials: PublicKeyResource[]; +} + +interface PublicKeyResource { + sid: string; + account_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class PublicKeyInstance { + protected _solution: PublicKeyContextSolution; + protected _context?: PublicKeyContext; + + constructor(protected _version: V1, payload: PublicKeyResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that that we created to identify the PublicKey resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential that the PublicKey resource belongs to. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The URI for this resource, relative to `https://accounts.twilio.com` + */ + url: string; + + private get _proxy(): PublicKeyContext { + this._context = this._context || new PublicKeyContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a PublicKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a PublicKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a PublicKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance + */ + fetch(callback?: (error: Error | null, item?: PublicKeyInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PublicKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a PublicKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance + */ + update(callback?: (error: Error | null, item?: PublicKeyInstance) => any): Promise; + /** + * Update a PublicKeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance + */ + update(params: PublicKeyContextUpdateOptions, callback?: (error: Error | null, item?: PublicKeyInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: PublicKeyInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a PublicKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a PublicKeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance with HTTP metadata + */ + updateWithHttpInfo(params: PublicKeyContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PublicKeySolution { +} + +export interface PublicKeyListInstance { + _version: V1; + _solution: PublicKeySolution; + _uri: string; + + (sid: string, ): PublicKeyContext; + get(sid: string, ): PublicKeyContext; + + + + + + + + + /** + * Create a PublicKeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance + */ + create(params: PublicKeyListInstanceCreateOptions, callback?: (error: Error | null, item?: PublicKeyInstance) => any): Promise; + + /** + * Create a PublicKeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublicKeyInstance with HTTP metadata + */ + createWithHttpInfo(params: PublicKeyListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams PublicKeyInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublicKeyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PublicKeyInstance, done: (err?: Error) => void) => void): void; + each(params: PublicKeyListInstanceEachOptions, callback?: (item: PublicKeyInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PublicKeyInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublicKeyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PublicKeyInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PublicKeyListInstanceEachOptions, callback?: (item: PublicKeyInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PublicKeyInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PublicKeyPage) => any): Promise; + /** + * Retrieve a single target page of PublicKeyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists PublicKeyInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublicKeyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PublicKeyInstance[]) => any): Promise; + list(params: PublicKeyListInstanceOptions, callback?: (error: Error | null, items: PublicKeyInstance[]) => any): Promise; + /** + * Lists PublicKeyInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublicKeyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: PublicKeyListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of PublicKeyInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublicKeyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PublicKeyPage) => any): Promise; + page(params: PublicKeyListInstancePageOptions, callback?: (error: Error | null, items: PublicKeyPage) => any): Promise; + /** + * Retrieve a single page of PublicKeyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublicKeyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: PublicKeyListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PublicKeyListInstance(version: V1): PublicKeyListInstance { + const instance = ((sid, ) => instance.get(sid, )) as PublicKeyListInstance; + + instance.get = function get(sid, ): PublicKeyContext { + return new PublicKeyContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Credentials/PublicKeys`; + + instance.create = function create(params: PublicKeyListInstanceCreateOptions, callback?: (error: Error | null, items: PublicKeyInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["publicKey"] === null || params["publicKey"] === undefined) { + throw new Error('Required parameter "params[\'publicKey\']" missing.'); + } + + let data: any = {}; + + + + data["PublicKey"] = params["publicKey"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PublicKeyInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: PublicKeyListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["publicKey"] === null || params["publicKey"] === undefined) { + throw new Error('Required parameter "params[\'publicKey\']" missing.'); + } + + let data: any = {}; + + + + data["PublicKey"] = params["publicKey"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PublicKeyInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: PublicKeyListInstancePageOptions | ((error: Error | null, items: PublicKeyPage) => any), callback?: (error: Error | null, items: PublicKeyPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PublicKeyPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PublicKeyPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PublicKeyPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PublicKeyListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PublicKeyPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PublicKeyPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PublicKeyPage extends Page { +/** +* Initialize the PublicKeyPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: PublicKeySolution) { + super(version, response, solution); + } + + /** + * Build an instance of PublicKeyInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PublicKeyResource): PublicKeyInstance { + + return new PublicKeyInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/accounts/v1/safelist.ts b/rest/accounts/v1/safelist.ts new file mode 100644 index 000000000..87eb496ac --- /dev/null +++ b/rest/accounts/v1/safelist.ts @@ -0,0 +1,420 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Accounts + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a SafelistInstance + */ +export interface SafelistListInstanceCreateOptions { + /** The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). */ + "phoneNumber": string; +} + +/** + * Options to pass to remove a SafelistInstance + */ +export interface SafelistListInstanceRemoveOptions { + /** The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). */ + "phoneNumber"?: string; +} + +/** + * Options to pass to fetch a SafelistInstance + */ +export interface SafelistListInstanceFetchOptions { + /** The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). */ + "phoneNumber"?: string; +} + + +export interface SafelistSolution { +} + +export interface SafelistListInstance { + _version: V1; + _solution: SafelistSolution; + _uri: string; + + + + /** + * Create a SafelistInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance + */ + create(params: SafelistListInstanceCreateOptions, callback?: (error: Error | null, item?: SafelistInstance) => any): Promise; + + /** + * Create a SafelistInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance with HTTP metadata + */ + createWithHttpInfo(params: SafelistListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Remove a SafelistInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a SafelistInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance + */ + remove(params: SafelistListInstanceRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a SafelistInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a SafelistInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance with HTTP metadata + */ + removeWithHttpInfo(params: SafelistListInstanceRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Fetch a SafelistInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance + */ + fetch(callback?: (error: Error | null, item?: SafelistInstance) => any): Promise; + /** + * Fetch a SafelistInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance + */ + fetch(params: SafelistListInstanceFetchOptions, callback?: (error: Error | null, item?: SafelistInstance) => any): Promise; + + /** + * Fetch a SafelistInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a SafelistInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance with HTTP metadata + */ + fetchWithHttpInfo(params: SafelistListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SafelistListInstance(version: V1): SafelistListInstance { + const instance = {} as SafelistListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/SafeList/Numbers`; + + instance.create = function create(params: SafelistListInstanceCreateOptions, callback?: (error: Error | null, items: SafelistInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SafelistInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SafelistListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SafelistInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.remove = function remove(params?: SafelistListInstanceRemoveOptions | ((error: Error | null, items: boolean) => any), callback?: (error: Error | null, items: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + + + + + + const headers: any = {}; + + let operationVersion = version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.removeWithHttpInfo = function removeWithHttpInfo(params?: SafelistListInstanceRemoveOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + + + + + + const headers: any = {}; + + let operationVersion = version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetch = function fetch(params?: SafelistListInstanceFetchOptions | ((error: Error | null, items: SafelistInstance) => any), callback?: (error: Error | null, items: SafelistInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new SafelistInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params?: SafelistListInstanceFetchOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SafelistInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface SafelistPayload extends SafelistResource {} + +interface SafelistResource { + sid: string; + phone_number: string; +} + +export class SafelistInstance { + + constructor(protected _version: V1, payload: SafelistResource) { + + this.sid = (payload.sid); + this.phoneNumber = (payload.phone_number); + + } + + /** + * The unique string that we created to identify the SafeList resource. + */ + sid: string; + /** + * The phone number or phone number 1k prefix in SafeList. + */ + phoneNumber: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + phoneNumber: this.phoneNumber, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/accounts/v1/secondaryAuthToken.ts b/rest/accounts/v1/secondaryAuthToken.ts new file mode 100644 index 000000000..b3ea700bf --- /dev/null +++ b/rest/accounts/v1/secondaryAuthToken.ts @@ -0,0 +1,335 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Accounts + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface SecondaryAuthTokenContext { + + /** + * Create a SecondaryAuthTokenInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SecondaryAuthTokenInstance + */ + create(callback?: (error: Error | null, item?: SecondaryAuthTokenInstance) => any): Promise + + /** + * Create a SecondaryAuthTokenInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SecondaryAuthTokenInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Remove a SecondaryAuthTokenInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a SecondaryAuthTokenInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SecondaryAuthTokenContextSolution { +} + +export class SecondaryAuthTokenContextImpl implements SecondaryAuthTokenContext { + protected _solution: SecondaryAuthTokenContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/AuthTokens/Secondary`; + } + + create(callback?: (error: Error | null, item?: SecondaryAuthTokenInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new SecondaryAuthTokenInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse => ({ + ...response, + body: new SecondaryAuthTokenInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SecondaryAuthTokenPayload extends SecondaryAuthTokenResource {} + +interface SecondaryAuthTokenResource { + account_sid: string; + date_created: Date; + date_updated: Date; + secondary_auth_token: string; + url: string; +} + +export class SecondaryAuthTokenInstance { + protected _solution: SecondaryAuthTokenContextSolution; + protected _context?: SecondaryAuthTokenContext; + + constructor(protected _version: V1, payload: SecondaryAuthTokenResource) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.secondaryAuthToken = (payload.secondary_auth_token); + this.url = (payload.url); + + this._solution = { }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the secondary Auth Token was created for. + */ + accountSid: string; + /** + * The date and time in UTC when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in UTC when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The generated secondary Auth Token that can be used to authenticate future API requests. + */ + secondaryAuthToken: string; + /** + * The URI for this resource, relative to `https://accounts.twilio.com` + */ + url: string; + + private get _proxy(): SecondaryAuthTokenContext { + this._context = this._context || new SecondaryAuthTokenContextImpl(this._version); + return this._context; + } + + /** + * Create a SecondaryAuthTokenInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SecondaryAuthTokenInstance + */ + create(callback?: (error: Error | null, item?: SecondaryAuthTokenInstance) => any): Promise + + { + return this._proxy.create(callback); + } + + /** + * Create a SecondaryAuthTokenInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SecondaryAuthTokenInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.createWithHttpInfo(callback); + } + + /** + * Remove a SecondaryAuthTokenInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SecondaryAuthTokenInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + secondaryAuthToken: this.secondaryAuthToken, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SecondaryAuthTokenSolution { +} + +export interface SecondaryAuthTokenListInstance { + _version: V1; + _solution: SecondaryAuthTokenSolution; + _uri: string; + + (): SecondaryAuthTokenContext; + get(): SecondaryAuthTokenContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SecondaryAuthTokenListInstance(version: V1): SecondaryAuthTokenListInstance { + const instance = (() => instance.get()) as SecondaryAuthTokenListInstance; + + instance.get = function get(): SecondaryAuthTokenContext { + return new SecondaryAuthTokenContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/api/V2010.ts b/rest/api/V2010.ts new file mode 100644 index 000000000..d191f1e9a --- /dev/null +++ b/rest/api/V2010.ts @@ -0,0 +1,146 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import ApiBase from "../ApiBase"; +import Version from "../../base/Version"; +import { AccountListInstance } from "./v2010/account"; +import { AuthCallsCredentialListMappingListInstance, AuthCallsCredentialListMappingContext } from "./v2010/authCallsCredentialListMapping"; +import { AuthCallsIpAccessControlListMappingListInstance, AuthCallsIpAccessControlListMappingContext } from "./v2010/authCallsIpAccessControlListMapping"; +import { AuthRegistrationsCredentialListMappingListInstance, AuthRegistrationsCredentialListMappingContext } from "./v2010/authRegistrationsCredentialListMapping"; +import { CredentialListListInstance, CredentialListContext } from "./v2010/credentialList"; +import { DomainListInstance, DomainContext } from "./v2010/domain"; +import { IpAccessControlListListInstance, IpAccessControlListContext } from "./v2010/ipAccessControlList"; +import { RecordListInstance } from "./v2010/record"; +import { TriggerListInstance } from "./v2010/trigger"; +import { AccountContext } from "./v2010/account"; + +export default class V2010 extends Version { + /** + * Initialize the V2010 version of Api + * + * @param domain - The Twilio (Twilio.Api) domain + */ + constructor(domain: ApiBase) { + super(domain, "2010-04-01"); + } + + /** accounts - { Twilio.Api.V2010.AccountListInstance } resource */ + protected _accounts?: AccountListInstance; + /** triggers - { Twilio.Api.V2010.TriggerListInstance } resource */ + protected _triggers?: TriggerListInstance; + /** account - { Twilio.Api.V2010.AccountContext } resource */ + protected _account?: AccountContext; + + /** Getter for accounts resource */ + get accounts(): AccountListInstance { + this._accounts = this._accounts || AccountListInstance(this); + return this._accounts; + } + + /** Accessor for credentialListMappings resource - list operations */ + credentialListMappings(AccountSid: string, DomainSid: string): AuthCallsCredentialListMappingListInstance; + /** Accessor for credentialListMappings resource - instance operations */ + credentialListMappings(AccountSid: string, DomainSid: string, sid: string): AuthCallsCredentialListMappingContext; + /** Implementation */ + credentialListMappings(AccountSid: string, DomainSid: string, sid?: string): AuthCallsCredentialListMappingListInstance | AuthCallsCredentialListMappingContext { + const listInstance = AuthCallsCredentialListMappingListInstance(this, AccountSid, DomainSid); + if (sid !== undefined) { + return listInstance.get(sid); + } + return listInstance; + } + + /** Accessor for ipAccessControlListMappings resource - list operations */ + ipAccessControlListMappings(AccountSid: string, DomainSid: string): AuthCallsIpAccessControlListMappingListInstance; + /** Accessor for ipAccessControlListMappings resource - instance operations */ + ipAccessControlListMappings(AccountSid: string, DomainSid: string, sid: string): AuthCallsIpAccessControlListMappingContext; + /** Implementation */ + ipAccessControlListMappings(AccountSid: string, DomainSid: string, sid?: string): AuthCallsIpAccessControlListMappingListInstance | AuthCallsIpAccessControlListMappingContext { + const listInstance = AuthCallsIpAccessControlListMappingListInstance(this, AccountSid, DomainSid); + if (sid !== undefined) { + return listInstance.get(sid); + } + return listInstance; + } + + /** Accessor for credentialListMappings resource - list operations */ + credentialListMappings(AccountSid: string, DomainSid: string): AuthRegistrationsCredentialListMappingListInstance; + /** Accessor for credentialListMappings resource - instance operations */ + credentialListMappings(AccountSid: string, DomainSid: string, sid: string): AuthRegistrationsCredentialListMappingContext; + /** Implementation */ + credentialListMappings(AccountSid: string, DomainSid: string, sid?: string): AuthRegistrationsCredentialListMappingListInstance | AuthRegistrationsCredentialListMappingContext { + const listInstance = AuthRegistrationsCredentialListMappingListInstance(this, AccountSid, DomainSid); + if (sid !== undefined) { + return listInstance.get(sid); + } + return listInstance; + } + + /** Accessor for credentialLists resource - list operations */ + credentialLists(AccountSid: string): CredentialListListInstance; + /** Accessor for credentialLists resource - instance operations */ + credentialLists(AccountSid: string, sid: string): CredentialListContext; + /** Implementation */ + credentialLists(AccountSid: string, sid?: string): CredentialListListInstance | CredentialListContext { + const listInstance = CredentialListListInstance(this, AccountSid); + if (sid !== undefined) { + return listInstance.get(sid); + } + return listInstance; + } + + /** Accessor for domains resource - list operations */ + domains(AccountSid: string): DomainListInstance; + /** Accessor for domains resource - instance operations */ + domains(AccountSid: string, sid: string): DomainContext; + /** Implementation */ + domains(AccountSid: string, sid?: string): DomainListInstance | DomainContext { + const listInstance = DomainListInstance(this, AccountSid); + if (sid !== undefined) { + return listInstance.get(sid); + } + return listInstance; + } + + /** Accessor for ipAccessControlLists resource - list operations */ + ipAccessControlLists(AccountSid: string): IpAccessControlListListInstance; + /** Accessor for ipAccessControlLists resource - instance operations */ + ipAccessControlLists(AccountSid: string, sid: string): IpAccessControlListContext; + /** Implementation */ + ipAccessControlLists(AccountSid: string, sid?: string): IpAccessControlListListInstance | IpAccessControlListContext { + const listInstance = IpAccessControlListListInstance(this, AccountSid); + if (sid !== undefined) { + return listInstance.get(sid); + } + return listInstance; + } + + /** Accessor for records resource */ + records(AccountSid: string): RecordListInstance { + return RecordListInstance(this, AccountSid); + } + + /** Getter for triggers resource */ + get triggers(): TriggerListInstance { + this._triggers = this._triggers || TriggerListInstance(this); + return this._triggers; + } + + /** Getter for account resource */ + get account(): AccountContext { + this._account = this._account || AccountListInstance(this)(this.domain.twilio.accountSid); + return this._account; + } + +} diff --git a/rest/api/v2010/account.ts b/rest/api/v2010/account.ts new file mode 100644 index 000000000..89e45b98a --- /dev/null +++ b/rest/api/v2010/account.ts @@ -0,0 +1,1213 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2010 from "../V2010"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { AddressListInstance } from "./account/address"; +import { ApplicationListInstance } from "./account/application"; +import { AuthorizedConnectAppListInstance } from "./account/authorizedConnectApp"; +import { AvailablePhoneNumberCountryListInstance } from "./account/availablePhoneNumberCountry"; +import { BalanceListInstance } from "./account/balance"; +import { CallListInstance } from "./account/call"; +import { ConferenceListInstance } from "./account/conference"; +import { ConnectAppListInstance } from "./account/connectApp"; +import { IncomingPhoneNumberListInstance } from "./account/incomingPhoneNumber"; +import { KeyListInstance } from "./account/key"; +import { MessageListInstance } from "./account/message"; +import { NewKeyListInstance } from "./account/newKey"; +import { NewSigningKeyListInstance } from "./account/newSigningKey"; +import { NotificationListInstance } from "./account/notification"; +import { OutgoingCallerIdListInstance } from "./account/outgoingCallerId"; +import { QueueListInstance } from "./account/queue"; +import { RecordingListInstance } from "./account/recording"; +import { ShortCodeListInstance } from "./account/shortCode"; +import { SigningKeyListInstance } from "./account/signingKey"; +import { TokenListInstance } from "./account/token"; +import { TranscriptionListInstance } from "./account/transcription"; +import { ValidationRequestListInstance } from "./account/validationRequest"; + + +/** + * The status of this account. Usually `active`, but can be `suspended` or `closed`. + */ +export type AccountStatus = 'active'|'suspended'|'closed'; + +/** + * The type of this account. Either `Trial` or `Full` if it\'s been upgraded + */ +export type AccountType = 'Trial'|'Full'; + + + +/** + * Options to pass to update a AccountInstance + */ +export interface AccountContextUpdateOptions { + /** Update the human-readable description of this Account */ + "friendlyName"?: string; + /** */ + "status"?: AccountStatus; +} + +/** + * Options to pass to create a AccountInstance + */ +export interface AccountListInstanceCreateOptions { + /** A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` */ + "friendlyName"?: string; +} + +/** + * Options to pass to each + */ +export interface AccountListInstanceEachOptions { + /** Only return the Account resources with friendly names that exactly match this name. */ + "friendlyName"?: string; + /** Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. */ + "status"?: AccountStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AccountInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AccountListInstanceOptions { + /** Only return the Account resources with friendly names that exactly match this name. */ + "friendlyName"?: string; + /** Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. */ + "status"?: AccountStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AccountListInstancePageOptions { + /** Only return the Account resources with friendly names that exactly match this name. */ + "friendlyName"?: string; + /** Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. */ + "status"?: AccountStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AccountContext { + addresses: AddressListInstance; + applications: ApplicationListInstance; + authorizedConnectApps: AuthorizedConnectAppListInstance; + availablePhoneNumbers: AvailablePhoneNumberCountryListInstance; + balance: BalanceListInstance; + calls: CallListInstance; + conferences: ConferenceListInstance; + connectApps: ConnectAppListInstance; + incomingPhoneNumbers: IncomingPhoneNumberListInstance; + keys: KeyListInstance; + messages: MessageListInstance; + newKeys: NewKeyListInstance; + newSigningKeys: NewSigningKeyListInstance; + notifications: NotificationListInstance; + outgoingCallerIds: OutgoingCallerIdListInstance; + queues: QueueListInstance; + recordings: RecordingListInstance; + shortCodes: ShortCodeListInstance; + signingKeys: SigningKeyListInstance; + tokens: TokenListInstance; + transcriptions: TranscriptionListInstance; + validationRequests: ValidationRequestListInstance; + + /** + * Fetch a AccountInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + fetch(callback?: (error: Error | null, item?: AccountInstance) => any): Promise + + /** + * Fetch a AccountInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a AccountInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + update(callback?: (error: Error | null, item?: AccountInstance) => any): Promise; + /** + * Update a AccountInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + update(params: AccountContextUpdateOptions, callback?: (error: Error | null, item?: AccountInstance) => any): Promise; + + /** + * Update a AccountInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AccountInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + updateWithHttpInfo(params: AccountContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AccountContextSolution { + "sid": string; +} + +export class AccountContextImpl implements AccountContext { + protected _solution: AccountContextSolution; + protected _uri: string; + + protected _addresses?: AddressListInstance; + protected _applications?: ApplicationListInstance; + protected _authorizedConnectApps?: AuthorizedConnectAppListInstance; + protected _availablePhoneNumbers?: AvailablePhoneNumberCountryListInstance; + protected _balance?: BalanceListInstance; + protected _calls?: CallListInstance; + protected _conferences?: ConferenceListInstance; + protected _connectApps?: ConnectAppListInstance; + protected _incomingPhoneNumbers?: IncomingPhoneNumberListInstance; + protected _keys?: KeyListInstance; + protected _messages?: MessageListInstance; + protected _newKeys?: NewKeyListInstance; + protected _newSigningKeys?: NewSigningKeyListInstance; + protected _notifications?: NotificationListInstance; + protected _outgoingCallerIds?: OutgoingCallerIdListInstance; + protected _queues?: QueueListInstance; + protected _recordings?: RecordingListInstance; + protected _shortCodes?: ShortCodeListInstance; + protected _signingKeys?: SigningKeyListInstance; + protected _tokens?: TokenListInstance; + protected _transcriptions?: TranscriptionListInstance; + protected _validationRequests?: ValidationRequestListInstance; + + constructor(protected _version: V2010, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Accounts/${sid}.json`; + } + + get addresses(): AddressListInstance { + this._addresses = this._addresses || AddressListInstance(this._version, this._solution.sid); + return this._addresses; + } + + get applications(): ApplicationListInstance { + this._applications = this._applications || ApplicationListInstance(this._version, this._solution.sid); + return this._applications; + } + + get authorizedConnectApps(): AuthorizedConnectAppListInstance { + this._authorizedConnectApps = this._authorizedConnectApps || AuthorizedConnectAppListInstance(this._version, this._solution.sid); + return this._authorizedConnectApps; + } + + get availablePhoneNumbers(): AvailablePhoneNumberCountryListInstance { + this._availablePhoneNumbers = this._availablePhoneNumbers || AvailablePhoneNumberCountryListInstance(this._version, this._solution.sid); + return this._availablePhoneNumbers; + } + + get balance(): BalanceListInstance { + this._balance = this._balance || BalanceListInstance(this._version, this._solution.sid); + return this._balance; + } + + get calls(): CallListInstance { + this._calls = this._calls || CallListInstance(this._version, this._solution.sid); + return this._calls; + } + + get conferences(): ConferenceListInstance { + this._conferences = this._conferences || ConferenceListInstance(this._version, this._solution.sid); + return this._conferences; + } + + get connectApps(): ConnectAppListInstance { + this._connectApps = this._connectApps || ConnectAppListInstance(this._version, this._solution.sid); + return this._connectApps; + } + + get incomingPhoneNumbers(): IncomingPhoneNumberListInstance { + this._incomingPhoneNumbers = this._incomingPhoneNumbers || IncomingPhoneNumberListInstance(this._version, this._solution.sid); + return this._incomingPhoneNumbers; + } + + get keys(): KeyListInstance { + this._keys = this._keys || KeyListInstance(this._version, this._solution.sid); + return this._keys; + } + + get messages(): MessageListInstance { + this._messages = this._messages || MessageListInstance(this._version, this._solution.sid); + return this._messages; + } + + get newKeys(): NewKeyListInstance { + this._newKeys = this._newKeys || NewKeyListInstance(this._version, this._solution.sid); + return this._newKeys; + } + + get newSigningKeys(): NewSigningKeyListInstance { + this._newSigningKeys = this._newSigningKeys || NewSigningKeyListInstance(this._version, this._solution.sid); + return this._newSigningKeys; + } + + get notifications(): NotificationListInstance { + this._notifications = this._notifications || NotificationListInstance(this._version, this._solution.sid); + return this._notifications; + } + + get outgoingCallerIds(): OutgoingCallerIdListInstance { + this._outgoingCallerIds = this._outgoingCallerIds || OutgoingCallerIdListInstance(this._version, this._solution.sid); + return this._outgoingCallerIds; + } + + get queues(): QueueListInstance { + this._queues = this._queues || QueueListInstance(this._version, this._solution.sid); + return this._queues; + } + + get recordings(): RecordingListInstance { + this._recordings = this._recordings || RecordingListInstance(this._version, this._solution.sid); + return this._recordings; + } + + get shortCodes(): ShortCodeListInstance { + this._shortCodes = this._shortCodes || ShortCodeListInstance(this._version, this._solution.sid); + return this._shortCodes; + } + + get signingKeys(): SigningKeyListInstance { + this._signingKeys = this._signingKeys || SigningKeyListInstance(this._version, this._solution.sid); + return this._signingKeys; + } + + get tokens(): TokenListInstance { + this._tokens = this._tokens || TokenListInstance(this._version, this._solution.sid); + return this._tokens; + } + + get transcriptions(): TranscriptionListInstance { + this._transcriptions = this._transcriptions || TranscriptionListInstance(this._version, this._solution.sid); + return this._transcriptions; + } + + get validationRequests(): ValidationRequestListInstance { + this._validationRequests = this._validationRequests || ValidationRequestListInstance(this._version, this._solution.sid); + return this._validationRequests; + } + + fetch(callback?: (error: Error | null, item?: AccountInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AccountInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AccountInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: AccountContextUpdateOptions | ((error: Error | null, item?: AccountInstance) => any),callback?: (error: Error | null, item?: AccountInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AccountInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: AccountContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AccountInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AccountPayload extends TwilioResponsePayload { + accounts: AccountResource[]; +} + +interface AccountResource { + auth_token: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + owner_account_sid: string; + sid: string; + status: AccountStatus; + subresource_uris: Record; + type: AccountType; + uri: string; +} + +export class AccountInstance { + protected _solution: AccountContextSolution; + protected _context?: AccountContext; + + constructor(protected _version: V2010, payload: AccountResource, sid?: string) { + + this.authToken = (payload.auth_token); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.ownerAccountSid = (payload.owner_account_sid); + this.sid = (payload.sid); + this.status = payload.status; + this.subresourceUris = (payload.subresource_uris); + this.type = payload.type; + this.uri = (payload.uri); + + this._solution = { sid: sid, }; + } + + /** + * The authorization token for this account. This token should be kept a secret, so no sharing. + */ + authToken: string; + /** + * The date that this account was created, in GMT in RFC 2822 format + */ + dateCreated: Date; + /** + * The date that this account was last updated, in GMT in RFC 2822 format. + */ + dateUpdated: Date; + /** + * A human readable description of this account, up to 64 characters long. By default the FriendlyName is your email address. + */ + friendlyName: string; + /** + * The unique 34 character id that represents the parent of this account. The OwnerAccountSid of a parent account is it\'s own sid. + */ + ownerAccountSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + status: AccountStatus; + /** + * A Map of various subresources available for the given Account Instance + */ + subresourceUris: Record; + type: AccountType; + /** + * The URI for this resource, relative to `https://api.twilio.com` + */ + uri: string; + + private get _proxy(): AccountContext { + this._context = this._context || new AccountContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a AccountInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + fetch(callback?: (error: Error | null, item?: AccountInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AccountInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a AccountInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + update(callback?: (error: Error | null, item?: AccountInstance) => any): Promise; + /** + * Update a AccountInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + update(params: AccountContextUpdateOptions, callback?: (error: Error | null, item?: AccountInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: AccountInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a AccountInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AccountInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + updateWithHttpInfo(params: AccountContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the addresses. + */ + addresses(): AddressListInstance { + return this._proxy.addresses; + } + + /** + * Access the applications. + */ + applications(): ApplicationListInstance { + return this._proxy.applications; + } + + /** + * Access the authorizedConnectApps. + */ + authorizedConnectApps(): AuthorizedConnectAppListInstance { + return this._proxy.authorizedConnectApps; + } + + /** + * Access the availablePhoneNumbers. + */ + availablePhoneNumbers(): AvailablePhoneNumberCountryListInstance { + return this._proxy.availablePhoneNumbers; + } + + /** + * Access the balance. + */ + balance(): BalanceListInstance { + return this._proxy.balance; + } + + /** + * Access the calls. + */ + calls(): CallListInstance { + return this._proxy.calls; + } + + /** + * Access the conferences. + */ + conferences(): ConferenceListInstance { + return this._proxy.conferences; + } + + /** + * Access the connectApps. + */ + connectApps(): ConnectAppListInstance { + return this._proxy.connectApps; + } + + /** + * Access the incomingPhoneNumbers. + */ + incomingPhoneNumbers(): IncomingPhoneNumberListInstance { + return this._proxy.incomingPhoneNumbers; + } + + /** + * Access the keys. + */ + keys(): KeyListInstance { + return this._proxy.keys; + } + + /** + * Access the messages. + */ + messages(): MessageListInstance { + return this._proxy.messages; + } + + /** + * Access the newKeys. + */ + newKeys(): NewKeyListInstance { + return this._proxy.newKeys; + } + + /** + * Access the newSigningKeys. + */ + newSigningKeys(): NewSigningKeyListInstance { + return this._proxy.newSigningKeys; + } + + /** + * Access the notifications. + */ + notifications(): NotificationListInstance { + return this._proxy.notifications; + } + + /** + * Access the outgoingCallerIds. + */ + outgoingCallerIds(): OutgoingCallerIdListInstance { + return this._proxy.outgoingCallerIds; + } + + /** + * Access the queues. + */ + queues(): QueueListInstance { + return this._proxy.queues; + } + + /** + * Access the recordings. + */ + recordings(): RecordingListInstance { + return this._proxy.recordings; + } + + /** + * Access the shortCodes. + */ + shortCodes(): ShortCodeListInstance { + return this._proxy.shortCodes; + } + + /** + * Access the signingKeys. + */ + signingKeys(): SigningKeyListInstance { + return this._proxy.signingKeys; + } + + /** + * Access the tokens. + */ + tokens(): TokenListInstance { + return this._proxy.tokens; + } + + /** + * Access the transcriptions. + */ + transcriptions(): TranscriptionListInstance { + return this._proxy.transcriptions; + } + + /** + * Access the validationRequests. + */ + validationRequests(): ValidationRequestListInstance { + return this._proxy.validationRequests; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + authToken: this.authToken, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + ownerAccountSid: this.ownerAccountSid, + sid: this.sid, + status: this.status, + subresourceUris: this.subresourceUris, + type: this.type, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AccountSolution { +} + +export interface AccountListInstance { + _version: V2010; + _solution: AccountSolution; + _uri: string; + + (sid: string, ): AccountContext; + get(sid: string, ): AccountContext; + + + + + + + /** + * Create a AccountInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + create(callback?: (error: Error | null, item?: AccountInstance) => any): Promise; + /** + * Create a AccountInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + create(params: AccountListInstanceCreateOptions, callback?: (error: Error | null, item?: AccountInstance) => any): Promise; + + /** + * Create a AccountInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a AccountInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + createWithHttpInfo(params: AccountListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams AccountInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + each(params: AccountListInstanceEachOptions, callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AccountInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AccountListInstanceEachOptions, callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AccountInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AccountPage) => any): Promise; + /** + * Retrieve a single target page of AccountInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AccountInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AccountInstance[]) => any): Promise; + list(params: AccountListInstanceOptions, callback?: (error: Error | null, items: AccountInstance[]) => any): Promise; + /** + * Lists AccountInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AccountListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AccountInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AccountPage) => any): Promise; + page(params: AccountListInstancePageOptions, callback?: (error: Error | null, items: AccountPage) => any): Promise; + /** + * Retrieve a single page of AccountInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AccountListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AccountListInstance(version: V2010): AccountListInstance { + const instance = ((sid, ) => instance.get(sid, )) as AccountListInstance; + + instance.get = function get(sid, ): AccountContext { + return new AccountContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Accounts.json`; + + instance.create = function create(params?: AccountListInstanceCreateOptions | ((error: Error | null, items: AccountInstance) => any), callback?: (error: Error | null, items: AccountInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AccountInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: AccountListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AccountInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AccountListInstancePageOptions | ((error: Error | null, items: AccountPage) => any), callback?: (error: Error | null, items: AccountPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AccountPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AccountPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AccountPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AccountListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AccountPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AccountPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AccountPage extends Page { +/** +* Initialize the AccountPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AccountSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AccountInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AccountResource): AccountInstance { + + return new AccountInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/address.ts b/rest/api/v2010/account/address.ts new file mode 100644 index 000000000..ab74c65c6 --- /dev/null +++ b/rest/api/v2010/account/address.ts @@ -0,0 +1,1167 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { DependentPhoneNumberListInstance } from "./address/dependentPhoneNumber"; + + + + + +/** + * Options to pass to update a AddressInstance + */ +export interface AddressContextUpdateOptions { + /** A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. */ + "friendlyName"?: string; + /** The name to associate with the address. */ + "customerName"?: string; + /** The number and street address of the address. */ + "street"?: string; + /** The city of the address. */ + "city"?: string; + /** The state or region of the address. */ + "region"?: string; + /** The postal code of the address. */ + "postalCode"?: string; + /** Whether to enable emergency calling on the address. Can be: `true` or `false`. */ + "emergencyEnabled"?: boolean; + /** Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won\\\'t alter the address you provide. */ + "autoCorrectAddress"?: boolean; + /** The additional number and street address of the address. */ + "streetSecondary"?: string; +} + +/** + * Options to pass to create a AddressInstance + */ +export interface AddressListInstanceCreateOptions { + /** The name to associate with the new address. */ + "customerName": string; + /** The number and street address of the new address. */ + "street": string; + /** The city of the new address. */ + "city": string; + /** The state or region of the new address. */ + "region": string; + /** The postal code of the new address. */ + "postalCode": string; + /** The ISO country code of the new address. */ + "isoCountry": string; + /** A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. */ + "friendlyName"?: string; + /** Whether to enable emergency calling on the new address. Can be: `true` or `false`. */ + "emergencyEnabled"?: boolean; + /** Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won\\\'t alter the address you provide. */ + "autoCorrectAddress"?: boolean; + /** The additional number and street address of the address. */ + "streetSecondary"?: string; +} + +/** + * Options to pass to each + */ +export interface AddressListInstanceEachOptions { + /** The `customer_name` of the Address resources to read. */ + "customerName"?: string; + /** The string that identifies the Address resources to read. */ + "friendlyName"?: string; + /** Whether the address can be associated to a number for emergency calling. */ + "emergencyEnabled"?: boolean; + /** The ISO country code of the Address resources to read. */ + "isoCountry"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AddressInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AddressListInstanceOptions { + /** The `customer_name` of the Address resources to read. */ + "customerName"?: string; + /** The string that identifies the Address resources to read. */ + "friendlyName"?: string; + /** Whether the address can be associated to a number for emergency calling. */ + "emergencyEnabled"?: boolean; + /** The ISO country code of the Address resources to read. */ + "isoCountry"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AddressListInstancePageOptions { + /** The `customer_name` of the Address resources to read. */ + "customerName"?: string; + /** The string that identifies the Address resources to read. */ + "friendlyName"?: string; + /** Whether the address can be associated to a number for emergency calling. */ + "emergencyEnabled"?: boolean; + /** The ISO country code of the Address resources to read. */ + "isoCountry"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AddressContext { + dependentPhoneNumbers: DependentPhoneNumberListInstance; + + /** + * Remove a AddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a AddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance + */ + fetch(callback?: (error: Error | null, item?: AddressInstance) => any): Promise + + /** + * Fetch a AddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a AddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance + */ + update(callback?: (error: Error | null, item?: AddressInstance) => any): Promise; + /** + * Update a AddressInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance + */ + update(params: AddressContextUpdateOptions, callback?: (error: Error | null, item?: AddressInstance) => any): Promise; + + /** + * Update a AddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AddressInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance with HTTP metadata + */ + updateWithHttpInfo(params: AddressContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AddressContextSolution { + "accountSid": string; + "sid": string; +} + +export class AddressContextImpl implements AddressContext { + protected _solution: AddressContextSolution; + protected _uri: string; + + protected _dependentPhoneNumbers?: DependentPhoneNumberListInstance; + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Addresses/${sid}.json`; + } + + get dependentPhoneNumbers(): DependentPhoneNumberListInstance { + this._dependentPhoneNumbers = this._dependentPhoneNumbers || DependentPhoneNumberListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._dependentPhoneNumbers; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AddressInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AddressInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AddressInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: AddressContextUpdateOptions | ((error: Error | null, item?: AddressInstance) => any),callback?: (error: Error | null, item?: AddressInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["customerName"] !== undefined) + data["CustomerName"] = params["customerName"]; + if (params["street"] !== undefined) + data["Street"] = params["street"]; + if (params["city"] !== undefined) + data["City"] = params["city"]; + if (params["region"] !== undefined) + data["Region"] = params["region"]; + if (params["postalCode"] !== undefined) + data["PostalCode"] = params["postalCode"]; + if (params["emergencyEnabled"] !== undefined) + data["EmergencyEnabled"] = serialize.bool(params["emergencyEnabled"]); + if (params["autoCorrectAddress"] !== undefined) + data["AutoCorrectAddress"] = serialize.bool(params["autoCorrectAddress"]); + if (params["streetSecondary"] !== undefined) + data["StreetSecondary"] = params["streetSecondary"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AddressInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: AddressContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["customerName"] !== undefined) + data["CustomerName"] = params["customerName"]; + if (params["street"] !== undefined) + data["Street"] = params["street"]; + if (params["city"] !== undefined) + data["City"] = params["city"]; + if (params["region"] !== undefined) + data["Region"] = params["region"]; + if (params["postalCode"] !== undefined) + data["PostalCode"] = params["postalCode"]; + if (params["emergencyEnabled"] !== undefined) + data["EmergencyEnabled"] = serialize.bool(params["emergencyEnabled"]); + if (params["autoCorrectAddress"] !== undefined) + data["AutoCorrectAddress"] = serialize.bool(params["autoCorrectAddress"]); + if (params["streetSecondary"] !== undefined) + data["StreetSecondary"] = params["streetSecondary"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AddressInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AddressPayload extends TwilioResponsePayload { + addresses: AddressResource[]; +} + +interface AddressResource { + account_sid: string; + city: string; + customer_name: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + iso_country: string; + postal_code: string; + region: string; + sid: string; + street: string; + uri: string; + emergency_enabled: boolean; + validated: boolean; + verified: boolean; + street_secondary: string; +} + +export class AddressInstance { + protected _solution: AddressContextSolution; + protected _context?: AddressContext; + + constructor(protected _version: V2010, payload: AddressResource, accountSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.city = (payload.city); + this.customerName = (payload.customer_name); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.isoCountry = (payload.iso_country); + this.postalCode = (payload.postal_code); + this.region = (payload.region); + this.sid = (payload.sid); + this.street = (payload.street); + this.uri = (payload.uri); + this.emergencyEnabled = (payload.emergency_enabled); + this.validated = (payload.validated); + this.verified = (payload.verified); + this.streetSecondary = (payload.street_secondary); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is responsible for the Address resource. + */ + accountSid: string; + /** + * The city in which the address is located. + */ + city: string; + /** + * The name associated with the address.This property has a maximum length of 16 4-byte characters, or 21 3-byte characters. + */ + customerName: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The ISO country code of the address. + */ + isoCountry: string; + /** + * The postal code of the address. + */ + postalCode: string; + /** + * The state or region of the address. + */ + region: string; + /** + * The unique string that that we created to identify the Address resource. + */ + sid: string; + /** + * The number and street address of the address. + */ + street: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * Whether emergency calling has been enabled on this number. + */ + emergencyEnabled: boolean; + /** + * Whether the address has been validated to comply with local regulation. In countries that require valid addresses, an invalid address will not be accepted. `true` indicates the Address has been validated. `false` indicate the country doesn\'t require validation or the Address is not valid. + */ + validated: boolean; + /** + * Whether the address has been verified to comply with regulation. In countries that require valid addresses, an invalid address will not be accepted. `true` indicates the Address has been verified. `false` indicate the country doesn\'t require verified or the Address is not valid. + */ + verified: boolean; + /** + * The additional number and street address of the address. + */ + streetSecondary: string; + + private get _proxy(): AddressContext { + this._context = this._context || new AddressContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a AddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance + */ + fetch(callback?: (error: Error | null, item?: AddressInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a AddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance + */ + update(callback?: (error: Error | null, item?: AddressInstance) => any): Promise; + /** + * Update a AddressInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance + */ + update(params: AddressContextUpdateOptions, callback?: (error: Error | null, item?: AddressInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: AddressInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a AddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AddressInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance with HTTP metadata + */ + updateWithHttpInfo(params: AddressContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the dependentPhoneNumbers. + */ + dependentPhoneNumbers(): DependentPhoneNumberListInstance { + return this._proxy.dependentPhoneNumbers; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + city: this.city, + customerName: this.customerName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + isoCountry: this.isoCountry, + postalCode: this.postalCode, + region: this.region, + sid: this.sid, + street: this.street, + uri: this.uri, + emergencyEnabled: this.emergencyEnabled, + validated: this.validated, + verified: this.verified, + streetSecondary: this.streetSecondary, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AddressSolution { + accountSid: string; +} + +export interface AddressListInstance { + _version: V2010; + _solution: AddressSolution; + _uri: string; + + (sid: string, ): AddressContext; + get(sid: string, ): AddressContext; + + + + + + + + + /** + * Create a AddressInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance + */ + create(params: AddressListInstanceCreateOptions, callback?: (error: Error | null, item?: AddressInstance) => any): Promise; + + /** + * Create a AddressInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressInstance with HTTP metadata + */ + createWithHttpInfo(params: AddressListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams AddressInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AddressInstance, done: (err?: Error) => void) => void): void; + each(params: AddressListInstanceEachOptions, callback?: (item: AddressInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AddressInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AddressInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AddressListInstanceEachOptions, callback?: (item: AddressInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AddressInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AddressPage) => any): Promise; + /** + * Retrieve a single target page of AddressInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AddressInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AddressInstance[]) => any): Promise; + list(params: AddressListInstanceOptions, callback?: (error: Error | null, items: AddressInstance[]) => any): Promise; + /** + * Lists AddressInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AddressListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AddressInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AddressPage) => any): Promise; + page(params: AddressListInstancePageOptions, callback?: (error: Error | null, items: AddressPage) => any): Promise; + /** + * Retrieve a single page of AddressInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AddressListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AddressListInstance(version: V2010, accountSid: string): AddressListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as AddressListInstance; + + instance.get = function get(sid, ): AddressContext { + return new AddressContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Addresses.json`; + + instance.create = function create(params: AddressListInstanceCreateOptions, callback?: (error: Error | null, items: AddressInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["customerName"] === null || params["customerName"] === undefined) { + throw new Error('Required parameter "params[\'customerName\']" missing.'); + } + + if (params["street"] === null || params["street"] === undefined) { + throw new Error('Required parameter "params[\'street\']" missing.'); + } + + if (params["city"] === null || params["city"] === undefined) { + throw new Error('Required parameter "params[\'city\']" missing.'); + } + + if (params["region"] === null || params["region"] === undefined) { + throw new Error('Required parameter "params[\'region\']" missing.'); + } + + if (params["postalCode"] === null || params["postalCode"] === undefined) { + throw new Error('Required parameter "params[\'postalCode\']" missing.'); + } + + if (params["isoCountry"] === null || params["isoCountry"] === undefined) { + throw new Error('Required parameter "params[\'isoCountry\']" missing.'); + } + + let data: any = {}; + + + + data["CustomerName"] = params["customerName"]; + + data["Street"] = params["street"]; + + data["City"] = params["city"]; + + data["Region"] = params["region"]; + + data["PostalCode"] = params["postalCode"]; + + data["IsoCountry"] = params["isoCountry"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["emergencyEnabled"] !== undefined) + data["EmergencyEnabled"] = serialize.bool(params["emergencyEnabled"]); + if (params["autoCorrectAddress"] !== undefined) + data["AutoCorrectAddress"] = serialize.bool(params["autoCorrectAddress"]); + if (params["streetSecondary"] !== undefined) + data["StreetSecondary"] = params["streetSecondary"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AddressInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AddressListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["customerName"] === null || params["customerName"] === undefined) { + throw new Error('Required parameter "params[\'customerName\']" missing.'); + } + + if (params["street"] === null || params["street"] === undefined) { + throw new Error('Required parameter "params[\'street\']" missing.'); + } + + if (params["city"] === null || params["city"] === undefined) { + throw new Error('Required parameter "params[\'city\']" missing.'); + } + + if (params["region"] === null || params["region"] === undefined) { + throw new Error('Required parameter "params[\'region\']" missing.'); + } + + if (params["postalCode"] === null || params["postalCode"] === undefined) { + throw new Error('Required parameter "params[\'postalCode\']" missing.'); + } + + if (params["isoCountry"] === null || params["isoCountry"] === undefined) { + throw new Error('Required parameter "params[\'isoCountry\']" missing.'); + } + + let data: any = {}; + + + + data["CustomerName"] = params["customerName"]; + + data["Street"] = params["street"]; + + data["City"] = params["city"]; + + data["Region"] = params["region"]; + + data["PostalCode"] = params["postalCode"]; + + data["IsoCountry"] = params["isoCountry"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["emergencyEnabled"] !== undefined) + data["EmergencyEnabled"] = serialize.bool(params["emergencyEnabled"]); + if (params["autoCorrectAddress"] !== undefined) + data["AutoCorrectAddress"] = serialize.bool(params["autoCorrectAddress"]); + if (params["streetSecondary"] !== undefined) + data["StreetSecondary"] = params["streetSecondary"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AddressInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AddressListInstancePageOptions | ((error: Error | null, items: AddressPage) => any), callback?: (error: Error | null, items: AddressPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["customerName"] !== undefined) + data["CustomerName"] = params["customerName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["emergencyEnabled"] !== undefined) + data["EmergencyEnabled"] = serialize.bool(params["emergencyEnabled"]); + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AddressPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AddressPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AddressPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AddressListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["customerName"] !== undefined) + data["CustomerName"] = params["customerName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["emergencyEnabled"] !== undefined) + data["EmergencyEnabled"] = serialize.bool(params["emergencyEnabled"]); + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AddressPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AddressPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AddressPage extends Page { +/** +* Initialize the AddressPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AddressSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AddressInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AddressResource): AddressInstance { + + return new AddressInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/address/dependentPhoneNumber.ts b/rest/api/v2010/account/address/dependentPhoneNumber.ts new file mode 100644 index 000000000..d8c880157 --- /dev/null +++ b/rest/api/v2010/account/address/dependentPhoneNumber.ts @@ -0,0 +1,569 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * Whether the phone number requires an [Address](https://www.twilio.com/docs/usage/api/address) registered with Twilio. Can be: `none`, `any`, `local`, or `foreign`. + */ +export type DependentPhoneNumberAddressRequirement = 'none'|'any'|'local'|'foreign'; + +/** + * Whether the phone number is enabled for emergency calling. + */ +export type DependentPhoneNumberEmergencyStatus = 'Active'|'Inactive'; + + +/** + * Options to pass to each + */ +export interface DependentPhoneNumberListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DependentPhoneNumberInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DependentPhoneNumberListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DependentPhoneNumberListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface DependentPhoneNumberSolution { + accountSid: string; + addressSid: string; +} + +export interface DependentPhoneNumberListInstance { + _version: V2010; + _solution: DependentPhoneNumberSolution; + _uri: string; + + + + + /** + * Streams DependentPhoneNumberInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentPhoneNumberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DependentPhoneNumberInstance, done: (err?: Error) => void) => void): void; + each(params: DependentPhoneNumberListInstanceEachOptions, callback?: (item: DependentPhoneNumberInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DependentPhoneNumberInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentPhoneNumberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DependentPhoneNumberInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DependentPhoneNumberListInstanceEachOptions, callback?: (item: DependentPhoneNumberInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DependentPhoneNumberInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DependentPhoneNumberPage) => any): Promise; + /** + * Retrieve a single target page of DependentPhoneNumberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists DependentPhoneNumberInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentPhoneNumberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DependentPhoneNumberInstance[]) => any): Promise; + list(params: DependentPhoneNumberListInstanceOptions, callback?: (error: Error | null, items: DependentPhoneNumberInstance[]) => any): Promise; + /** + * Lists DependentPhoneNumberInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentPhoneNumberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: DependentPhoneNumberListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of DependentPhoneNumberInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentPhoneNumberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DependentPhoneNumberPage) => any): Promise; + page(params: DependentPhoneNumberListInstancePageOptions, callback?: (error: Error | null, items: DependentPhoneNumberPage) => any): Promise; + /** + * Retrieve a single page of DependentPhoneNumberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentPhoneNumberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: DependentPhoneNumberListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DependentPhoneNumberListInstance(version: V2010, accountSid: string, addressSid: string): DependentPhoneNumberListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(addressSid)) { + throw new Error('Parameter \'addressSid\' is not valid.'); + } + + const instance = {} as DependentPhoneNumberListInstance; + + instance._version = version; + instance._solution = { accountSid, addressSid, }; + instance._uri = `/Accounts/${accountSid}/Addresses/${addressSid}/DependentPhoneNumbers.json`; + + instance.page = function page(params?: DependentPhoneNumberListInstancePageOptions | ((error: Error | null, items: DependentPhoneNumberPage) => any), callback?: (error: Error | null, items: DependentPhoneNumberPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DependentPhoneNumberPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DependentPhoneNumberPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DependentPhoneNumberPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DependentPhoneNumberListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DependentPhoneNumberPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DependentPhoneNumberPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface DependentPhoneNumberPayload extends TwilioResponsePayload { + dependent_phone_numbers: DependentPhoneNumberResource[]; +} + +interface DependentPhoneNumberResource { + sid: string; + account_sid: string; + friendly_name: string; + phone_number: string; + voice_url: string; + voice_method: string; + voice_fallback_method: string; + voice_fallback_url: string; + voice_caller_id_lookup: boolean; + date_created: Date; + date_updated: Date; + sms_fallback_method: string; + sms_fallback_url: string; + sms_method: string; + sms_url: string; + address_requirements: DependentPhoneNumberAddressRequirement; + capabilities: any; + status_callback: string; + status_callback_method: string; + api_version: string; + sms_application_sid: string; + voice_application_sid: string; + trunk_sid: string; + emergency_status: DependentPhoneNumberEmergencyStatus; + emergency_address_sid: string; + uri: string; +} + +export class DependentPhoneNumberInstance { + + constructor(protected _version: V2010, payload: DependentPhoneNumberResource, accountSid: string, addressSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.phoneNumber = (payload.phone_number); + this.voiceUrl = (payload.voice_url); + this.voiceMethod = (payload.voice_method); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceCallerIdLookup = (payload.voice_caller_id_lookup); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.smsFallbackMethod = (payload.sms_fallback_method); + this.smsFallbackUrl = (payload.sms_fallback_url); + this.smsMethod = (payload.sms_method); + this.smsUrl = (payload.sms_url); + this.addressRequirements = payload.address_requirements; + this.capabilities = (payload.capabilities); + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.apiVersion = (payload.api_version); + this.smsApplicationSid = (payload.sms_application_sid); + this.voiceApplicationSid = (payload.voice_application_sid); + this.trunkSid = (payload.trunk_sid); + this.emergencyStatus = payload.emergency_status; + this.emergencyAddressSid = (payload.emergency_address_sid); + this.uri = (payload.uri); + + } + + /** + * The unique string that that we created to identify the DependentPhoneNumber resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DependentPhoneNumber resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + */ + voiceUrl: string; + /** + * The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + */ + voiceMethod: string; + /** + * The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + */ + voiceFallbackMethod: string; + /** + * The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + */ + voiceFallbackUrl: string; + /** + * Whether we look up the caller\'s caller-ID name from the CNAM database. Can be: `true` or `false`. Caller ID lookups can cost $0.01 each. + */ + voiceCallerIdLookup: boolean; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + */ + smsFallbackMethod: string; + /** + * The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + */ + smsFallbackUrl: string; + /** + * The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + */ + smsMethod: string; + /** + * The URL we call when the phone number receives an incoming SMS message. + */ + smsUrl: string; + addressRequirements: DependentPhoneNumberAddressRequirement; + /** + * The set of Boolean properties that indicates whether a phone number can receive calls or messages. Capabilities are `Voice`, `SMS`, and `MMS` and each capability can be: `true` or `false`. + */ + capabilities: any; + /** + * The URL we call using the `status_callback_method` to send status information to your application. + */ + statusCallback: string; + /** + * The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + */ + statusCallbackMethod: string; + /** + * The API version used to start a new TwiML session. + */ + apiVersion: string; + /** + * The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + */ + smsApplicationSid: string; + /** + * The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + */ + voiceApplicationSid: string; + /** + * The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + */ + trunkSid: string; + emergencyStatus: DependentPhoneNumberEmergencyStatus; + /** + * The SID of the emergency address configuration that we use for emergency calling from the phone number. + */ + emergencyAddressSid: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + phoneNumber: this.phoneNumber, + voiceUrl: this.voiceUrl, + voiceMethod: this.voiceMethod, + voiceFallbackMethod: this.voiceFallbackMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceCallerIdLookup: this.voiceCallerIdLookup, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + smsFallbackMethod: this.smsFallbackMethod, + smsFallbackUrl: this.smsFallbackUrl, + smsMethod: this.smsMethod, + smsUrl: this.smsUrl, + addressRequirements: this.addressRequirements, + capabilities: this.capabilities, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + apiVersion: this.apiVersion, + smsApplicationSid: this.smsApplicationSid, + voiceApplicationSid: this.voiceApplicationSid, + trunkSid: this.trunkSid, + emergencyStatus: this.emergencyStatus, + emergencyAddressSid: this.emergencyAddressSid, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class DependentPhoneNumberPage extends Page { +/** +* Initialize the DependentPhoneNumberPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: DependentPhoneNumberSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DependentPhoneNumberInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DependentPhoneNumberResource): DependentPhoneNumberInstance { + + return new DependentPhoneNumberInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.addressSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/application.ts b/rest/api/v2010/account/application.ts new file mode 100644 index 000000000..d6c6ad117 --- /dev/null +++ b/rest/api/v2010/account/application.ts @@ -0,0 +1,1209 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a ApplicationInstance + */ +export interface ApplicationContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account\\\'s default API version. */ + "apiVersion"?: string; + /** The URL we should call when the phone number assigned to this application receives a call. */ + "voiceUrl"?: string; + /** The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. */ + "voiceMethod"?: string; + /** The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. */ + "statusCallbackMethod"?: string; + /** Whether we should look up the caller\\\'s caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. */ + "voiceCallerIdLookup"?: boolean; + /** The URL we should call when the phone number receives an incoming SMS message. */ + "smsUrl"?: string; + /** The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. */ + "smsMethod"?: string; + /** The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. */ + "smsFallbackUrl"?: string; + /** The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. */ + "smsFallbackMethod"?: string; + /** Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. */ + "smsStatusCallback"?: string; + /** The URL we should call using a POST method to send message status information to your application. */ + "messageStatusCallback"?: string; + /** Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. */ + "publicApplicationConnectEnabled"?: boolean; +} + +/** + * Options to pass to create a ApplicationInstance + */ +export interface ApplicationListInstanceCreateOptions { + /** The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account\\\'s default API version. */ + "apiVersion"?: string; + /** The URL we should call when the phone number assigned to this application receives a call. */ + "voiceUrl"?: string; + /** The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. */ + "voiceMethod"?: string; + /** The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. */ + "statusCallbackMethod"?: string; + /** Whether we should look up the caller\\\'s caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. */ + "voiceCallerIdLookup"?: boolean; + /** The URL we should call when the phone number receives an incoming SMS message. */ + "smsUrl"?: string; + /** The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. */ + "smsMethod"?: string; + /** The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. */ + "smsFallbackUrl"?: string; + /** The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. */ + "smsFallbackMethod"?: string; + /** The URL we should call using a POST method to send status information about SMS messages sent by the application. */ + "smsStatusCallback"?: string; + /** The URL we should call using a POST method to send message status information to your application. */ + "messageStatusCallback"?: string; + /** A descriptive string that you create to describe the new application. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. */ + "publicApplicationConnectEnabled"?: boolean; +} + +/** + * Options to pass to each + */ +export interface ApplicationListInstanceEachOptions { + /** The string that identifies the Application resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ApplicationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ApplicationListInstanceOptions { + /** The string that identifies the Application resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ApplicationListInstancePageOptions { + /** The string that identifies the Application resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ApplicationContext { + + /** + * Remove a ApplicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ApplicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ApplicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + fetch(callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise + + /** + * Fetch a ApplicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ApplicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + update(callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise; + /** + * Update a ApplicationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + update(params: ApplicationContextUpdateOptions, callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise; + + /** + * Update a ApplicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ApplicationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ApplicationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ApplicationContextSolution { + "accountSid": string; + "sid": string; +} + +export class ApplicationContextImpl implements ApplicationContext { + protected _solution: ApplicationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Applications/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ApplicationInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ApplicationInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ApplicationContextUpdateOptions | ((error: Error | null, item?: ApplicationInstance) => any),callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsStatusCallback"] !== undefined) + data["SmsStatusCallback"] = params["smsStatusCallback"]; + if (params["messageStatusCallback"] !== undefined) + data["MessageStatusCallback"] = params["messageStatusCallback"]; + if (params["publicApplicationConnectEnabled"] !== undefined) + data["PublicApplicationConnectEnabled"] = serialize.bool(params["publicApplicationConnectEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ApplicationInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ApplicationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsStatusCallback"] !== undefined) + data["SmsStatusCallback"] = params["smsStatusCallback"]; + if (params["messageStatusCallback"] !== undefined) + data["MessageStatusCallback"] = params["messageStatusCallback"]; + if (params["publicApplicationConnectEnabled"] !== undefined) + data["PublicApplicationConnectEnabled"] = serialize.bool(params["publicApplicationConnectEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ApplicationInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ApplicationPayload extends TwilioResponsePayload { + applications: ApplicationResource[]; +} + +interface ApplicationResource { + account_sid: string; + api_version: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + message_status_callback: string; + sid: string; + sms_fallback_method: string; + sms_fallback_url: string; + sms_method: string; + sms_status_callback: string; + sms_url: string; + status_callback: string; + status_callback_method: string; + uri: string; + voice_caller_id_lookup: boolean; + voice_fallback_method: string; + voice_fallback_url: string; + voice_method: string; + voice_url: string; + public_application_connect_enabled: boolean; +} + +export class ApplicationInstance { + protected _solution: ApplicationContextSolution; + protected _context?: ApplicationContext; + + constructor(protected _version: V2010, payload: ApplicationResource, accountSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.messageStatusCallback = (payload.message_status_callback); + this.sid = (payload.sid); + this.smsFallbackMethod = (payload.sms_fallback_method); + this.smsFallbackUrl = (payload.sms_fallback_url); + this.smsMethod = (payload.sms_method); + this.smsStatusCallback = (payload.sms_status_callback); + this.smsUrl = (payload.sms_url); + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.uri = (payload.uri); + this.voiceCallerIdLookup = (payload.voice_caller_id_lookup); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceMethod = (payload.voice_method); + this.voiceUrl = (payload.voice_url); + this.publicApplicationConnectEnabled = (payload.public_application_connect_enabled); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Application resource. + */ + accountSid: string; + /** + * The API version used to start a new TwiML session. + */ + apiVersion: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The URL we call using a POST method to send message status information to your application. + */ + messageStatusCallback: string; + /** + * The unique string that that we created to identify the Application resource. + */ + sid: string; + /** + * The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + */ + smsFallbackMethod: string; + /** + * The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + */ + smsFallbackUrl: string; + /** + * The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + */ + smsMethod: string; + /** + * The URL we call using a POST method to send status information to your application about SMS messages that refer to the application. + */ + smsStatusCallback: string; + /** + * The URL we call when the phone number receives an incoming SMS message. + */ + smsUrl: string; + /** + * The URL we call using the `status_callback_method` to send status information to your application. + */ + statusCallback: string; + /** + * The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + */ + statusCallbackMethod: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * Whether we look up the caller\'s caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + */ + voiceCallerIdLookup: boolean; + /** + * The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + */ + voiceFallbackMethod: string; + /** + * The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + */ + voiceFallbackUrl: string; + /** + * The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + */ + voiceMethod: string; + /** + * The URL we call when the phone number assigned to this application receives a call. + */ + voiceUrl: string; + /** + * Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + */ + publicApplicationConnectEnabled: boolean; + + private get _proxy(): ApplicationContext { + this._context = this._context || new ApplicationContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ApplicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ApplicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ApplicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + fetch(callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ApplicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ApplicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + update(callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise; + /** + * Update a ApplicationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + update(params: ApplicationContextUpdateOptions, callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ApplicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ApplicationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ApplicationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + messageStatusCallback: this.messageStatusCallback, + sid: this.sid, + smsFallbackMethod: this.smsFallbackMethod, + smsFallbackUrl: this.smsFallbackUrl, + smsMethod: this.smsMethod, + smsStatusCallback: this.smsStatusCallback, + smsUrl: this.smsUrl, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + uri: this.uri, + voiceCallerIdLookup: this.voiceCallerIdLookup, + voiceFallbackMethod: this.voiceFallbackMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceMethod: this.voiceMethod, + voiceUrl: this.voiceUrl, + publicApplicationConnectEnabled: this.publicApplicationConnectEnabled, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ApplicationSolution { + accountSid: string; +} + +export interface ApplicationListInstance { + _version: V2010; + _solution: ApplicationSolution; + _uri: string; + + (sid: string, ): ApplicationContext; + get(sid: string, ): ApplicationContext; + + + + + + + + + /** + * Create a ApplicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + create(callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise; + /** + * Create a ApplicationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + create(params: ApplicationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise; + + /** + * Create a ApplicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ApplicationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + createWithHttpInfo(params: ApplicationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ApplicationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ApplicationInstance, done: (err?: Error) => void) => void): void; + each(params: ApplicationListInstanceEachOptions, callback?: (item: ApplicationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ApplicationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ApplicationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ApplicationListInstanceEachOptions, callback?: (item: ApplicationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ApplicationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ApplicationPage) => any): Promise; + /** + * Retrieve a single target page of ApplicationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ApplicationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ApplicationInstance[]) => any): Promise; + list(params: ApplicationListInstanceOptions, callback?: (error: Error | null, items: ApplicationInstance[]) => any): Promise; + /** + * Lists ApplicationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ApplicationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ApplicationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ApplicationPage) => any): Promise; + page(params: ApplicationListInstancePageOptions, callback?: (error: Error | null, items: ApplicationPage) => any): Promise; + /** + * Retrieve a single page of ApplicationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ApplicationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ApplicationListInstance(version: V2010, accountSid: string): ApplicationListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ApplicationListInstance; + + instance.get = function get(sid, ): ApplicationContext { + return new ApplicationContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Applications.json`; + + instance.create = function create(params?: ApplicationListInstanceCreateOptions | ((error: Error | null, items: ApplicationInstance) => any), callback?: (error: Error | null, items: ApplicationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsStatusCallback"] !== undefined) + data["SmsStatusCallback"] = params["smsStatusCallback"]; + if (params["messageStatusCallback"] !== undefined) + data["MessageStatusCallback"] = params["messageStatusCallback"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["publicApplicationConnectEnabled"] !== undefined) + data["PublicApplicationConnectEnabled"] = serialize.bool(params["publicApplicationConnectEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ApplicationInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ApplicationListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsStatusCallback"] !== undefined) + data["SmsStatusCallback"] = params["smsStatusCallback"]; + if (params["messageStatusCallback"] !== undefined) + data["MessageStatusCallback"] = params["messageStatusCallback"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["publicApplicationConnectEnabled"] !== undefined) + data["PublicApplicationConnectEnabled"] = serialize.bool(params["publicApplicationConnectEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ApplicationInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ApplicationListInstancePageOptions | ((error: Error | null, items: ApplicationPage) => any), callback?: (error: Error | null, items: ApplicationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ApplicationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ApplicationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ApplicationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ApplicationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ApplicationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ApplicationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ApplicationPage extends Page { +/** +* Initialize the ApplicationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: ApplicationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ApplicationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ApplicationResource): ApplicationInstance { + + return new ApplicationInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/authorizedConnectApp.ts b/rest/api/v2010/account/authorizedConnectApp.ts new file mode 100644 index 000000000..173c8c77d --- /dev/null +++ b/rest/api/v2010/account/authorizedConnectApp.ts @@ -0,0 +1,581 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The set of permissions that you authorized for the Connect App. Can be: `get-all` or `post-all`. + */ +export type AuthorizedConnectAppPermission = 'get-all'|'post-all'; + + + +/** + * Options to pass to each + */ +export interface AuthorizedConnectAppListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AuthorizedConnectAppInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AuthorizedConnectAppListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AuthorizedConnectAppListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AuthorizedConnectAppContext { + + /** + * Fetch a AuthorizedConnectAppInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizedConnectAppInstance + */ + fetch(callback?: (error: Error | null, item?: AuthorizedConnectAppInstance) => any): Promise + + /** + * Fetch a AuthorizedConnectAppInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizedConnectAppInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AuthorizedConnectAppContextSolution { + "accountSid": string; + "connectAppSid": string; +} + +export class AuthorizedConnectAppContextImpl implements AuthorizedConnectAppContext { + protected _solution: AuthorizedConnectAppContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, connectAppSid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(connectAppSid)) { + throw new Error('Parameter \'connectAppSid\' is not valid.'); + } + + this._solution = { accountSid, connectAppSid, }; + this._uri = `/Accounts/${accountSid}/AuthorizedConnectApps/${connectAppSid}.json`; + } + + fetch(callback?: (error: Error | null, item?: AuthorizedConnectAppInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AuthorizedConnectAppInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.connectAppSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AuthorizedConnectAppInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.connectAppSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AuthorizedConnectAppPayload extends TwilioResponsePayload { + authorized_connect_apps: AuthorizedConnectAppResource[]; +} + +interface AuthorizedConnectAppResource { + account_sid: string; + connect_app_company_name: string; + connect_app_description: string; + connect_app_friendly_name: string; + connect_app_homepage_url: string; + connect_app_sid: string; + permissions: Array; + uri: string; +} + +export class AuthorizedConnectAppInstance { + protected _solution: AuthorizedConnectAppContextSolution; + protected _context?: AuthorizedConnectAppContext; + + constructor(protected _version: V2010, payload: AuthorizedConnectAppResource, accountSid: string, connectAppSid?: string) { + + this.accountSid = (payload.account_sid); + this.connectAppCompanyName = (payload.connect_app_company_name); + this.connectAppDescription = (payload.connect_app_description); + this.connectAppFriendlyName = (payload.connect_app_friendly_name); + this.connectAppHomepageUrl = (payload.connect_app_homepage_url); + this.connectAppSid = (payload.connect_app_sid); + this.permissions = (payload.permissions); + this.uri = (payload.uri); + + this._solution = { accountSid, connectAppSid: connectAppSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AuthorizedConnectApp resource. + */ + accountSid: string; + /** + * The company name set for the Connect App. + */ + connectAppCompanyName: string; + /** + * A detailed description of the Connect App. + */ + connectAppDescription: string; + /** + * The name of the Connect App. + */ + connectAppFriendlyName: string; + /** + * The public URL for the Connect App. + */ + connectAppHomepageUrl: string; + /** + * The SID that we assigned to the Connect App. + */ + connectAppSid: string; + /** + * The set of permissions that you authorized for the Connect App. Can be: `get-all` or `post-all`. + */ + permissions: Array; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): AuthorizedConnectAppContext { + this._context = this._context || new AuthorizedConnectAppContextImpl(this._version, this._solution.accountSid, this._solution.connectAppSid); + return this._context; + } + + /** + * Fetch a AuthorizedConnectAppInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizedConnectAppInstance + */ + fetch(callback?: (error: Error | null, item?: AuthorizedConnectAppInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AuthorizedConnectAppInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizedConnectAppInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + connectAppCompanyName: this.connectAppCompanyName, + connectAppDescription: this.connectAppDescription, + connectAppFriendlyName: this.connectAppFriendlyName, + connectAppHomepageUrl: this.connectAppHomepageUrl, + connectAppSid: this.connectAppSid, + permissions: this.permissions, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AuthorizedConnectAppSolution { + accountSid: string; +} + +export interface AuthorizedConnectAppListInstance { + _version: V2010; + _solution: AuthorizedConnectAppSolution; + _uri: string; + + (connectAppSid: string, ): AuthorizedConnectAppContext; + get(connectAppSid: string, ): AuthorizedConnectAppContext; + + + + + + /** + * Streams AuthorizedConnectAppInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizedConnectAppListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AuthorizedConnectAppInstance, done: (err?: Error) => void) => void): void; + each(params: AuthorizedConnectAppListInstanceEachOptions, callback?: (item: AuthorizedConnectAppInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AuthorizedConnectAppInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizedConnectAppListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AuthorizedConnectAppInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AuthorizedConnectAppListInstanceEachOptions, callback?: (item: AuthorizedConnectAppInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AuthorizedConnectAppInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AuthorizedConnectAppPage) => any): Promise; + /** + * Retrieve a single target page of AuthorizedConnectAppInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AuthorizedConnectAppInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizedConnectAppListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AuthorizedConnectAppInstance[]) => any): Promise; + list(params: AuthorizedConnectAppListInstanceOptions, callback?: (error: Error | null, items: AuthorizedConnectAppInstance[]) => any): Promise; + /** + * Lists AuthorizedConnectAppInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizedConnectAppListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AuthorizedConnectAppListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AuthorizedConnectAppInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizedConnectAppListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AuthorizedConnectAppPage) => any): Promise; + page(params: AuthorizedConnectAppListInstancePageOptions, callback?: (error: Error | null, items: AuthorizedConnectAppPage) => any): Promise; + /** + * Retrieve a single page of AuthorizedConnectAppInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizedConnectAppListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AuthorizedConnectAppListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AuthorizedConnectAppListInstance(version: V2010, accountSid: string): AuthorizedConnectAppListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((connectAppSid, ) => instance.get(connectAppSid, )) as AuthorizedConnectAppListInstance; + + instance.get = function get(connectAppSid, ): AuthorizedConnectAppContext { + return new AuthorizedConnectAppContextImpl(version, accountSid, connectAppSid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/AuthorizedConnectApps.json`; + + instance.page = function page(params?: AuthorizedConnectAppListInstancePageOptions | ((error: Error | null, items: AuthorizedConnectAppPage) => any), callback?: (error: Error | null, items: AuthorizedConnectAppPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AuthorizedConnectAppPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AuthorizedConnectAppPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AuthorizedConnectAppPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AuthorizedConnectAppListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthorizedConnectAppPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthorizedConnectAppPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AuthorizedConnectAppPage extends Page { +/** +* Initialize the AuthorizedConnectAppPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AuthorizedConnectAppSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AuthorizedConnectAppInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AuthorizedConnectAppResource): AuthorizedConnectAppInstance { + + return new AuthorizedConnectAppInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/availablePhoneNumberCountry.ts b/rest/api/v2010/account/availablePhoneNumberCountry.ts new file mode 100644 index 000000000..27fa84da8 --- /dev/null +++ b/rest/api/v2010/account/availablePhoneNumberCountry.ts @@ -0,0 +1,660 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { LocalListInstance } from "./availablePhoneNumberCountry/local"; +import { MachineToMachineListInstance } from "./availablePhoneNumberCountry/machineToMachine"; +import { MobileListInstance } from "./availablePhoneNumberCountry/mobile"; +import { NationalListInstance } from "./availablePhoneNumberCountry/national"; +import { SharedCostListInstance } from "./availablePhoneNumberCountry/sharedCost"; +import { TollFreeListInstance } from "./availablePhoneNumberCountry/tollFree"; +import { VoipListInstance } from "./availablePhoneNumberCountry/voip"; + + + + +/** + * Options to pass to each + */ +export interface AvailablePhoneNumberCountryListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AvailablePhoneNumberCountryInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AvailablePhoneNumberCountryListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AvailablePhoneNumberCountryListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AvailablePhoneNumberCountryContext { + local: LocalListInstance; + machineToMachine: MachineToMachineListInstance; + mobile: MobileListInstance; + national: NationalListInstance; + sharedCost: SharedCostListInstance; + tollFree: TollFreeListInstance; + voip: VoipListInstance; + + /** + * Fetch a AvailablePhoneNumberCountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailablePhoneNumberCountryInstance + */ + fetch(callback?: (error: Error | null, item?: AvailablePhoneNumberCountryInstance) => any): Promise + + /** + * Fetch a AvailablePhoneNumberCountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailablePhoneNumberCountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AvailablePhoneNumberCountryContextSolution { + "accountSid": string; + "countryCode": string; +} + +export class AvailablePhoneNumberCountryContextImpl implements AvailablePhoneNumberCountryContext { + protected _solution: AvailablePhoneNumberCountryContextSolution; + protected _uri: string; + + protected _local?: LocalListInstance; + protected _machineToMachine?: MachineToMachineListInstance; + protected _mobile?: MobileListInstance; + protected _national?: NationalListInstance; + protected _sharedCost?: SharedCostListInstance; + protected _tollFree?: TollFreeListInstance; + protected _voip?: VoipListInstance; + + constructor(protected _version: V2010, accountSid: string, countryCode: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(countryCode)) { + throw new Error('Parameter \'countryCode\' is not valid.'); + } + + this._solution = { accountSid, countryCode, }; + this._uri = `/Accounts/${accountSid}/AvailablePhoneNumbers/${countryCode}.json`; + } + + get local(): LocalListInstance { + this._local = this._local || LocalListInstance(this._version, this._solution.accountSid, this._solution.countryCode); + return this._local; + } + + get machineToMachine(): MachineToMachineListInstance { + this._machineToMachine = this._machineToMachine || MachineToMachineListInstance(this._version, this._solution.accountSid, this._solution.countryCode); + return this._machineToMachine; + } + + get mobile(): MobileListInstance { + this._mobile = this._mobile || MobileListInstance(this._version, this._solution.accountSid, this._solution.countryCode); + return this._mobile; + } + + get national(): NationalListInstance { + this._national = this._national || NationalListInstance(this._version, this._solution.accountSid, this._solution.countryCode); + return this._national; + } + + get sharedCost(): SharedCostListInstance { + this._sharedCost = this._sharedCost || SharedCostListInstance(this._version, this._solution.accountSid, this._solution.countryCode); + return this._sharedCost; + } + + get tollFree(): TollFreeListInstance { + this._tollFree = this._tollFree || TollFreeListInstance(this._version, this._solution.accountSid, this._solution.countryCode); + return this._tollFree; + } + + get voip(): VoipListInstance { + this._voip = this._voip || VoipListInstance(this._version, this._solution.accountSid, this._solution.countryCode); + return this._voip; + } + + fetch(callback?: (error: Error | null, item?: AvailablePhoneNumberCountryInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AvailablePhoneNumberCountryInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.countryCode)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AvailablePhoneNumberCountryInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.countryCode) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AvailablePhoneNumberCountryPayload extends TwilioResponsePayload { + countries: AvailablePhoneNumberCountryResource[]; +} + +interface AvailablePhoneNumberCountryResource { + country_code: string; + country: string; + uri: string; + beta: boolean; + subresource_uris: Record; +} + +export class AvailablePhoneNumberCountryInstance { + protected _solution: AvailablePhoneNumberCountryContextSolution; + protected _context?: AvailablePhoneNumberCountryContext; + + constructor(protected _version: V2010, payload: AvailablePhoneNumberCountryResource, accountSid: string, countryCode?: string) { + + this.countryCode = (payload.country_code); + this.country = (payload.country); + this.uri = (payload.uri); + this.beta = (payload.beta); + this.subresourceUris = (payload.subresource_uris); + + this._solution = { accountSid, countryCode: countryCode, }; + } + + /** + * The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country. + */ + countryCode: string; + /** + * The name of the country. + */ + country: string; + /** + * The URI of the Country resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * Whether all phone numbers available in the country are new to the Twilio platform. `true` if they are and `false` if all numbers are not in the Twilio Phone Number Beta program. + */ + beta: boolean; + /** + * A list of related AvailablePhoneNumber resources identified by their URIs relative to `https://api.twilio.com`. + */ + subresourceUris: Record; + + private get _proxy(): AvailablePhoneNumberCountryContext { + this._context = this._context || new AvailablePhoneNumberCountryContextImpl(this._version, this._solution.accountSid, this._solution.countryCode); + return this._context; + } + + /** + * Fetch a AvailablePhoneNumberCountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailablePhoneNumberCountryInstance + */ + fetch(callback?: (error: Error | null, item?: AvailablePhoneNumberCountryInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AvailablePhoneNumberCountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailablePhoneNumberCountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the local. + */ + local(): LocalListInstance { + return this._proxy.local; + } + + /** + * Access the machineToMachine. + */ + machineToMachine(): MachineToMachineListInstance { + return this._proxy.machineToMachine; + } + + /** + * Access the mobile. + */ + mobile(): MobileListInstance { + return this._proxy.mobile; + } + + /** + * Access the national. + */ + national(): NationalListInstance { + return this._proxy.national; + } + + /** + * Access the sharedCost. + */ + sharedCost(): SharedCostListInstance { + return this._proxy.sharedCost; + } + + /** + * Access the tollFree. + */ + tollFree(): TollFreeListInstance { + return this._proxy.tollFree; + } + + /** + * Access the voip. + */ + voip(): VoipListInstance { + return this._proxy.voip; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + countryCode: this.countryCode, + country: this.country, + uri: this.uri, + beta: this.beta, + subresourceUris: this.subresourceUris, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AvailablePhoneNumberCountrySolution { + accountSid: string; +} + +export interface AvailablePhoneNumberCountryListInstance { + _version: V2010; + _solution: AvailablePhoneNumberCountrySolution; + _uri: string; + + (countryCode: string, ): AvailablePhoneNumberCountryContext; + get(countryCode: string, ): AvailablePhoneNumberCountryContext; + + + + + + /** + * Streams AvailablePhoneNumberCountryInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailablePhoneNumberCountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AvailablePhoneNumberCountryInstance, done: (err?: Error) => void) => void): void; + each(params: AvailablePhoneNumberCountryListInstanceEachOptions, callback?: (item: AvailablePhoneNumberCountryInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AvailablePhoneNumberCountryInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailablePhoneNumberCountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AvailablePhoneNumberCountryInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AvailablePhoneNumberCountryListInstanceEachOptions, callback?: (item: AvailablePhoneNumberCountryInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AvailablePhoneNumberCountryInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AvailablePhoneNumberCountryPage) => any): Promise; + /** + * Retrieve a single target page of AvailablePhoneNumberCountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AvailablePhoneNumberCountryInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailablePhoneNumberCountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AvailablePhoneNumberCountryInstance[]) => any): Promise; + list(params: AvailablePhoneNumberCountryListInstanceOptions, callback?: (error: Error | null, items: AvailablePhoneNumberCountryInstance[]) => any): Promise; + /** + * Lists AvailablePhoneNumberCountryInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailablePhoneNumberCountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AvailablePhoneNumberCountryListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AvailablePhoneNumberCountryInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailablePhoneNumberCountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AvailablePhoneNumberCountryPage) => any): Promise; + page(params: AvailablePhoneNumberCountryListInstancePageOptions, callback?: (error: Error | null, items: AvailablePhoneNumberCountryPage) => any): Promise; + /** + * Retrieve a single page of AvailablePhoneNumberCountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailablePhoneNumberCountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AvailablePhoneNumberCountryListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AvailablePhoneNumberCountryListInstance(version: V2010, accountSid: string): AvailablePhoneNumberCountryListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((countryCode, ) => instance.get(countryCode, )) as AvailablePhoneNumberCountryListInstance; + + instance.get = function get(countryCode, ): AvailablePhoneNumberCountryContext { + return new AvailablePhoneNumberCountryContextImpl(version, accountSid, countryCode); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/AvailablePhoneNumbers.json`; + + instance.page = function page(params?: AvailablePhoneNumberCountryListInstancePageOptions | ((error: Error | null, items: AvailablePhoneNumberCountryPage) => any), callback?: (error: Error | null, items: AvailablePhoneNumberCountryPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AvailablePhoneNumberCountryPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AvailablePhoneNumberCountryPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AvailablePhoneNumberCountryPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AvailablePhoneNumberCountryListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AvailablePhoneNumberCountryPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AvailablePhoneNumberCountryPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AvailablePhoneNumberCountryPage extends Page { +/** +* Initialize the AvailablePhoneNumberCountryPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AvailablePhoneNumberCountrySolution) { + super(version, response, solution); + } + + /** + * Build an instance of AvailablePhoneNumberCountryInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AvailablePhoneNumberCountryResource): AvailablePhoneNumberCountryInstance { + + return new AvailablePhoneNumberCountryInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/availablePhoneNumberCountry/local.ts b/rest/api/v2010/account/availablePhoneNumberCountry/local.ts new file mode 100644 index 000000000..5b78f1283 --- /dev/null +++ b/rest/api/v2010/account/availablePhoneNumberCountry/local.ts @@ -0,0 +1,652 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../../interfaces"; + + + +/** + * Options to pass to each + */ +export interface LocalListInstanceEachOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: LocalInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface LocalListInstanceOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface LocalListInstancePageOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface LocalSolution { + accountSid: string; + countryCode: string; +} + +export interface LocalListInstance { + _version: V2010; + _solution: LocalSolution; + _uri: string; + + + + + /** + * Streams LocalInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: LocalInstance, done: (err?: Error) => void) => void): void; + each(params: LocalListInstanceEachOptions, callback?: (item: LocalInstance, done: (err?: Error) => void) => void): void; + /** + * Streams LocalInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: LocalInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: LocalListInstanceEachOptions, callback?: (item: LocalInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of LocalInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: LocalPage) => any): Promise; + /** + * Retrieve a single target page of LocalInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists LocalInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: LocalInstance[]) => any): Promise; + list(params: LocalListInstanceOptions, callback?: (error: Error | null, items: LocalInstance[]) => any): Promise; + /** + * Lists LocalInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: LocalListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of LocalInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: LocalPage) => any): Promise; + page(params: LocalListInstancePageOptions, callback?: (error: Error | null, items: LocalPage) => any): Promise; + /** + * Retrieve a single page of LocalInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: LocalListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function LocalListInstance(version: V2010, accountSid: string, countryCode: string): LocalListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(countryCode)) { + throw new Error('Parameter \'countryCode\' is not valid.'); + } + + const instance = {} as LocalListInstance; + + instance._version = version; + instance._solution = { accountSid, countryCode, }; + instance._uri = `/Accounts/${accountSid}/AvailablePhoneNumbers/${countryCode}/Local.json`; + + instance.page = function page(params?: LocalListInstancePageOptions | ((error: Error | null, items: LocalPage) => any), callback?: (error: Error | null, items: LocalPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new LocalPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: LocalPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new LocalPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: LocalListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new LocalPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new LocalPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface LocalPayload extends TwilioResponsePayload { + available_phone_numbers: LocalResource[]; +} + +interface LocalResource { + friendly_name: string; + phone_number: string; + lata: string; + locality: string; + rate_center: string; + latitude: number; + longitude: number; + region: string; + postal_code: string; + iso_country: string; + address_requirements: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; +} + +export class LocalInstance { + + constructor(protected _version: V2010, payload: LocalResource, accountSid: string, countryCode: string) { + + this.friendlyName = (payload.friendly_name); + this.phoneNumber = (payload.phone_number); + this.lata = (payload.lata); + this.locality = (payload.locality); + this.rateCenter = (payload.rate_center); + this.latitude = (payload.latitude); + this.longitude = (payload.longitude); + this.region = (payload.region); + this.postalCode = (payload.postal_code); + this.isoCountry = (payload.iso_country); + this.addressRequirements = (payload.address_requirements); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + + } + + /** + * A formatted version of the phone number. + */ + friendlyName: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + */ + lata: string; + /** + * The locality or city of this phone number\'s location. + */ + locality: string; + /** + * The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + */ + rateCenter: string; + /** + * The latitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + latitude: number; + /** + * The longitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + longitude: number; + /** + * The two-letter state or province abbreviation of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + region: string; + /** + * The postal or ZIP code of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + postalCode: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + */ + isoCountry: string; + /** + * The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number\'s country is required. `foreign` means an address outside of the phone number\'s country is required. + */ + addressRequirements: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + friendlyName: this.friendlyName, + phoneNumber: this.phoneNumber, + lata: this.lata, + locality: this.locality, + rateCenter: this.rateCenter, + latitude: this.latitude, + longitude: this.longitude, + region: this.region, + postalCode: this.postalCode, + isoCountry: this.isoCountry, + addressRequirements: this.addressRequirements, + beta: this.beta, + capabilities: this.capabilities, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class LocalPage extends Page { +/** +* Initialize the LocalPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: LocalSolution) { + super(version, response, solution); + } + + /** + * Build an instance of LocalInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: LocalResource): LocalInstance { + + return new LocalInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.countryCode, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/availablePhoneNumberCountry/machineToMachine.ts b/rest/api/v2010/account/availablePhoneNumberCountry/machineToMachine.ts new file mode 100644 index 000000000..f07067464 --- /dev/null +++ b/rest/api/v2010/account/availablePhoneNumberCountry/machineToMachine.ts @@ -0,0 +1,652 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../../interfaces"; + + + +/** + * Options to pass to each + */ +export interface MachineToMachineListInstanceEachOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MachineToMachineInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MachineToMachineListInstanceOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MachineToMachineListInstancePageOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface MachineToMachineSolution { + accountSid: string; + countryCode: string; +} + +export interface MachineToMachineListInstance { + _version: V2010; + _solution: MachineToMachineSolution; + _uri: string; + + + + + /** + * Streams MachineToMachineInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MachineToMachineListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MachineToMachineInstance, done: (err?: Error) => void) => void): void; + each(params: MachineToMachineListInstanceEachOptions, callback?: (item: MachineToMachineInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MachineToMachineInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MachineToMachineListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MachineToMachineInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MachineToMachineListInstanceEachOptions, callback?: (item: MachineToMachineInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MachineToMachineInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MachineToMachinePage) => any): Promise; + /** + * Retrieve a single target page of MachineToMachineInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MachineToMachineInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MachineToMachineListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MachineToMachineInstance[]) => any): Promise; + list(params: MachineToMachineListInstanceOptions, callback?: (error: Error | null, items: MachineToMachineInstance[]) => any): Promise; + /** + * Lists MachineToMachineInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MachineToMachineListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MachineToMachineListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MachineToMachineInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MachineToMachineListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MachineToMachinePage) => any): Promise; + page(params: MachineToMachineListInstancePageOptions, callback?: (error: Error | null, items: MachineToMachinePage) => any): Promise; + /** + * Retrieve a single page of MachineToMachineInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MachineToMachineListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MachineToMachineListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MachineToMachineListInstance(version: V2010, accountSid: string, countryCode: string): MachineToMachineListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(countryCode)) { + throw new Error('Parameter \'countryCode\' is not valid.'); + } + + const instance = {} as MachineToMachineListInstance; + + instance._version = version; + instance._solution = { accountSid, countryCode, }; + instance._uri = `/Accounts/${accountSid}/AvailablePhoneNumbers/${countryCode}/MachineToMachine.json`; + + instance.page = function page(params?: MachineToMachineListInstancePageOptions | ((error: Error | null, items: MachineToMachinePage) => any), callback?: (error: Error | null, items: MachineToMachinePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MachineToMachinePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MachineToMachinePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MachineToMachinePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MachineToMachineListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MachineToMachinePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MachineToMachinePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface MachineToMachinePayload extends TwilioResponsePayload { + available_phone_numbers: MachineToMachineResource[]; +} + +interface MachineToMachineResource { + friendly_name: string; + phone_number: string; + lata: string; + locality: string; + rate_center: string; + latitude: number; + longitude: number; + region: string; + postal_code: string; + iso_country: string; + address_requirements: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; +} + +export class MachineToMachineInstance { + + constructor(protected _version: V2010, payload: MachineToMachineResource, accountSid: string, countryCode: string) { + + this.friendlyName = (payload.friendly_name); + this.phoneNumber = (payload.phone_number); + this.lata = (payload.lata); + this.locality = (payload.locality); + this.rateCenter = (payload.rate_center); + this.latitude = (payload.latitude); + this.longitude = (payload.longitude); + this.region = (payload.region); + this.postalCode = (payload.postal_code); + this.isoCountry = (payload.iso_country); + this.addressRequirements = (payload.address_requirements); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + + } + + /** + * A formatted version of the phone number. + */ + friendlyName: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + */ + lata: string; + /** + * The locality or city of this phone number\'s location. + */ + locality: string; + /** + * The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + */ + rateCenter: string; + /** + * The latitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + latitude: number; + /** + * The longitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + longitude: number; + /** + * The two-letter state or province abbreviation of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + region: string; + /** + * The postal or ZIP code of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + postalCode: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + */ + isoCountry: string; + /** + * The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number\'s country is required. `foreign` means an address outside of the phone number\'s country is required. + */ + addressRequirements: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + friendlyName: this.friendlyName, + phoneNumber: this.phoneNumber, + lata: this.lata, + locality: this.locality, + rateCenter: this.rateCenter, + latitude: this.latitude, + longitude: this.longitude, + region: this.region, + postalCode: this.postalCode, + isoCountry: this.isoCountry, + addressRequirements: this.addressRequirements, + beta: this.beta, + capabilities: this.capabilities, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class MachineToMachinePage extends Page { +/** +* Initialize the MachineToMachinePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: MachineToMachineSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MachineToMachineInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MachineToMachineResource): MachineToMachineInstance { + + return new MachineToMachineInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.countryCode, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/availablePhoneNumberCountry/mobile.ts b/rest/api/v2010/account/availablePhoneNumberCountry/mobile.ts new file mode 100644 index 000000000..a17138c5c --- /dev/null +++ b/rest/api/v2010/account/availablePhoneNumberCountry/mobile.ts @@ -0,0 +1,652 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../../interfaces"; + + + +/** + * Options to pass to each + */ +export interface MobileListInstanceEachOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MobileInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MobileListInstanceOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MobileListInstancePageOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface MobileSolution { + accountSid: string; + countryCode: string; +} + +export interface MobileListInstance { + _version: V2010; + _solution: MobileSolution; + _uri: string; + + + + + /** + * Streams MobileInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MobileInstance, done: (err?: Error) => void) => void): void; + each(params: MobileListInstanceEachOptions, callback?: (item: MobileInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MobileInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MobileInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MobileListInstanceEachOptions, callback?: (item: MobileInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MobileInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MobilePage) => any): Promise; + /** + * Retrieve a single target page of MobileInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MobileInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MobileInstance[]) => any): Promise; + list(params: MobileListInstanceOptions, callback?: (error: Error | null, items: MobileInstance[]) => any): Promise; + /** + * Lists MobileInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MobileListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MobileInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MobilePage) => any): Promise; + page(params: MobileListInstancePageOptions, callback?: (error: Error | null, items: MobilePage) => any): Promise; + /** + * Retrieve a single page of MobileInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MobileListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MobileListInstance(version: V2010, accountSid: string, countryCode: string): MobileListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(countryCode)) { + throw new Error('Parameter \'countryCode\' is not valid.'); + } + + const instance = {} as MobileListInstance; + + instance._version = version; + instance._solution = { accountSid, countryCode, }; + instance._uri = `/Accounts/${accountSid}/AvailablePhoneNumbers/${countryCode}/Mobile.json`; + + instance.page = function page(params?: MobileListInstancePageOptions | ((error: Error | null, items: MobilePage) => any), callback?: (error: Error | null, items: MobilePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MobilePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MobilePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MobilePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MobileListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MobilePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MobilePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface MobilePayload extends TwilioResponsePayload { + available_phone_numbers: MobileResource[]; +} + +interface MobileResource { + friendly_name: string; + phone_number: string; + lata: string; + locality: string; + rate_center: string; + latitude: number; + longitude: number; + region: string; + postal_code: string; + iso_country: string; + address_requirements: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; +} + +export class MobileInstance { + + constructor(protected _version: V2010, payload: MobileResource, accountSid: string, countryCode: string) { + + this.friendlyName = (payload.friendly_name); + this.phoneNumber = (payload.phone_number); + this.lata = (payload.lata); + this.locality = (payload.locality); + this.rateCenter = (payload.rate_center); + this.latitude = (payload.latitude); + this.longitude = (payload.longitude); + this.region = (payload.region); + this.postalCode = (payload.postal_code); + this.isoCountry = (payload.iso_country); + this.addressRequirements = (payload.address_requirements); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + + } + + /** + * A formatted version of the phone number. + */ + friendlyName: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + */ + lata: string; + /** + * The locality or city of this phone number\'s location. + */ + locality: string; + /** + * The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + */ + rateCenter: string; + /** + * The latitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + latitude: number; + /** + * The longitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + longitude: number; + /** + * The two-letter state or province abbreviation of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + region: string; + /** + * The postal or ZIP code of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + postalCode: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + */ + isoCountry: string; + /** + * The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number\'s country is required. `foreign` means an address outside of the phone number\'s country is required. + */ + addressRequirements: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + friendlyName: this.friendlyName, + phoneNumber: this.phoneNumber, + lata: this.lata, + locality: this.locality, + rateCenter: this.rateCenter, + latitude: this.latitude, + longitude: this.longitude, + region: this.region, + postalCode: this.postalCode, + isoCountry: this.isoCountry, + addressRequirements: this.addressRequirements, + beta: this.beta, + capabilities: this.capabilities, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class MobilePage extends Page { +/** +* Initialize the MobilePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: MobileSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MobileInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MobileResource): MobileInstance { + + return new MobileInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.countryCode, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/availablePhoneNumberCountry/national.ts b/rest/api/v2010/account/availablePhoneNumberCountry/national.ts new file mode 100644 index 000000000..9c8f5eea7 --- /dev/null +++ b/rest/api/v2010/account/availablePhoneNumberCountry/national.ts @@ -0,0 +1,652 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../../interfaces"; + + + +/** + * Options to pass to each + */ +export interface NationalListInstanceEachOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: NationalInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface NationalListInstanceOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface NationalListInstancePageOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface NationalSolution { + accountSid: string; + countryCode: string; +} + +export interface NationalListInstance { + _version: V2010; + _solution: NationalSolution; + _uri: string; + + + + + /** + * Streams NationalInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NationalListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: NationalInstance, done: (err?: Error) => void) => void): void; + each(params: NationalListInstanceEachOptions, callback?: (item: NationalInstance, done: (err?: Error) => void) => void): void; + /** + * Streams NationalInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NationalListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: NationalInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: NationalListInstanceEachOptions, callback?: (item: NationalInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of NationalInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: NationalPage) => any): Promise; + /** + * Retrieve a single target page of NationalInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists NationalInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NationalListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: NationalInstance[]) => any): Promise; + list(params: NationalListInstanceOptions, callback?: (error: Error | null, items: NationalInstance[]) => any): Promise; + /** + * Lists NationalInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NationalListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: NationalListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of NationalInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NationalListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: NationalPage) => any): Promise; + page(params: NationalListInstancePageOptions, callback?: (error: Error | null, items: NationalPage) => any): Promise; + /** + * Retrieve a single page of NationalInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NationalListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: NationalListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NationalListInstance(version: V2010, accountSid: string, countryCode: string): NationalListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(countryCode)) { + throw new Error('Parameter \'countryCode\' is not valid.'); + } + + const instance = {} as NationalListInstance; + + instance._version = version; + instance._solution = { accountSid, countryCode, }; + instance._uri = `/Accounts/${accountSid}/AvailablePhoneNumbers/${countryCode}/National.json`; + + instance.page = function page(params?: NationalListInstancePageOptions | ((error: Error | null, items: NationalPage) => any), callback?: (error: Error | null, items: NationalPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new NationalPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: NationalPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new NationalPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: NationalListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NationalPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NationalPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface NationalPayload extends TwilioResponsePayload { + available_phone_numbers: NationalResource[]; +} + +interface NationalResource { + friendly_name: string; + phone_number: string; + lata: string; + locality: string; + rate_center: string; + latitude: number; + longitude: number; + region: string; + postal_code: string; + iso_country: string; + address_requirements: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; +} + +export class NationalInstance { + + constructor(protected _version: V2010, payload: NationalResource, accountSid: string, countryCode: string) { + + this.friendlyName = (payload.friendly_name); + this.phoneNumber = (payload.phone_number); + this.lata = (payload.lata); + this.locality = (payload.locality); + this.rateCenter = (payload.rate_center); + this.latitude = (payload.latitude); + this.longitude = (payload.longitude); + this.region = (payload.region); + this.postalCode = (payload.postal_code); + this.isoCountry = (payload.iso_country); + this.addressRequirements = (payload.address_requirements); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + + } + + /** + * A formatted version of the phone number. + */ + friendlyName: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + */ + lata: string; + /** + * The locality or city of this phone number\'s location. + */ + locality: string; + /** + * The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + */ + rateCenter: string; + /** + * The latitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + latitude: number; + /** + * The longitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + longitude: number; + /** + * The two-letter state or province abbreviation of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + region: string; + /** + * The postal or ZIP code of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + postalCode: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + */ + isoCountry: string; + /** + * The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number\'s country is required. `foreign` means an address outside of the phone number\'s country is required. + */ + addressRequirements: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + friendlyName: this.friendlyName, + phoneNumber: this.phoneNumber, + lata: this.lata, + locality: this.locality, + rateCenter: this.rateCenter, + latitude: this.latitude, + longitude: this.longitude, + region: this.region, + postalCode: this.postalCode, + isoCountry: this.isoCountry, + addressRequirements: this.addressRequirements, + beta: this.beta, + capabilities: this.capabilities, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class NationalPage extends Page { +/** +* Initialize the NationalPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: NationalSolution) { + super(version, response, solution); + } + + /** + * Build an instance of NationalInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: NationalResource): NationalInstance { + + return new NationalInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.countryCode, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/availablePhoneNumberCountry/sharedCost.ts b/rest/api/v2010/account/availablePhoneNumberCountry/sharedCost.ts new file mode 100644 index 000000000..2d2d1a0b6 --- /dev/null +++ b/rest/api/v2010/account/availablePhoneNumberCountry/sharedCost.ts @@ -0,0 +1,652 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../../interfaces"; + + + +/** + * Options to pass to each + */ +export interface SharedCostListInstanceEachOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SharedCostInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SharedCostListInstanceOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SharedCostListInstancePageOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface SharedCostSolution { + accountSid: string; + countryCode: string; +} + +export interface SharedCostListInstance { + _version: V2010; + _solution: SharedCostSolution; + _uri: string; + + + + + /** + * Streams SharedCostInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SharedCostListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SharedCostInstance, done: (err?: Error) => void) => void): void; + each(params: SharedCostListInstanceEachOptions, callback?: (item: SharedCostInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SharedCostInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SharedCostListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SharedCostInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SharedCostListInstanceEachOptions, callback?: (item: SharedCostInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SharedCostInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SharedCostPage) => any): Promise; + /** + * Retrieve a single target page of SharedCostInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists SharedCostInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SharedCostListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SharedCostInstance[]) => any): Promise; + list(params: SharedCostListInstanceOptions, callback?: (error: Error | null, items: SharedCostInstance[]) => any): Promise; + /** + * Lists SharedCostInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SharedCostListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: SharedCostListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of SharedCostInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SharedCostListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SharedCostPage) => any): Promise; + page(params: SharedCostListInstancePageOptions, callback?: (error: Error | null, items: SharedCostPage) => any): Promise; + /** + * Retrieve a single page of SharedCostInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SharedCostListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: SharedCostListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SharedCostListInstance(version: V2010, accountSid: string, countryCode: string): SharedCostListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(countryCode)) { + throw new Error('Parameter \'countryCode\' is not valid.'); + } + + const instance = {} as SharedCostListInstance; + + instance._version = version; + instance._solution = { accountSid, countryCode, }; + instance._uri = `/Accounts/${accountSid}/AvailablePhoneNumbers/${countryCode}/SharedCost.json`; + + instance.page = function page(params?: SharedCostListInstancePageOptions | ((error: Error | null, items: SharedCostPage) => any), callback?: (error: Error | null, items: SharedCostPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SharedCostPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SharedCostPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SharedCostPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SharedCostListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SharedCostPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SharedCostPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface SharedCostPayload extends TwilioResponsePayload { + available_phone_numbers: SharedCostResource[]; +} + +interface SharedCostResource { + friendly_name: string; + phone_number: string; + lata: string; + locality: string; + rate_center: string; + latitude: number; + longitude: number; + region: string; + postal_code: string; + iso_country: string; + address_requirements: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; +} + +export class SharedCostInstance { + + constructor(protected _version: V2010, payload: SharedCostResource, accountSid: string, countryCode: string) { + + this.friendlyName = (payload.friendly_name); + this.phoneNumber = (payload.phone_number); + this.lata = (payload.lata); + this.locality = (payload.locality); + this.rateCenter = (payload.rate_center); + this.latitude = (payload.latitude); + this.longitude = (payload.longitude); + this.region = (payload.region); + this.postalCode = (payload.postal_code); + this.isoCountry = (payload.iso_country); + this.addressRequirements = (payload.address_requirements); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + + } + + /** + * A formatted version of the phone number. + */ + friendlyName: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + */ + lata: string; + /** + * The locality or city of this phone number\'s location. + */ + locality: string; + /** + * The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + */ + rateCenter: string; + /** + * The latitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + latitude: number; + /** + * The longitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + longitude: number; + /** + * The two-letter state or province abbreviation of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + region: string; + /** + * The postal or ZIP code of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + postalCode: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + */ + isoCountry: string; + /** + * The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number\'s country is required. `foreign` means an address outside of the phone number\'s country is required. + */ + addressRequirements: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + friendlyName: this.friendlyName, + phoneNumber: this.phoneNumber, + lata: this.lata, + locality: this.locality, + rateCenter: this.rateCenter, + latitude: this.latitude, + longitude: this.longitude, + region: this.region, + postalCode: this.postalCode, + isoCountry: this.isoCountry, + addressRequirements: this.addressRequirements, + beta: this.beta, + capabilities: this.capabilities, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class SharedCostPage extends Page { +/** +* Initialize the SharedCostPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: SharedCostSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SharedCostInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SharedCostResource): SharedCostInstance { + + return new SharedCostInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.countryCode, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/availablePhoneNumberCountry/tollFree.ts b/rest/api/v2010/account/availablePhoneNumberCountry/tollFree.ts new file mode 100644 index 000000000..d931fcdc6 --- /dev/null +++ b/rest/api/v2010/account/availablePhoneNumberCountry/tollFree.ts @@ -0,0 +1,652 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../../interfaces"; + + + +/** + * Options to pass to each + */ +export interface TollFreeListInstanceEachOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TollFreeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TollFreeListInstanceOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TollFreeListInstancePageOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface TollFreeSolution { + accountSid: string; + countryCode: string; +} + +export interface TollFreeListInstance { + _version: V2010; + _solution: TollFreeSolution; + _uri: string; + + + + + /** + * Streams TollFreeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TollFreeInstance, done: (err?: Error) => void) => void): void; + each(params: TollFreeListInstanceEachOptions, callback?: (item: TollFreeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TollFreeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TollFreeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TollFreeListInstanceEachOptions, callback?: (item: TollFreeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TollFreeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TollFreePage) => any): Promise; + /** + * Retrieve a single target page of TollFreeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists TollFreeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TollFreeInstance[]) => any): Promise; + list(params: TollFreeListInstanceOptions, callback?: (error: Error | null, items: TollFreeInstance[]) => any): Promise; + /** + * Lists TollFreeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: TollFreeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of TollFreeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TollFreePage) => any): Promise; + page(params: TollFreeListInstancePageOptions, callback?: (error: Error | null, items: TollFreePage) => any): Promise; + /** + * Retrieve a single page of TollFreeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: TollFreeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TollFreeListInstance(version: V2010, accountSid: string, countryCode: string): TollFreeListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(countryCode)) { + throw new Error('Parameter \'countryCode\' is not valid.'); + } + + const instance = {} as TollFreeListInstance; + + instance._version = version; + instance._solution = { accountSid, countryCode, }; + instance._uri = `/Accounts/${accountSid}/AvailablePhoneNumbers/${countryCode}/TollFree.json`; + + instance.page = function page(params?: TollFreeListInstancePageOptions | ((error: Error | null, items: TollFreePage) => any), callback?: (error: Error | null, items: TollFreePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TollFreePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TollFreePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TollFreePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TollFreeListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TollFreePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TollFreePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TollFreePayload extends TwilioResponsePayload { + available_phone_numbers: TollFreeResource[]; +} + +interface TollFreeResource { + friendly_name: string; + phone_number: string; + lata: string; + locality: string; + rate_center: string; + latitude: number; + longitude: number; + region: string; + postal_code: string; + iso_country: string; + address_requirements: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; +} + +export class TollFreeInstance { + + constructor(protected _version: V2010, payload: TollFreeResource, accountSid: string, countryCode: string) { + + this.friendlyName = (payload.friendly_name); + this.phoneNumber = (payload.phone_number); + this.lata = (payload.lata); + this.locality = (payload.locality); + this.rateCenter = (payload.rate_center); + this.latitude = (payload.latitude); + this.longitude = (payload.longitude); + this.region = (payload.region); + this.postalCode = (payload.postal_code); + this.isoCountry = (payload.iso_country); + this.addressRequirements = (payload.address_requirements); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + + } + + /** + * A formatted version of the phone number. + */ + friendlyName: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + */ + lata: string; + /** + * The locality or city of this phone number\'s location. + */ + locality: string; + /** + * The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + */ + rateCenter: string; + /** + * The latitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + latitude: number; + /** + * The longitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + longitude: number; + /** + * The two-letter state or province abbreviation of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + region: string; + /** + * The postal or ZIP code of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + postalCode: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + */ + isoCountry: string; + /** + * The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number\'s country is required. `foreign` means an address outside of the phone number\'s country is required. + */ + addressRequirements: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + friendlyName: this.friendlyName, + phoneNumber: this.phoneNumber, + lata: this.lata, + locality: this.locality, + rateCenter: this.rateCenter, + latitude: this.latitude, + longitude: this.longitude, + region: this.region, + postalCode: this.postalCode, + isoCountry: this.isoCountry, + addressRequirements: this.addressRequirements, + beta: this.beta, + capabilities: this.capabilities, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class TollFreePage extends Page { +/** +* Initialize the TollFreePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: TollFreeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TollFreeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TollFreeResource): TollFreeInstance { + + return new TollFreeInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.countryCode, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/availablePhoneNumberCountry/voip.ts b/rest/api/v2010/account/availablePhoneNumberCountry/voip.ts new file mode 100644 index 000000000..d8e441669 --- /dev/null +++ b/rest/api/v2010/account/availablePhoneNumberCountry/voip.ts @@ -0,0 +1,652 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../../interfaces"; + + + +/** + * Options to pass to each + */ +export interface VoipListInstanceEachOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: VoipInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface VoipListInstanceOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface VoipListInstancePageOptions { + /** The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. */ + "areaCode"?: number; + /** Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can\'t be adjacent to each other. */ + "contains"?: string; + /** Whether the phone numbers can receive text messages. Can be: `true` or `false`. */ + "smsEnabled"?: boolean; + /** Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. */ + "mmsEnabled"?: boolean; + /** Whether the phone numbers can receive calls. Can be: `true` or `false`. */ + "voiceEnabled"?: boolean; + /** Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeAllAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeLocalAddressRequired"?: boolean; + /** Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. */ + "excludeForeignAddressRequired"?: boolean; + /** Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. */ + "nearNumber"?: string; + /** Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. */ + "nearLatLong"?: string; + /** The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. */ + "distance"?: number; + /** Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. */ + "inPostalCode"?: string; + /** Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. */ + "inRegion"?: string; + /** Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. */ + "inRateCenter"?: string; + /** Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. */ + "inLata"?: string; + /** Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. */ + "inLocality"?: string; + /** Whether the phone numbers can receive faxes. Can be: `true` or `false`. */ + "faxEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface VoipSolution { + accountSid: string; + countryCode: string; +} + +export interface VoipListInstance { + _version: V2010; + _solution: VoipSolution; + _uri: string; + + + + + /** + * Streams VoipInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VoipListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: VoipInstance, done: (err?: Error) => void) => void): void; + each(params: VoipListInstanceEachOptions, callback?: (item: VoipInstance, done: (err?: Error) => void) => void): void; + /** + * Streams VoipInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VoipListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: VoipInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: VoipListInstanceEachOptions, callback?: (item: VoipInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of VoipInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: VoipPage) => any): Promise; + /** + * Retrieve a single target page of VoipInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists VoipInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VoipListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: VoipInstance[]) => any): Promise; + list(params: VoipListInstanceOptions, callback?: (error: Error | null, items: VoipInstance[]) => any): Promise; + /** + * Lists VoipInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VoipListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: VoipListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of VoipInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VoipListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: VoipPage) => any): Promise; + page(params: VoipListInstancePageOptions, callback?: (error: Error | null, items: VoipPage) => any): Promise; + /** + * Retrieve a single page of VoipInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VoipListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: VoipListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function VoipListInstance(version: V2010, accountSid: string, countryCode: string): VoipListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(countryCode)) { + throw new Error('Parameter \'countryCode\' is not valid.'); + } + + const instance = {} as VoipListInstance; + + instance._version = version; + instance._solution = { accountSid, countryCode, }; + instance._uri = `/Accounts/${accountSid}/AvailablePhoneNumbers/${countryCode}/Voip.json`; + + instance.page = function page(params?: VoipListInstancePageOptions | ((error: Error | null, items: VoipPage) => any), callback?: (error: Error | null, items: VoipPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new VoipPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: VoipPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new VoipPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: VoipListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + if (params["contains"] !== undefined) + data["Contains"] = params["contains"]; + if (params["smsEnabled"] !== undefined) + data["SmsEnabled"] = serialize.bool(params["smsEnabled"]); + if (params["mmsEnabled"] !== undefined) + data["MmsEnabled"] = serialize.bool(params["mmsEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["excludeAllAddressRequired"] !== undefined) + data["ExcludeAllAddressRequired"] = serialize.bool(params["excludeAllAddressRequired"]); + if (params["excludeLocalAddressRequired"] !== undefined) + data["ExcludeLocalAddressRequired"] = serialize.bool(params["excludeLocalAddressRequired"]); + if (params["excludeForeignAddressRequired"] !== undefined) + data["ExcludeForeignAddressRequired"] = serialize.bool(params["excludeForeignAddressRequired"]); + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["nearNumber"] !== undefined) + data["NearNumber"] = params["nearNumber"]; + if (params["nearLatLong"] !== undefined) + data["NearLatLong"] = params["nearLatLong"]; + if (params["distance"] !== undefined) + data["Distance"] = params["distance"]; + if (params["inPostalCode"] !== undefined) + data["InPostalCode"] = params["inPostalCode"]; + if (params["inRegion"] !== undefined) + data["InRegion"] = params["inRegion"]; + if (params["inRateCenter"] !== undefined) + data["InRateCenter"] = params["inRateCenter"]; + if (params["inLata"] !== undefined) + data["InLata"] = params["inLata"]; + if (params["inLocality"] !== undefined) + data["InLocality"] = params["inLocality"]; + if (params["faxEnabled"] !== undefined) + data["FaxEnabled"] = serialize.bool(params["faxEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new VoipPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new VoipPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface VoipPayload extends TwilioResponsePayload { + available_phone_numbers: VoipResource[]; +} + +interface VoipResource { + friendly_name: string; + phone_number: string; + lata: string; + locality: string; + rate_center: string; + latitude: number; + longitude: number; + region: string; + postal_code: string; + iso_country: string; + address_requirements: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; +} + +export class VoipInstance { + + constructor(protected _version: V2010, payload: VoipResource, accountSid: string, countryCode: string) { + + this.friendlyName = (payload.friendly_name); + this.phoneNumber = (payload.phone_number); + this.lata = (payload.lata); + this.locality = (payload.locality); + this.rateCenter = (payload.rate_center); + this.latitude = (payload.latitude); + this.longitude = (payload.longitude); + this.region = (payload.region); + this.postalCode = (payload.postal_code); + this.isoCountry = (payload.iso_country); + this.addressRequirements = (payload.address_requirements); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + + } + + /** + * A formatted version of the phone number. + */ + friendlyName: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + */ + lata: string; + /** + * The locality or city of this phone number\'s location. + */ + locality: string; + /** + * The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + */ + rateCenter: string; + /** + * The latitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + latitude: number; + /** + * The longitude of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + longitude: number; + /** + * The two-letter state or province abbreviation of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + region: string; + /** + * The postal or ZIP code of this phone number\'s location. Available for only phone numbers from the US and Canada. + */ + postalCode: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + */ + isoCountry: string; + /** + * The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number\'s country is required. `foreign` means an address outside of the phone number\'s country is required. + */ + addressRequirements: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + friendlyName: this.friendlyName, + phoneNumber: this.phoneNumber, + lata: this.lata, + locality: this.locality, + rateCenter: this.rateCenter, + latitude: this.latitude, + longitude: this.longitude, + region: this.region, + postalCode: this.postalCode, + isoCountry: this.isoCountry, + addressRequirements: this.addressRequirements, + beta: this.beta, + capabilities: this.capabilities, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class VoipPage extends Page { +/** +* Initialize the VoipPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: VoipSolution) { + super(version, response, solution); + } + + /** + * Build an instance of VoipInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: VoipResource): VoipInstance { + + return new VoipInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.countryCode, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/balance.ts b/rest/api/v2010/account/balance.ts new file mode 100644 index 000000000..4f6379dc2 --- /dev/null +++ b/rest/api/v2010/account/balance.ts @@ -0,0 +1,169 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +export interface BalanceSolution { + accountSid: string; +} + +export interface BalanceListInstance { + _version: V2010; + _solution: BalanceSolution; + _uri: string; + + + + /** + * Fetch a BalanceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BalanceInstance + */ + fetch(callback?: (error: Error | null, item?: BalanceInstance) => any): Promise + + /** + * Fetch a BalanceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BalanceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BalanceListInstance(version: V2010, accountSid: string): BalanceListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as BalanceListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Balance.json`; + + instance.fetch = function fetch( callback?: (error: Error | null, items: BalanceInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BalanceInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo( callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new BalanceInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface BalancePayload extends BalanceResource {} + +interface BalanceResource { + account_sid: string; + balance: string; + currency: string; +} + +export class BalanceInstance { + + constructor(protected _version: V2010, payload: BalanceResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.balance = (payload.balance); + this.currency = (payload.currency); + + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The balance of the Account, in units specified by the unit parameter. Balance changes may not be reflected immediately. Child accounts do not contain balance information + */ + balance: string; + /** + * The units of currency for the account balance + */ + currency: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + balance: this.balance, + currency: this.currency, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/api/v2010/account/call.ts b/rest/api/v2010/account/call.ts new file mode 100644 index 000000000..b609eade9 --- /dev/null +++ b/rest/api/v2010/account/call.ts @@ -0,0 +1,1558 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { EventListInstance } from "./call/event"; +import { NotificationListInstance } from "./call/notification"; +import { PaymentListInstance } from "./call/payment"; +import { RecordingListInstance } from "./call/recording"; +import { SiprecListInstance } from "./call/siprec"; +import { StreamListInstance } from "./call/stream"; +import { TranscriptionListInstance } from "./call/transcription"; +import { UserDefinedMessageListInstance } from "./call/userDefinedMessage"; +import { UserDefinedMessageSubscriptionListInstance } from "./call/userDefinedMessageSubscription"; +import TwiML from "../../../../twiml/TwiML"; + + +/** + * The status of this call. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy` or `no-answer`. See [Call Status Values](https://www.twilio.com/docs/voice/api/call-resource#call-status-values) below for more information. + */ +export type CallStatus = 'queued'|'ringing'|'in-progress'|'completed'|'busy'|'failed'|'no-answer'|'canceled'; + +export type CallUpdateStatus = 'canceled'|'completed'; + + + + +/** + * Options to pass to update a CallInstance + */ +export interface CallContextUpdateOptions { + /** The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). */ + "url"?: string; + /** The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. */ + "method"?: string; + /** */ + "status"?: CallUpdateStatus; + /** The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. */ + "fallbackUrl"?: string; + /** The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. */ + "fallbackMethod"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). */ + "statusCallback"?: string; + /** The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. */ + "statusCallbackMethod"?: string; + /** TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive */ + "twiml"?: TwiML | string; + /** The maximum duration of the call in seconds. Constraints depend on account and configuration. */ + "timeLimit"?: number; +} + +/** + * Options to pass to create a CallInstance + */ +export interface CallListInstanceCreateOptions { + /** The phone number, SIP address, or client identifier to call. */ + "to": string; + /** The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. */ + "from": string; + /** The HTTP method we should use when calling the `url` parameter\\\'s value. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. */ + "method"?: string; + /** The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. */ + "fallbackUrl"?: string; + /** The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. */ + "fallbackMethod"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). */ + "statusCallback"?: string; + /** The call progress events that we will send to the `status_callback` URL. Can be: `initiated`, `ringing`, `answered`, and `completed`. If no event is specified, we send the `completed` status. If you want to receive multiple events, specify each one in a separate `status_callback_event` parameter. See the code sample for [monitoring call progress](https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-create-a-call-resource-and-specify-a-statuscallbackevent&code-sdk-version=json). If an `application_sid` is present, this parameter is ignored. */ + "statusCallbackEvent"?: Array; + /** The HTTP method we should use when calling the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. */ + "statusCallbackMethod"?: string; + /** The string of keys to dial after connecting to the number, with a maximum length of 32 digits. Valid digits in the string include any digit (`0`-`9`), \\\'`A`\\\', \\\'`B`\\\', \\\'`C`\\\', \\\'`D`\\\', \\\'`#`\\\', and \\\'`*`\\\'. You can also use \\\'`w`\\\' to insert a half-second pause and \\\'`W`\\\' to insert a one-second pause. For example, to pause for one second after connecting and then dial extension 1234 followed by the # key, set this parameter to `W1234#`. Be sure to URL-encode this string because the \\\'`#`\\\' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. */ + "sendDigits"?: string; + /** The integer number of seconds that we should allow the phone to ring before assuming there is no answer. The default is `60` seconds and the maximum is `600` seconds. For some call flows, we will add a 5-second buffer to the timeout value you provide. For this reason, a timeout value of 10 seconds could result in an actual timeout closer to 15 seconds. You can set this to a short time, such as `15` seconds, to hang up before reaching an answering machine or voicemail. */ + "timeout"?: number; + /** Whether to record the call. Can be `true` to record the phone call, or `false` to not. The default is `false`. The `recording_url` is sent to the `status_callback` URL. */ + "record"?: boolean; + /** The number of channels in the final recording. Can be: `mono` or `dual`. The default is `mono`. `mono` records both legs of the call in a single channel of the recording file. `dual` records each leg to a separate channel of the recording file. The first channel of a dual-channel recording contains the parent call and the second channel contains the child call. */ + "recordingChannels"?: string; + /** The URL that we call when the recording is available to be accessed. */ + "recordingStatusCallback"?: string; + /** The HTTP method we should use when calling the `recording_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. */ + "recordingStatusCallbackMethod"?: string; + /** The identifier of the configuration to be used when creating and processing the recording */ + "recordingConfigurationId"?: string; + /** The username used to authenticate the caller making a SIP call. */ + "sipAuthUsername"?: string; + /** The password required to authenticate the user account specified in `sip_auth_username`. */ + "sipAuthPassword"?: string; + /** Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. If `send_digits` is provided, this parameter is ignored. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). */ + "machineDetection"?: string; + /** The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. */ + "machineDetectionTimeout"?: number; + /** The recording status events that will trigger calls to the URL specified in `recording_status_callback`. Can be: `in-progress`, `completed` and `absent`. Defaults to `completed`. Separate multiple values with a space. */ + "recordingStatusCallbackEvent"?: Array; + /** Whether to trim any leading and trailing silence from the recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. */ + "trim"?: string; + /** The phone number, SIP address, or Client identifier that made this call. Phone numbers are in [E.164 format](https://wwnw.twilio.com/docs/glossary/what-e164) (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. */ + "callerId"?: string; + /** The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. */ + "machineDetectionSpeechThreshold"?: number; + /** The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. */ + "machineDetectionSpeechEndThreshold"?: number; + /** The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. */ + "machineDetectionSilenceTimeout"?: number; + /** Select whether to perform answering machine detection in the background. Default, blocks the execution of the call until Answering Machine Detection is completed. Can be: `true` or `false`. */ + "asyncAmd"?: string; + /** The URL that we should call using the `async_amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. */ + "asyncAmdStatusCallback"?: string; + /** The HTTP method we should use when calling the `async_amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. */ + "asyncAmdStatusCallbackMethod"?: string; + /** The STIR/SHAKEN passport for this call, provided as a base64 encoded string. Multiple passports (at max 5) are comma separated and provided as base64 encoded string */ + "passports"?: string; + /** The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) */ + "byoc"?: string; + /** The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party\\\'s phone. (Branded Calls Beta) */ + "callReason"?: string; + /** A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call\\\'s call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. */ + "callToken"?: string; + /** The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. */ + "recordingTrack"?: string; + /** The maximum duration of the call in seconds. Constraints depend on account and configuration. */ + "timeLimit"?: number; + /** The URL that we should use to deliver `push call notification`. */ + "clientNotificationUrl"?: string; + /** The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). */ + "url"?: string; + /** TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. */ + "twiml"?: TwiML | string; + /** The SID of the Application resource that will handle the call, if the call will be handled by an application. */ + "applicationSid"?: string; +} + +/** + * Options to pass to each + */ +export interface CallListInstanceEachOptions { + /** Only show calls made to this phone number, SIP address, Client identifier or SIM SID. */ + "to"?: string; + /** Only include calls from this phone number, SIP address, Client identifier or SIM SID. */ + "from"?: string; + /** Only include calls spawned by calls with this SID. */ + "parentCallSid"?: string; + /** The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. */ + "status"?: CallStatus; + /** Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. */ + "startTime"?: Date; + /** Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. */ + "startTimeBefore"?: Date; + /** Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. */ + "startTimeAfter"?: Date; + /** Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. */ + "endTime"?: Date; + /** Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. */ + "endTimeBefore"?: Date; + /** Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. */ + "endTimeAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CallInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CallListInstanceOptions { + /** Only show calls made to this phone number, SIP address, Client identifier or SIM SID. */ + "to"?: string; + /** Only include calls from this phone number, SIP address, Client identifier or SIM SID. */ + "from"?: string; + /** Only include calls spawned by calls with this SID. */ + "parentCallSid"?: string; + /** The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. */ + "status"?: CallStatus; + /** Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. */ + "startTime"?: Date; + /** Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. */ + "startTimeBefore"?: Date; + /** Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. */ + "startTimeAfter"?: Date; + /** Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. */ + "endTime"?: Date; + /** Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. */ + "endTimeBefore"?: Date; + /** Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. */ + "endTimeAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CallListInstancePageOptions { + /** Only show calls made to this phone number, SIP address, Client identifier or SIM SID. */ + "to"?: string; + /** Only include calls from this phone number, SIP address, Client identifier or SIM SID. */ + "from"?: string; + /** Only include calls spawned by calls with this SID. */ + "parentCallSid"?: string; + /** The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. */ + "status"?: CallStatus; + /** Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. */ + "startTime"?: Date; + /** Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. */ + "startTimeBefore"?: Date; + /** Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. */ + "startTimeAfter"?: Date; + /** Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. */ + "endTime"?: Date; + /** Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. */ + "endTimeBefore"?: Date; + /** Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. */ + "endTimeAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CallContext { + events: EventListInstance; + notifications: NotificationListInstance; + payments: PaymentListInstance; + recordings: RecordingListInstance; + siprec: SiprecListInstance; + streams: StreamListInstance; + transcriptions: TranscriptionListInstance; + userDefinedMessages: UserDefinedMessageListInstance; + userDefinedMessageSubscriptions: UserDefinedMessageSubscriptionListInstance; + + /** + * Remove a CallInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a CallInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a CallInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance + */ + fetch(callback?: (error: Error | null, item?: CallInstance) => any): Promise + + /** + * Fetch a CallInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a CallInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance + */ + update(callback?: (error: Error | null, item?: CallInstance) => any): Promise; + /** + * Update a CallInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance + */ + update(params: CallContextUpdateOptions, callback?: (error: Error | null, item?: CallInstance) => any): Promise; + + /** + * Update a CallInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CallInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance with HTTP metadata + */ + updateWithHttpInfo(params: CallContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CallContextSolution { + "accountSid": string; + "sid": string; +} + +export class CallContextImpl implements CallContext { + protected _solution: CallContextSolution; + protected _uri: string; + + protected _events?: EventListInstance; + protected _notifications?: NotificationListInstance; + protected _payments?: PaymentListInstance; + protected _recordings?: RecordingListInstance; + protected _siprec?: SiprecListInstance; + protected _streams?: StreamListInstance; + protected _transcriptions?: TranscriptionListInstance; + protected _userDefinedMessages?: UserDefinedMessageListInstance; + protected _userDefinedMessageSubscriptions?: UserDefinedMessageSubscriptionListInstance; + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Calls/${sid}.json`; + } + + get events(): EventListInstance { + this._events = this._events || EventListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._events; + } + + get notifications(): NotificationListInstance { + this._notifications = this._notifications || NotificationListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._notifications; + } + + get payments(): PaymentListInstance { + this._payments = this._payments || PaymentListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._payments; + } + + get recordings(): RecordingListInstance { + this._recordings = this._recordings || RecordingListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._recordings; + } + + get siprec(): SiprecListInstance { + this._siprec = this._siprec || SiprecListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._siprec; + } + + get streams(): StreamListInstance { + this._streams = this._streams || StreamListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._streams; + } + + get transcriptions(): TranscriptionListInstance { + this._transcriptions = this._transcriptions || TranscriptionListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._transcriptions; + } + + get userDefinedMessages(): UserDefinedMessageListInstance { + this._userDefinedMessages = this._userDefinedMessages || UserDefinedMessageListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._userDefinedMessages; + } + + get userDefinedMessageSubscriptions(): UserDefinedMessageSubscriptionListInstance { + this._userDefinedMessageSubscriptions = this._userDefinedMessageSubscriptions || UserDefinedMessageSubscriptionListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._userDefinedMessageSubscriptions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CallInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CallInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CallInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: CallContextUpdateOptions | ((error: Error | null, item?: CallInstance) => any),callback?: (error: Error | null, item?: CallInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["url"] !== undefined) + data["Url"] = params["url"]; + if (params["method"] !== undefined) + data["Method"] = params["method"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["fallbackUrl"] !== undefined) + data["FallbackUrl"] = params["fallbackUrl"]; + if (params["fallbackMethod"] !== undefined) + data["FallbackMethod"] = params["fallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["twiml"] !== undefined) + data["Twiml"] = serialize.twiml(params["twiml"]); + if (params["timeLimit"] !== undefined) + data["TimeLimit"] = params["timeLimit"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CallInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: CallContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["url"] !== undefined) + data["Url"] = params["url"]; + if (params["method"] !== undefined) + data["Method"] = params["method"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["fallbackUrl"] !== undefined) + data["FallbackUrl"] = params["fallbackUrl"]; + if (params["fallbackMethod"] !== undefined) + data["FallbackMethod"] = params["fallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["twiml"] !== undefined) + data["Twiml"] = serialize.twiml(params["twiml"]); + if (params["timeLimit"] !== undefined) + data["TimeLimit"] = params["timeLimit"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CallInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CallPayload extends TwilioResponsePayload { + calls: CallResource[]; +} + +interface CallResource { + sid: string; + date_created: Date; + date_updated: Date; + parent_call_sid: string; + account_sid: string; + to: string; + to_formatted: string; + from: string; + from_formatted: string; + phone_number_sid: string; + status: CallStatus; + start_time: Date; + end_time: Date; + duration: string; + price: string; + price_unit: string; + direction: string; + answered_by: string; + api_version: string; + forwarded_from: string; + group_sid: string; + caller_name: string; + queue_time: string; + trunk_sid: string; + uri: string; + subresource_uris: Record; +} + +export class CallInstance { + protected _solution: CallContextSolution; + protected _context?: CallContext; + + constructor(protected _version: V2010, payload: CallResource, accountSid: string, sid?: string) { + + this.sid = (payload.sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.parentCallSid = (payload.parent_call_sid); + this.accountSid = (payload.account_sid); + this.to = (payload.to); + this.toFormatted = (payload.to_formatted); + this.from = (payload.from); + this.fromFormatted = (payload.from_formatted); + this.phoneNumberSid = (payload.phone_number_sid); + this.status = payload.status; + this.startTime = deserialize.rfc2822DateTime(payload.start_time); + this.endTime = deserialize.rfc2822DateTime(payload.end_time); + this.duration = (payload.duration); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.direction = (payload.direction); + this.answeredBy = (payload.answered_by); + this.apiVersion = (payload.api_version); + this.forwardedFrom = (payload.forwarded_from); + this.groupSid = (payload.group_sid); + this.callerName = (payload.caller_name); + this.queueTime = (payload.queue_time); + this.trunkSid = (payload.trunk_sid); + this.uri = (payload.uri); + this.subresourceUris = (payload.subresource_uris); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The unique string that we created to identify this Call resource. + */ + sid: string; + /** + * The date and time in UTC that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in UTC that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The SID that identifies the call that created this leg. + */ + parentCallSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Call resource. + */ + accountSid: string; + /** + * The phone number, SIP address, Client identifier or SIM SID that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. SIM SIDs are formatted as `sim:sid`. + */ + to: string; + /** + * The phone number, SIP address or Client identifier that received this call. Formatted for display. Non-North American phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +442071838750). + */ + toFormatted: string; + /** + * The phone number, SIP address, Client identifier or SIM SID that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. SIM SIDs are formatted as `sim:sid`. + */ + from: string; + /** + * The calling phone number, SIP address, or Client identifier formatted for display. Non-North American phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +442071838750). + */ + fromFormatted: string; + /** + * If the call was inbound, this is the SID of the IncomingPhoneNumber resource that received the call. If the call was outbound, it is the SID of the OutgoingCallerId resource from which the call was placed. + */ + phoneNumberSid: string; + status: CallStatus; + /** + * The start time of the call, given as UTC in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. Empty if the call has not yet been dialed. + */ + startTime: Date; + /** + * The time the call ended, given as UTC in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. Empty if the call did not complete successfully. + */ + endTime: Date; + /** + * The length of the call in seconds. This value is empty for busy, failed, unanswered, or ongoing calls. + */ + duration: string; + /** + * The charge for this call, in the currency associated with the account. Populated after the call is completed. May not be immediately available. The price associated with a call only reflects the charge for connectivity. Charges for other call-related features such as Answering Machine Detection, Text-To-Speech, and SIP REFER are not included in this value. + */ + price: string; + /** + * The currency in which `Price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g., `USD`, `EUR`, `JPY`). Always capitalized for calls. + */ + priceUnit: string; + /** + * A string describing the direction of the call. Can be: `inbound` for inbound calls, `outbound-api` for calls initiated via the REST API or `outbound-dial` for calls initiated by a `` verb. Using [Elastic SIP Trunking](https://www.twilio.com/docs/sip-trunking), the values can be [`trunking-terminating`](https://www.twilio.com/docs/sip-trunking#termination) for outgoing calls from your communications infrastructure to the PSTN or [`trunking-originating`](https://www.twilio.com/docs/sip-trunking#origination) for incoming calls to your communications infrastructure from the PSTN. + */ + direction: string; + /** + * Either `human` or `machine` if this call was initiated with answering machine detection. Empty otherwise. + */ + answeredBy: string; + /** + * The API version used to create the call. + */ + apiVersion: string; + /** + * The forwarding phone number if this call was an incoming call forwarded from another number (depends on carrier supporting forwarding). Otherwise, empty. + */ + forwardedFrom: string; + /** + * The Group SID associated with this call. If no Group is associated with the call, the field is empty. + */ + groupSid: string; + /** + * The caller\'s name if this call was an incoming call to a phone number with caller ID Lookup enabled. Otherwise, empty. + */ + callerName: string; + /** + * The wait time in milliseconds before the call is placed. + */ + queueTime: string; + /** + * The unique identifier of the trunk resource that was used for this call. The field is empty if the call was not made using a SIP trunk or if the call is not terminated. + */ + trunkSid: string; + /** + * The URI of this resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * A list of subresources available to this call, identified by their URIs relative to `https://api.twilio.com`. + */ + subresourceUris: Record; + + private get _proxy(): CallContext { + this._context = this._context || new CallContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a CallInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CallInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CallInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance + */ + fetch(callback?: (error: Error | null, item?: CallInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CallInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CallInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance + */ + update(callback?: (error: Error | null, item?: CallInstance) => any): Promise; + /** + * Update a CallInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance + */ + update(params: CallContextUpdateOptions, callback?: (error: Error | null, item?: CallInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: CallInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a CallInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CallInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance with HTTP metadata + */ + updateWithHttpInfo(params: CallContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the events. + */ + events(): EventListInstance { + return this._proxy.events; + } + + /** + * Access the notifications. + */ + notifications(): NotificationListInstance { + return this._proxy.notifications; + } + + /** + * Access the payments. + */ + payments(): PaymentListInstance { + return this._proxy.payments; + } + + /** + * Access the recordings. + */ + recordings(): RecordingListInstance { + return this._proxy.recordings; + } + + /** + * Access the siprec. + */ + siprec(): SiprecListInstance { + return this._proxy.siprec; + } + + /** + * Access the streams. + */ + streams(): StreamListInstance { + return this._proxy.streams; + } + + /** + * Access the transcriptions. + */ + transcriptions(): TranscriptionListInstance { + return this._proxy.transcriptions; + } + + /** + * Access the userDefinedMessages. + */ + userDefinedMessages(): UserDefinedMessageListInstance { + return this._proxy.userDefinedMessages; + } + + /** + * Access the userDefinedMessageSubscriptions. + */ + userDefinedMessageSubscriptions(): UserDefinedMessageSubscriptionListInstance { + return this._proxy.userDefinedMessageSubscriptions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + parentCallSid: this.parentCallSid, + accountSid: this.accountSid, + to: this.to, + toFormatted: this.toFormatted, + from: this.from, + fromFormatted: this.fromFormatted, + phoneNumberSid: this.phoneNumberSid, + status: this.status, + startTime: this.startTime, + endTime: this.endTime, + duration: this.duration, + price: this.price, + priceUnit: this.priceUnit, + direction: this.direction, + answeredBy: this.answeredBy, + apiVersion: this.apiVersion, + forwardedFrom: this.forwardedFrom, + groupSid: this.groupSid, + callerName: this.callerName, + queueTime: this.queueTime, + trunkSid: this.trunkSid, + uri: this.uri, + subresourceUris: this.subresourceUris, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CallSolution { + accountSid: string; +} + +export interface CallListInstance { + _version: V2010; + _solution: CallSolution; + _uri: string; + + (sid: string, ): CallContext; + get(sid: string, ): CallContext; + + + + + + + + + /** + * Create a CallInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance + */ + create(params: CallListInstanceCreateOptions, callback?: (error: Error | null, item?: CallInstance) => any): Promise; + + /** + * Create a CallInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance with HTTP metadata + */ + createWithHttpInfo(params: CallListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CallInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CallInstance, done: (err?: Error) => void) => void): void; + each(params: CallListInstanceEachOptions, callback?: (item: CallInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CallInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CallInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CallListInstanceEachOptions, callback?: (item: CallInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CallInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CallPage) => any): Promise; + /** + * Retrieve a single target page of CallInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CallInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CallInstance[]) => any): Promise; + list(params: CallListInstanceOptions, callback?: (error: Error | null, items: CallInstance[]) => any): Promise; + /** + * Lists CallInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CallListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CallInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CallPage) => any): Promise; + page(params: CallListInstancePageOptions, callback?: (error: Error | null, items: CallPage) => any): Promise; + /** + * Retrieve a single page of CallInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CallListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CallListInstance(version: V2010, accountSid: string): CallListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as CallListInstance; + + instance.get = function get(sid, ): CallContext { + return new CallContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Calls.json`; + + instance.create = function create(params: CallListInstanceCreateOptions, callback?: (error: Error | null, items: CallInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + if (params["from"] === null || params["from"] === undefined) { + throw new Error('Required parameter "params[\'from\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + + data["From"] = params["from"]; + if (params["method"] !== undefined) + data["Method"] = params["method"]; + if (params["fallbackUrl"] !== undefined) + data["FallbackUrl"] = params["fallbackUrl"]; + if (params["fallbackMethod"] !== undefined) + data["FallbackMethod"] = params["fallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackEvent"] !== undefined) + data["StatusCallbackEvent"] = serialize.map(params["statusCallbackEvent"], (e: string) => (e)); + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["sendDigits"] !== undefined) + data["SendDigits"] = params["sendDigits"]; + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["record"] !== undefined) + data["Record"] = serialize.bool(params["record"]); + if (params["recordingChannels"] !== undefined) + data["RecordingChannels"] = params["recordingChannels"]; + if (params["recordingStatusCallback"] !== undefined) + data["RecordingStatusCallback"] = params["recordingStatusCallback"]; + if (params["recordingStatusCallbackMethod"] !== undefined) + data["RecordingStatusCallbackMethod"] = params["recordingStatusCallbackMethod"]; + if (params["recordingConfigurationId"] !== undefined) + data["RecordingConfigurationId"] = params["recordingConfigurationId"]; + if (params["sipAuthUsername"] !== undefined) + data["SipAuthUsername"] = params["sipAuthUsername"]; + if (params["sipAuthPassword"] !== undefined) + data["SipAuthPassword"] = params["sipAuthPassword"]; + if (params["machineDetection"] !== undefined) + data["MachineDetection"] = params["machineDetection"]; + if (params["machineDetectionTimeout"] !== undefined) + data["MachineDetectionTimeout"] = params["machineDetectionTimeout"]; + if (params["recordingStatusCallbackEvent"] !== undefined) + data["RecordingStatusCallbackEvent"] = serialize.map(params["recordingStatusCallbackEvent"], (e: string) => (e)); + if (params["trim"] !== undefined) + data["Trim"] = params["trim"]; + if (params["callerId"] !== undefined) + data["CallerId"] = params["callerId"]; + if (params["machineDetectionSpeechThreshold"] !== undefined) + data["MachineDetectionSpeechThreshold"] = params["machineDetectionSpeechThreshold"]; + if (params["machineDetectionSpeechEndThreshold"] !== undefined) + data["MachineDetectionSpeechEndThreshold"] = params["machineDetectionSpeechEndThreshold"]; + if (params["machineDetectionSilenceTimeout"] !== undefined) + data["MachineDetectionSilenceTimeout"] = params["machineDetectionSilenceTimeout"]; + if (params["asyncAmd"] !== undefined) + data["AsyncAmd"] = params["asyncAmd"]; + if (params["asyncAmdStatusCallback"] !== undefined) + data["AsyncAmdStatusCallback"] = params["asyncAmdStatusCallback"]; + if (params["asyncAmdStatusCallbackMethod"] !== undefined) + data["AsyncAmdStatusCallbackMethod"] = params["asyncAmdStatusCallbackMethod"]; + if (params["passports"] !== undefined) + data["Passports"] = params["passports"]; + if (params["byoc"] !== undefined) + data["Byoc"] = params["byoc"]; + if (params["callReason"] !== undefined) + data["CallReason"] = params["callReason"]; + if (params["callToken"] !== undefined) + data["CallToken"] = params["callToken"]; + if (params["recordingTrack"] !== undefined) + data["RecordingTrack"] = params["recordingTrack"]; + if (params["timeLimit"] !== undefined) + data["TimeLimit"] = params["timeLimit"]; + if (params["clientNotificationUrl"] !== undefined) + data["ClientNotificationUrl"] = params["clientNotificationUrl"]; + if (params["url"] !== undefined) + data["Url"] = params["url"]; + if (params["twiml"] !== undefined) + data["Twiml"] = serialize.twiml(params["twiml"]); + if (params["applicationSid"] !== undefined) + data["ApplicationSid"] = params["applicationSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CallInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CallListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + if (params["from"] === null || params["from"] === undefined) { + throw new Error('Required parameter "params[\'from\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + + data["From"] = params["from"]; + if (params["method"] !== undefined) + data["Method"] = params["method"]; + if (params["fallbackUrl"] !== undefined) + data["FallbackUrl"] = params["fallbackUrl"]; + if (params["fallbackMethod"] !== undefined) + data["FallbackMethod"] = params["fallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackEvent"] !== undefined) + data["StatusCallbackEvent"] = serialize.map(params["statusCallbackEvent"], (e: string) => (e)); + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["sendDigits"] !== undefined) + data["SendDigits"] = params["sendDigits"]; + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["record"] !== undefined) + data["Record"] = serialize.bool(params["record"]); + if (params["recordingChannels"] !== undefined) + data["RecordingChannels"] = params["recordingChannels"]; + if (params["recordingStatusCallback"] !== undefined) + data["RecordingStatusCallback"] = params["recordingStatusCallback"]; + if (params["recordingStatusCallbackMethod"] !== undefined) + data["RecordingStatusCallbackMethod"] = params["recordingStatusCallbackMethod"]; + if (params["recordingConfigurationId"] !== undefined) + data["RecordingConfigurationId"] = params["recordingConfigurationId"]; + if (params["sipAuthUsername"] !== undefined) + data["SipAuthUsername"] = params["sipAuthUsername"]; + if (params["sipAuthPassword"] !== undefined) + data["SipAuthPassword"] = params["sipAuthPassword"]; + if (params["machineDetection"] !== undefined) + data["MachineDetection"] = params["machineDetection"]; + if (params["machineDetectionTimeout"] !== undefined) + data["MachineDetectionTimeout"] = params["machineDetectionTimeout"]; + if (params["recordingStatusCallbackEvent"] !== undefined) + data["RecordingStatusCallbackEvent"] = serialize.map(params["recordingStatusCallbackEvent"], (e: string) => (e)); + if (params["trim"] !== undefined) + data["Trim"] = params["trim"]; + if (params["callerId"] !== undefined) + data["CallerId"] = params["callerId"]; + if (params["machineDetectionSpeechThreshold"] !== undefined) + data["MachineDetectionSpeechThreshold"] = params["machineDetectionSpeechThreshold"]; + if (params["machineDetectionSpeechEndThreshold"] !== undefined) + data["MachineDetectionSpeechEndThreshold"] = params["machineDetectionSpeechEndThreshold"]; + if (params["machineDetectionSilenceTimeout"] !== undefined) + data["MachineDetectionSilenceTimeout"] = params["machineDetectionSilenceTimeout"]; + if (params["asyncAmd"] !== undefined) + data["AsyncAmd"] = params["asyncAmd"]; + if (params["asyncAmdStatusCallback"] !== undefined) + data["AsyncAmdStatusCallback"] = params["asyncAmdStatusCallback"]; + if (params["asyncAmdStatusCallbackMethod"] !== undefined) + data["AsyncAmdStatusCallbackMethod"] = params["asyncAmdStatusCallbackMethod"]; + if (params["passports"] !== undefined) + data["Passports"] = params["passports"]; + if (params["byoc"] !== undefined) + data["Byoc"] = params["byoc"]; + if (params["callReason"] !== undefined) + data["CallReason"] = params["callReason"]; + if (params["callToken"] !== undefined) + data["CallToken"] = params["callToken"]; + if (params["recordingTrack"] !== undefined) + data["RecordingTrack"] = params["recordingTrack"]; + if (params["timeLimit"] !== undefined) + data["TimeLimit"] = params["timeLimit"]; + if (params["clientNotificationUrl"] !== undefined) + data["ClientNotificationUrl"] = params["clientNotificationUrl"]; + if (params["url"] !== undefined) + data["Url"] = params["url"]; + if (params["twiml"] !== undefined) + data["Twiml"] = serialize.twiml(params["twiml"]); + if (params["applicationSid"] !== undefined) + data["ApplicationSid"] = params["applicationSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CallInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CallListInstancePageOptions | ((error: Error | null, items: CallPage) => any), callback?: (error: Error | null, items: CallPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["parentCallSid"] !== undefined) + data["ParentCallSid"] = params["parentCallSid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["startTime"] !== undefined) + data["StartTime"] = serialize.iso8601DateTime(params["startTime"]); + if (params["startTimeBefore"] !== undefined) + data["StartTime<"] = serialize.iso8601DateTime(params["startTimeBefore"]); + if (params["startTimeAfter"] !== undefined) + data["StartTime>"] = serialize.iso8601DateTime(params["startTimeAfter"]); + if (params["endTime"] !== undefined) + data["EndTime"] = serialize.iso8601DateTime(params["endTime"]); + if (params["endTimeBefore"] !== undefined) + data["EndTime<"] = serialize.iso8601DateTime(params["endTimeBefore"]); + if (params["endTimeAfter"] !== undefined) + data["EndTime>"] = serialize.iso8601DateTime(params["endTimeAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CallPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CallPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CallPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CallListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["parentCallSid"] !== undefined) + data["ParentCallSid"] = params["parentCallSid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["startTime"] !== undefined) + data["StartTime"] = serialize.iso8601DateTime(params["startTime"]); + if (params["startTimeBefore"] !== undefined) + data["StartTime<"] = serialize.iso8601DateTime(params["startTimeBefore"]); + if (params["startTimeAfter"] !== undefined) + data["StartTime>"] = serialize.iso8601DateTime(params["startTimeAfter"]); + if (params["endTime"] !== undefined) + data["EndTime"] = serialize.iso8601DateTime(params["endTime"]); + if (params["endTimeBefore"] !== undefined) + data["EndTime<"] = serialize.iso8601DateTime(params["endTimeBefore"]); + if (params["endTimeAfter"] !== undefined) + data["EndTime>"] = serialize.iso8601DateTime(params["endTimeAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CallPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CallPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CallPage extends Page { +/** +* Initialize the CallPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: CallSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CallInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CallResource): CallInstance { + + return new CallInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/call/event.ts b/rest/api/v2010/account/call/event.ts new file mode 100644 index 000000000..fd4ce6d58 --- /dev/null +++ b/rest/api/v2010/account/call/event.ts @@ -0,0 +1,397 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface EventListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EventInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EventListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EventListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface EventSolution { + accountSid: string; + callSid: string; +} + +export interface EventListInstance { + _version: V2010; + _solution: EventSolution; + _uri: string; + + + + + /** + * Streams EventInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + each(params: EventListInstanceEachOptions, callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EventInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EventListInstanceEachOptions, callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EventInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EventPage) => any): Promise; + /** + * Retrieve a single target page of EventInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists EventInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EventInstance[]) => any): Promise; + list(params: EventListInstanceOptions, callback?: (error: Error | null, items: EventInstance[]) => any): Promise; + /** + * Lists EventInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: EventListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of EventInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EventPage) => any): Promise; + page(params: EventListInstancePageOptions, callback?: (error: Error | null, items: EventPage) => any): Promise; + /** + * Retrieve a single page of EventInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: EventListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EventListInstance(version: V2010, accountSid: string, callSid: string): EventListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = {} as EventListInstance; + + instance._version = version; + instance._solution = { accountSid, callSid, }; + instance._uri = `/Accounts/${accountSid}/Calls/${callSid}/Events.json`; + + instance.page = function page(params?: EventListInstancePageOptions | ((error: Error | null, items: EventPage) => any), callback?: (error: Error | null, items: EventPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EventPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EventPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EventPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EventListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EventPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EventPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface EventPayload extends TwilioResponsePayload { + events: EventResource[]; +} + +interface EventResource { + request: any; + response: any; +} + +export class EventInstance { + + constructor(protected _version: V2010, payload: EventResource, accountSid: string, callSid: string) { + + this.request = (payload.request); + this.response = (payload.response); + + } + + /** + * Contains a dictionary representing the request of the call. + */ + request: any; + /** + * Contains a dictionary representing the call response, including a list of the call events. + */ + response: any; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + request: this.request, + response: this.response, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class EventPage extends Page { +/** +* Initialize the EventPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: EventSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EventInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EventResource): EventInstance { + + return new EventInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.callSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/call/notification.ts b/rest/api/v2010/account/call/notification.ts new file mode 100644 index 000000000..d1ac0526a --- /dev/null +++ b/rest/api/v2010/account/call/notification.ts @@ -0,0 +1,690 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface NotificationListInstanceEachOptions { + /** Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. */ + "log"?: number; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDate"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateBefore"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: NotificationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface NotificationListInstanceOptions { + /** Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. */ + "log"?: number; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDate"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateBefore"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface NotificationListInstancePageOptions { + /** Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. */ + "log"?: number; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDate"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateBefore"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface NotificationContext { + + /** + * Fetch a NotificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + fetch(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise + + /** + * Fetch a NotificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface NotificationContextSolution { + "accountSid": string; + "callSid": string; + "sid": string; +} + +export class NotificationContextImpl implements NotificationContext { + protected _solution: NotificationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, callSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, callSid, sid, }; + this._uri = `/Accounts/${accountSid}/Calls/${callSid}/Notifications/${sid}.json`; + } + + fetch(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new NotificationInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new NotificationInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface NotificationPayload extends TwilioResponsePayload { + notifications: NotificationResource[]; +} + +interface NotificationResource { + account_sid: string; + api_version: string; + call_sid: string; + date_created: Date; + date_updated: Date; + error_code: string; + log: string; + message_date: Date; + message_text: string; + more_info: string; + request_method: string; + request_url: string; + request_variables: string; + response_body: string; + response_headers: string; + sid: string; + uri: string; +} + +export class NotificationInstance { + protected _solution: NotificationContextSolution; + protected _context?: NotificationContext; + + constructor(protected _version: V2010, payload: NotificationResource, accountSid: string, callSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.callSid = (payload.call_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.errorCode = (payload.error_code); + this.log = (payload.log); + this.messageDate = deserialize.rfc2822DateTime(payload.message_date); + this.messageText = (payload.message_text); + this.moreInfo = (payload.more_info); + this.requestMethod = (payload.request_method); + this.requestUrl = (payload.request_url); + this.requestVariables = (payload.request_variables); + this.responseBody = (payload.response_body); + this.responseHeaders = (payload.response_headers); + this.sid = (payload.sid); + this.uri = (payload.uri); + + this._solution = { accountSid, callSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resource. + */ + accountSid: string; + /** + * The API version used to create the Call Notification resource. + */ + apiVersion: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Call Notification resource is associated with. + */ + callSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * A unique error code for the error condition that is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + */ + errorCode: string; + /** + * An integer log level that corresponds to the type of notification: `0` is ERROR, `1` is WARNING. + */ + log: string; + /** + * The date the notification was actually generated in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. Message buffering can cause this value to differ from `date_created`. + */ + messageDate: Date; + /** + * The text of the notification. + */ + messageText: string; + /** + * The URL for more information about the error condition. This value is a page in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + */ + moreInfo: string; + /** + * The HTTP method used to generate the notification. If the notification was generated during a phone call, this is the HTTP Method used to request the resource on your server. If the notification was generated by your use of our REST API, this is the HTTP method used to call the resource on our servers. + */ + requestMethod: string; + /** + * The URL of the resource that generated the notification. If the notification was generated during a phone call, this is the URL of the resource on your server that caused the notification. If the notification was generated by your use of our REST API, this is the URL of the resource you called. + */ + requestUrl: string; + /** + * The HTTP GET or POST variables we sent to your server. However, if the notification was generated by our REST API, this contains the HTTP POST or PUT variables you sent to our API. + */ + requestVariables: string; + /** + * The HTTP body returned by your server. + */ + responseBody: string; + /** + * The HTTP headers returned by your server. + */ + responseHeaders: string; + /** + * The unique string that that we created to identify the Call Notification resource. + */ + sid: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): NotificationContext { + this._context = this._context || new NotificationContextImpl(this._version, this._solution.accountSid, this._solution.callSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a NotificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + fetch(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a NotificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + callSid: this.callSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + errorCode: this.errorCode, + log: this.log, + messageDate: this.messageDate, + messageText: this.messageText, + moreInfo: this.moreInfo, + requestMethod: this.requestMethod, + requestUrl: this.requestUrl, + requestVariables: this.requestVariables, + responseBody: this.responseBody, + responseHeaders: this.responseHeaders, + sid: this.sid, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface NotificationSolution { + accountSid: string; + callSid: string; +} + +export interface NotificationListInstance { + _version: V2010; + _solution: NotificationSolution; + _uri: string; + + (sid: string, ): NotificationContext; + get(sid: string, ): NotificationContext; + + + + + + /** + * Streams NotificationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: NotificationInstance, done: (err?: Error) => void) => void): void; + each(params: NotificationListInstanceEachOptions, callback?: (item: NotificationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams NotificationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: NotificationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: NotificationListInstanceEachOptions, callback?: (item: NotificationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of NotificationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: NotificationPage) => any): Promise; + /** + * Retrieve a single target page of NotificationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists NotificationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: NotificationInstance[]) => any): Promise; + list(params: NotificationListInstanceOptions, callback?: (error: Error | null, items: NotificationInstance[]) => any): Promise; + /** + * Lists NotificationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: NotificationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of NotificationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: NotificationPage) => any): Promise; + page(params: NotificationListInstancePageOptions, callback?: (error: Error | null, items: NotificationPage) => any): Promise; + /** + * Retrieve a single page of NotificationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: NotificationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NotificationListInstance(version: V2010, accountSid: string, callSid: string): NotificationListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as NotificationListInstance; + + instance.get = function get(sid, ): NotificationContext { + return new NotificationContextImpl(version, accountSid, callSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, callSid, }; + instance._uri = `/Accounts/${accountSid}/Calls/${callSid}/Notifications.json`; + + instance.page = function page(params?: NotificationListInstancePageOptions | ((error: Error | null, items: NotificationPage) => any), callback?: (error: Error | null, items: NotificationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["log"] !== undefined) + data["Log"] = params["log"]; + if (params["messageDate"] !== undefined) + data["MessageDate"] = serialize.iso8601Date(params["messageDate"]); + if (params["messageDateBefore"] !== undefined) + data["MessageDate<"] = serialize.iso8601Date(params["messageDateBefore"]); + if (params["messageDateAfter"] !== undefined) + data["MessageDate>"] = serialize.iso8601Date(params["messageDateAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new NotificationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: NotificationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new NotificationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: NotificationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["log"] !== undefined) + data["Log"] = params["log"]; + if (params["messageDate"] !== undefined) + data["MessageDate"] = serialize.iso8601Date(params["messageDate"]); + if (params["messageDateBefore"] !== undefined) + data["MessageDate<"] = serialize.iso8601Date(params["messageDateBefore"]); + if (params["messageDateAfter"] !== undefined) + data["MessageDate>"] = serialize.iso8601Date(params["messageDateAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NotificationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NotificationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class NotificationPage extends Page { +/** +* Initialize the NotificationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: NotificationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of NotificationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: NotificationResource): NotificationInstance { + + return new NotificationInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.callSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/call/payment.ts b/rest/api/v2010/account/call/payment.ts new file mode 100644 index 000000000..5ff5778a6 --- /dev/null +++ b/rest/api/v2010/account/call/payment.ts @@ -0,0 +1,598 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * Type of bank account if payment source is ACH. One of `consumer-checking`, `consumer-savings`, or `commercial-checking`. The default value is `consumer-checking`. + */ +export type PaymentBankAccountType = 'consumer-checking'|'consumer-savings'|'commercial-checking'; + +/** + * The piece of payment information that you wish the caller to enter. Must be one of `payment-card-number`, `expiration-date`, `security-code`, `postal-code`, `bank-routing-number`, `bank-account-number`, or their `-matcher` variants for input confirmation when `RequireMatchingInputs` is enabled. + */ +export type PaymentCapture = 'payment-card-number'|'expiration-date'|'security-code'|'postal-code'|'bank-routing-number'|'bank-account-number'|'payment-card-number-matcher'|'expiration-date-matcher'|'security-code-matcher'|'postal-code-matcher'; + +/** + * Type of payment being captured. One of `credit-card` or `ach-debit`. The default value is `credit-card`. + */ +export type PaymentPaymentMethod = 'credit-card'|'ach-debit'; + +/** + * Indicates whether the current payment session should be cancelled or completed. When `cancel` the payment session is cancelled. When `complete`, Twilio sends the payment information to the selected Pay Connector for processing. + */ +export type PaymentStatus = 'complete'|'cancel'; + +/** + * Indicates whether the payment method should be tokenized as a `one-time`, `reusable`, or `payment-method` token. The default value is `reusable`. Do not enter a charge amount when tokenizing. If a charge amount is entered, the payment method will be charged and not tokenized. + */ +export type PaymentTokenType = 'one-time'|'reusable'|'payment-method'; + + +/** + * Options to pass to update a PaymentInstance + */ +export interface PaymentContextUpdateOptions { + /** A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. */ + "idempotencyKey": string; + /** Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. */ + "statusCallback": string; + /** */ + "capture"?: PaymentCapture; + /** */ + "status"?: PaymentStatus; +} + +/** + * Options to pass to create a PaymentInstance + */ +export interface PaymentListInstanceCreateOptions { + /** A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. */ + "idempotencyKey": string; + /** Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) */ + "statusCallback": string; + /** */ + "bankAccountType"?: PaymentBankAccountType; + /** A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. */ + "chargeAmount"?: number; + /** The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the Pay Connector are accepted. */ + "currency"?: string; + /** The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. */ + "description"?: string; + /** A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. */ + "input"?: string; + /** A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. */ + "minPostalCodeLength"?: number; + /** A single-level JSON object used to pass custom parameters to payment processors. (Required for ACH payments). The information that has to be included here depends on the Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). */ + "parameter"?: any; + /** This is the unique name corresponding to the Pay Connector installed in the Twilio Add-ons. Learn more about [ Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. */ + "paymentConnector"?: string; + /** */ + "paymentMethod"?: PaymentPaymentMethod; + /** Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. */ + "postalCode"?: boolean; + /** Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. */ + "securityCode"?: boolean; + /** The number of seconds that should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. */ + "timeout"?: number; + /** */ + "tokenType"?: PaymentTokenType; + /** Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` */ + "validCardTypes"?: string; + /** A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. */ + "requireMatchingInputs"?: string; + /** Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. */ + "confirmation"?: string; +} + +export interface PaymentContext { + + /** + * Update a PaymentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PaymentInstance + */ + update(params: PaymentContextUpdateOptions, callback?: (error: Error | null, item?: PaymentInstance) => any): Promise; + + /** + * Update a PaymentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PaymentInstance with HTTP metadata + */ + updateWithHttpInfo(params: PaymentContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PaymentContextSolution { + "accountSid": string; + "callSid": string; + "sid": string; +} + +export class PaymentContextImpl implements PaymentContext { + protected _solution: PaymentContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, callSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, callSid, sid, }; + this._uri = `/Accounts/${accountSid}/Calls/${callSid}/Payments/${sid}.json`; + } + + update(params: PaymentContextUpdateOptions,callback?: (error: Error | null, item?: PaymentInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["idempotencyKey"] === null || params["idempotencyKey"] === undefined) { + throw new Error('Required parameter "params[\'idempotencyKey\']" missing.'); + } + + if (params["statusCallback"] === null || params["statusCallback"] === undefined) { + throw new Error('Required parameter "params[\'statusCallback\']" missing.'); + } + + let data: any = {}; + + + + data["IdempotencyKey"] = params["idempotencyKey"]; + + data["StatusCallback"] = params["statusCallback"]; + if (params["capture"] !== undefined) + data["Capture"] = params["capture"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PaymentInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: PaymentContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["idempotencyKey"] === null || params["idempotencyKey"] === undefined) { + throw new Error('Required parameter "params[\'idempotencyKey\']" missing.'); + } + + if (params["statusCallback"] === null || params["statusCallback"] === undefined) { + throw new Error('Required parameter "params[\'statusCallback\']" missing.'); + } + + let data: any = {}; + + + + data["IdempotencyKey"] = params["idempotencyKey"]; + + data["StatusCallback"] = params["statusCallback"]; + if (params["capture"] !== undefined) + data["Capture"] = params["capture"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PaymentInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PaymentPayload extends PaymentResource {} + +interface PaymentResource { + account_sid: string; + call_sid: string; + sid: string; + date_created: Date; + date_updated: Date; + uri: string; +} + +export class PaymentInstance { + protected _solution: PaymentContextSolution; + protected _context?: PaymentContext; + + constructor(protected _version: V2010, payload: PaymentResource, accountSid: string, callSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.callSid = (payload.call_sid); + this.sid = (payload.sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.uri = (payload.uri); + + this._solution = { accountSid, callSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + */ + accountSid: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Payments resource is associated with. This will refer to the call sid that is producing the payment card (credit/ACH) information thru DTMF. + */ + callSid: string; + /** + * The SID of the Payments resource. + */ + sid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): PaymentContext { + this._context = this._context || new PaymentContextImpl(this._version, this._solution.accountSid, this._solution.callSid, this._solution.sid); + return this._context; + } + + /** + * Update a PaymentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PaymentInstance + */ + update(params: PaymentContextUpdateOptions, callback?: (error: Error | null, item?: PaymentInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: PaymentInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a PaymentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PaymentInstance with HTTP metadata + */ + updateWithHttpInfo(params: PaymentContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + callSid: this.callSid, + sid: this.sid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PaymentSolution { + accountSid: string; + callSid: string; +} + +export interface PaymentListInstance { + _version: V2010; + _solution: PaymentSolution; + _uri: string; + + (sid: string, ): PaymentContext; + get(sid: string, ): PaymentContext; + + + + + /** + * Create a PaymentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PaymentInstance + */ + create(params: PaymentListInstanceCreateOptions, callback?: (error: Error | null, item?: PaymentInstance) => any): Promise; + + /** + * Create a PaymentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PaymentInstance with HTTP metadata + */ + createWithHttpInfo(params: PaymentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PaymentListInstance(version: V2010, accountSid: string, callSid: string): PaymentListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as PaymentListInstance; + + instance.get = function get(sid, ): PaymentContext { + return new PaymentContextImpl(version, accountSid, callSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, callSid, }; + instance._uri = `/Accounts/${accountSid}/Calls/${callSid}/Payments.json`; + + instance.create = function create(params: PaymentListInstanceCreateOptions, callback?: (error: Error | null, items: PaymentInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["idempotencyKey"] === null || params["idempotencyKey"] === undefined) { + throw new Error('Required parameter "params[\'idempotencyKey\']" missing.'); + } + + if (params["statusCallback"] === null || params["statusCallback"] === undefined) { + throw new Error('Required parameter "params[\'statusCallback\']" missing.'); + } + + let data: any = {}; + + + + data["IdempotencyKey"] = params["idempotencyKey"]; + + data["StatusCallback"] = params["statusCallback"]; + if (params["bankAccountType"] !== undefined) + data["BankAccountType"] = params["bankAccountType"]; + if (params["chargeAmount"] !== undefined) + data["ChargeAmount"] = params["chargeAmount"]; + if (params["currency"] !== undefined) + data["Currency"] = params["currency"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["input"] !== undefined) + data["Input"] = params["input"]; + if (params["minPostalCodeLength"] !== undefined) + data["MinPostalCodeLength"] = params["minPostalCodeLength"]; + if (params["parameter"] !== undefined) + data["Parameter"] = serialize.object(params["parameter"]); + if (params["paymentConnector"] !== undefined) + data["PaymentConnector"] = params["paymentConnector"]; + if (params["paymentMethod"] !== undefined) + data["PaymentMethod"] = params["paymentMethod"]; + if (params["postalCode"] !== undefined) + data["PostalCode"] = serialize.bool(params["postalCode"]); + if (params["securityCode"] !== undefined) + data["SecurityCode"] = serialize.bool(params["securityCode"]); + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["tokenType"] !== undefined) + data["TokenType"] = params["tokenType"]; + if (params["validCardTypes"] !== undefined) + data["ValidCardTypes"] = params["validCardTypes"]; + if (params["requireMatchingInputs"] !== undefined) + data["RequireMatchingInputs"] = params["requireMatchingInputs"]; + if (params["confirmation"] !== undefined) + data["Confirmation"] = params["confirmation"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PaymentInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: PaymentListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["idempotencyKey"] === null || params["idempotencyKey"] === undefined) { + throw new Error('Required parameter "params[\'idempotencyKey\']" missing.'); + } + + if (params["statusCallback"] === null || params["statusCallback"] === undefined) { + throw new Error('Required parameter "params[\'statusCallback\']" missing.'); + } + + let data: any = {}; + + + + data["IdempotencyKey"] = params["idempotencyKey"]; + + data["StatusCallback"] = params["statusCallback"]; + if (params["bankAccountType"] !== undefined) + data["BankAccountType"] = params["bankAccountType"]; + if (params["chargeAmount"] !== undefined) + data["ChargeAmount"] = params["chargeAmount"]; + if (params["currency"] !== undefined) + data["Currency"] = params["currency"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["input"] !== undefined) + data["Input"] = params["input"]; + if (params["minPostalCodeLength"] !== undefined) + data["MinPostalCodeLength"] = params["minPostalCodeLength"]; + if (params["parameter"] !== undefined) + data["Parameter"] = serialize.object(params["parameter"]); + if (params["paymentConnector"] !== undefined) + data["PaymentConnector"] = params["paymentConnector"]; + if (params["paymentMethod"] !== undefined) + data["PaymentMethod"] = params["paymentMethod"]; + if (params["postalCode"] !== undefined) + data["PostalCode"] = serialize.bool(params["postalCode"]); + if (params["securityCode"] !== undefined) + data["SecurityCode"] = serialize.bool(params["securityCode"]); + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["tokenType"] !== undefined) + data["TokenType"] = params["tokenType"]; + if (params["validCardTypes"] !== undefined) + data["ValidCardTypes"] = params["validCardTypes"]; + if (params["requireMatchingInputs"] !== undefined) + data["RequireMatchingInputs"] = params["requireMatchingInputs"]; + if (params["confirmation"] !== undefined) + data["Confirmation"] = params["confirmation"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PaymentInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/api/v2010/account/call/recording.ts b/rest/api/v2010/account/call/recording.ts new file mode 100644 index 000000000..8043061d0 --- /dev/null +++ b/rest/api/v2010/account/call/recording.ts @@ -0,0 +1,1055 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * How the recording was created. Can be: `DialVerb`, `Conference`, `OutboundAPI`, `Trunking`, `RecordVerb`, `StartCallRecordingAPI`, and `StartConferenceRecordingAPI`. + */ +export type RecordingSource = 'DialVerb'|'Conference'|'OutboundAPI'|'Trunking'|'RecordVerb'|'StartCallRecordingAPI'|'StartConferenceRecordingAPI'; + +/** + * The status of the recording. Can be: `processing`, `completed` and `absent`. For more detailed statuses on in-progress recordings, check out how to [Update a Recording Resource](https://www.twilio.com/docs/voice/api/recording#update-a-recording-resource). + */ +export type RecordingStatus = 'in-progress'|'paused'|'stopped'|'processing'|'completed'|'absent'; + + + + +/** + * Options to pass to update a RecordingInstance + */ +export interface RecordingContextUpdateOptions { + /** */ + "status": RecordingStatus; + /** Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. */ + "pauseBehavior"?: string; +} + +/** + * Options to pass to create a RecordingInstance + */ +export interface RecordingListInstanceCreateOptions { + /** The recording status events on which we should call the `recording_status_callback` URL. Can be: `in-progress`, `completed` and `absent` and the default is `completed`. Separate multiple event values with a space. */ + "recordingStatusCallbackEvent"?: Array; + /** The URL we should call using the `recording_status_callback_method` on each recording event specified in `recording_status_callback_event`. For more information, see [RecordingStatusCallback parameters](https://www.twilio.com/docs/voice/api/recording#recordingstatuscallback). */ + "recordingStatusCallback"?: string; + /** The HTTP method we should use to call `recording_status_callback`. Can be: `GET` or `POST` and the default is `POST`. */ + "recordingStatusCallbackMethod"?: string; + /** Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. */ + "trim"?: string; + /** The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. */ + "recordingChannels"?: string; + /** The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. */ + "recordingTrack"?: string; + /** The identifier of the configuration to be used when creating and processing the recording */ + "recordingConfigurationId"?: string; +} + +/** + * Options to pass to each + */ +export interface RecordingListInstanceEachOptions { + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreated"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedBefore"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RecordingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RecordingListInstanceOptions { + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreated"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedBefore"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RecordingListInstancePageOptions { + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreated"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedBefore"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RecordingContext { + + /** + * Remove a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a RecordingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise; + + /** + * Update a RecordingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RecordingContextSolution { + "accountSid": string; + "callSid": string; + "sid": string; +} + +export class RecordingContextImpl implements RecordingContext { + protected _solution: RecordingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, callSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, callSid, sid, }; + this._uri = `/Accounts/${accountSid}/Calls/${callSid}/Recordings/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: RecordingContextUpdateOptions,callback?: (error: Error | null, item?: RecordingInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + if (params["pauseBehavior"] !== undefined) + data["PauseBehavior"] = params["pauseBehavior"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: RecordingContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + if (params["pauseBehavior"] !== undefined) + data["PauseBehavior"] = params["pauseBehavior"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RecordingPayload extends TwilioResponsePayload { + recordings: RecordingResource[]; +} + +interface RecordingResource { + account_sid: string; + api_version: string; + call_sid: string; + conference_sid: string; + date_created: Date; + date_updated: Date; + start_time: Date; + duration: string; + sid: string; + price: number; + uri: string; + encryption_details: any; + price_unit: string; + status: RecordingStatus; + channels: number; + source: RecordingSource; + error_code: number; + track: string; +} + +export class RecordingInstance { + protected _solution: RecordingContextSolution; + protected _context?: RecordingContext; + + constructor(protected _version: V2010, payload: RecordingResource, accountSid: string, callSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.callSid = (payload.call_sid); + this.conferenceSid = (payload.conference_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.startTime = deserialize.rfc2822DateTime(payload.start_time); + this.duration = (payload.duration); + this.sid = (payload.sid); + this.price = (payload.price); + this.uri = (payload.uri); + this.encryptionDetails = (payload.encryption_details); + this.priceUnit = (payload.price_unit); + this.status = payload.status; + this.channels = deserialize.integer(payload.channels); + this.source = payload.source; + this.errorCode = deserialize.integer(payload.error_code); + this.track = (payload.track); + + this._solution = { accountSid, callSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource. + */ + accountSid: string; + /** + * The API version used to make the recording. + */ + apiVersion: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Recording resource is associated with. + */ + callSid: string; + /** + * The Conference SID that identifies the conference associated with the recording, if a conference recording. + */ + conferenceSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + startTime: Date; + /** + * The length of the recording in seconds. + */ + duration: string; + /** + * The unique string that that we created to identify the Recording resource. + */ + sid: string; + /** + * The one-time cost of creating the recording in the `price_unit` currency. + */ + price: number; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + */ + encryptionDetails: any; + /** + * The currency used in the `price` property. Example: `USD`. + */ + priceUnit: string; + status: RecordingStatus; + /** + * The number of channels in the final recording file. Can be: `1`, or `2`. Separating a two leg call into two separate channels of the recording file is supported in [Dial](https://www.twilio.com/docs/voice/twiml/dial#attributes-record) and [Outbound Rest API](https://www.twilio.com/docs/voice/make-calls) record options. + */ + channels: number; + source: RecordingSource; + /** + * The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + */ + errorCode: number; + /** + * The recorded track. Can be: `inbound`, `outbound`, or `both`. + */ + track: string; + + private get _proxy(): RecordingContext { + this._context = this._context || new RecordingContextImpl(this._version, this._solution.accountSid, this._solution.callSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RecordingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a RecordingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + callSid: this.callSid, + conferenceSid: this.conferenceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + startTime: this.startTime, + duration: this.duration, + sid: this.sid, + price: this.price, + uri: this.uri, + encryptionDetails: this.encryptionDetails, + priceUnit: this.priceUnit, + status: this.status, + channels: this.channels, + source: this.source, + errorCode: this.errorCode, + track: this.track, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RecordingSolution { + accountSid: string; + callSid: string; +} + +export interface RecordingListInstance { + _version: V2010; + _solution: RecordingSolution; + _uri: string; + + (sid: string, ): RecordingContext; + get(sid: string, ): RecordingContext; + + + + + + + + + /** + * Create a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + create(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise; + /** + * Create a RecordingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + create(params: RecordingListInstanceCreateOptions, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise; + + /** + * Create a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a RecordingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + createWithHttpInfo(params: RecordingListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams RecordingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + each(params: RecordingListInstanceEachOptions, callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RecordingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RecordingListInstanceEachOptions, callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RecordingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RecordingPage) => any): Promise; + /** + * Retrieve a single target page of RecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RecordingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RecordingInstance[]) => any): Promise; + list(params: RecordingListInstanceOptions, callback?: (error: Error | null, items: RecordingInstance[]) => any): Promise; + /** + * Lists RecordingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RecordingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RecordingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RecordingPage) => any): Promise; + page(params: RecordingListInstancePageOptions, callback?: (error: Error | null, items: RecordingPage) => any): Promise; + /** + * Retrieve a single page of RecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RecordingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RecordingListInstance(version: V2010, accountSid: string, callSid: string): RecordingListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RecordingListInstance; + + instance.get = function get(sid, ): RecordingContext { + return new RecordingContextImpl(version, accountSid, callSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, callSid, }; + instance._uri = `/Accounts/${accountSid}/Calls/${callSid}/Recordings.json`; + + instance.create = function create(params?: RecordingListInstanceCreateOptions | ((error: Error | null, items: RecordingInstance) => any), callback?: (error: Error | null, items: RecordingInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["recordingStatusCallbackEvent"] !== undefined) + data["RecordingStatusCallbackEvent"] = serialize.map(params["recordingStatusCallbackEvent"], (e: string) => (e)); + if (params["recordingStatusCallback"] !== undefined) + data["RecordingStatusCallback"] = params["recordingStatusCallback"]; + if (params["recordingStatusCallbackMethod"] !== undefined) + data["RecordingStatusCallbackMethod"] = params["recordingStatusCallbackMethod"]; + if (params["trim"] !== undefined) + data["Trim"] = params["trim"]; + if (params["recordingChannels"] !== undefined) + data["RecordingChannels"] = params["recordingChannels"]; + if (params["recordingTrack"] !== undefined) + data["RecordingTrack"] = params["recordingTrack"]; + if (params["recordingConfigurationId"] !== undefined) + data["RecordingConfigurationId"] = params["recordingConfigurationId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: RecordingListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["recordingStatusCallbackEvent"] !== undefined) + data["RecordingStatusCallbackEvent"] = serialize.map(params["recordingStatusCallbackEvent"], (e: string) => (e)); + if (params["recordingStatusCallback"] !== undefined) + data["RecordingStatusCallback"] = params["recordingStatusCallback"]; + if (params["recordingStatusCallbackMethod"] !== undefined) + data["RecordingStatusCallbackMethod"] = params["recordingStatusCallbackMethod"]; + if (params["trim"] !== undefined) + data["Trim"] = params["trim"]; + if (params["recordingChannels"] !== undefined) + data["RecordingChannels"] = params["recordingChannels"]; + if (params["recordingTrack"] !== undefined) + data["RecordingTrack"] = params["recordingTrack"]; + if (params["recordingConfigurationId"] !== undefined) + data["RecordingConfigurationId"] = params["recordingConfigurationId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RecordingListInstancePageOptions | ((error: Error | null, items: RecordingPage) => any), callback?: (error: Error | null, items: RecordingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601Date(params["dateCreated"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreated<"] = serialize.iso8601Date(params["dateCreatedBefore"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreated>"] = serialize.iso8601Date(params["dateCreatedAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RecordingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RecordingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RecordingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RecordingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601Date(params["dateCreated"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreated<"] = serialize.iso8601Date(params["dateCreatedBefore"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreated>"] = serialize.iso8601Date(params["dateCreatedAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RecordingPage extends Page { +/** +* Initialize the RecordingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: RecordingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RecordingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RecordingResource): RecordingInstance { + + return new RecordingInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.callSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/call/siprec.ts b/rest/api/v2010/account/call/siprec.ts new file mode 100644 index 000000000..99798f9f1 --- /dev/null +++ b/rest/api/v2010/account/call/siprec.ts @@ -0,0 +1,1679 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The status - one of `stopped`, `in-progress` + */ +export type SiprecStatus = 'in-progress'|'stopped'; + +/** + * One of `inbound_track`, `outbound_track`, `both_tracks`. + */ +export type SiprecTrack = 'inbound_track'|'outbound_track'|'both_tracks'; + +export type SiprecUpdateStatus = 'stopped'; + + +/** + * Options to pass to update a SiprecInstance + */ +export interface SiprecContextUpdateOptions { + /** */ + "status": SiprecUpdateStatus; +} + +/** + * Options to pass to create a SiprecInstance + */ +export interface SiprecListInstanceCreateOptions { + /** The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. */ + "name"?: string; + /** Unique name used when configuring the connector via Marketplace Add-on. */ + "connectorName"?: string; + /** */ + "track"?: SiprecTrack; + /** Absolute URL of the status callback. */ + "statusCallback"?: string; + /** The http method for the status_callback (one of GET, POST). */ + "statusCallbackMethod"?: string; + /** Parameter name */ + "parameter1.name"?: string; + /** Parameter value */ + "parameter1.value"?: string; + /** Parameter name */ + "parameter2.name"?: string; + /** Parameter value */ + "parameter2.value"?: string; + /** Parameter name */ + "parameter3.name"?: string; + /** Parameter value */ + "parameter3.value"?: string; + /** Parameter name */ + "parameter4.name"?: string; + /** Parameter value */ + "parameter4.value"?: string; + /** Parameter name */ + "parameter5.name"?: string; + /** Parameter value */ + "parameter5.value"?: string; + /** Parameter name */ + "parameter6.name"?: string; + /** Parameter value */ + "parameter6.value"?: string; + /** Parameter name */ + "parameter7.name"?: string; + /** Parameter value */ + "parameter7.value"?: string; + /** Parameter name */ + "parameter8.name"?: string; + /** Parameter value */ + "parameter8.value"?: string; + /** Parameter name */ + "parameter9.name"?: string; + /** Parameter value */ + "parameter9.value"?: string; + /** Parameter name */ + "parameter10.name"?: string; + /** Parameter value */ + "parameter10.value"?: string; + /** Parameter name */ + "parameter11.name"?: string; + /** Parameter value */ + "parameter11.value"?: string; + /** Parameter name */ + "parameter12.name"?: string; + /** Parameter value */ + "parameter12.value"?: string; + /** Parameter name */ + "parameter13.name"?: string; + /** Parameter value */ + "parameter13.value"?: string; + /** Parameter name */ + "parameter14.name"?: string; + /** Parameter value */ + "parameter14.value"?: string; + /** Parameter name */ + "parameter15.name"?: string; + /** Parameter value */ + "parameter15.value"?: string; + /** Parameter name */ + "parameter16.name"?: string; + /** Parameter value */ + "parameter16.value"?: string; + /** Parameter name */ + "parameter17.name"?: string; + /** Parameter value */ + "parameter17.value"?: string; + /** Parameter name */ + "parameter18.name"?: string; + /** Parameter value */ + "parameter18.value"?: string; + /** Parameter name */ + "parameter19.name"?: string; + /** Parameter value */ + "parameter19.value"?: string; + /** Parameter name */ + "parameter20.name"?: string; + /** Parameter value */ + "parameter20.value"?: string; + /** Parameter name */ + "parameter21.name"?: string; + /** Parameter value */ + "parameter21.value"?: string; + /** Parameter name */ + "parameter22.name"?: string; + /** Parameter value */ + "parameter22.value"?: string; + /** Parameter name */ + "parameter23.name"?: string; + /** Parameter value */ + "parameter23.value"?: string; + /** Parameter name */ + "parameter24.name"?: string; + /** Parameter value */ + "parameter24.value"?: string; + /** Parameter name */ + "parameter25.name"?: string; + /** Parameter value */ + "parameter25.value"?: string; + /** Parameter name */ + "parameter26.name"?: string; + /** Parameter value */ + "parameter26.value"?: string; + /** Parameter name */ + "parameter27.name"?: string; + /** Parameter value */ + "parameter27.value"?: string; + /** Parameter name */ + "parameter28.name"?: string; + /** Parameter value */ + "parameter28.value"?: string; + /** Parameter name */ + "parameter29.name"?: string; + /** Parameter value */ + "parameter29.value"?: string; + /** Parameter name */ + "parameter30.name"?: string; + /** Parameter value */ + "parameter30.value"?: string; + /** Parameter name */ + "parameter31.name"?: string; + /** Parameter value */ + "parameter31.value"?: string; + /** Parameter name */ + "parameter32.name"?: string; + /** Parameter value */ + "parameter32.value"?: string; + /** Parameter name */ + "parameter33.name"?: string; + /** Parameter value */ + "parameter33.value"?: string; + /** Parameter name */ + "parameter34.name"?: string; + /** Parameter value */ + "parameter34.value"?: string; + /** Parameter name */ + "parameter35.name"?: string; + /** Parameter value */ + "parameter35.value"?: string; + /** Parameter name */ + "parameter36.name"?: string; + /** Parameter value */ + "parameter36.value"?: string; + /** Parameter name */ + "parameter37.name"?: string; + /** Parameter value */ + "parameter37.value"?: string; + /** Parameter name */ + "parameter38.name"?: string; + /** Parameter value */ + "parameter38.value"?: string; + /** Parameter name */ + "parameter39.name"?: string; + /** Parameter value */ + "parameter39.value"?: string; + /** Parameter name */ + "parameter40.name"?: string; + /** Parameter value */ + "parameter40.value"?: string; + /** Parameter name */ + "parameter41.name"?: string; + /** Parameter value */ + "parameter41.value"?: string; + /** Parameter name */ + "parameter42.name"?: string; + /** Parameter value */ + "parameter42.value"?: string; + /** Parameter name */ + "parameter43.name"?: string; + /** Parameter value */ + "parameter43.value"?: string; + /** Parameter name */ + "parameter44.name"?: string; + /** Parameter value */ + "parameter44.value"?: string; + /** Parameter name */ + "parameter45.name"?: string; + /** Parameter value */ + "parameter45.value"?: string; + /** Parameter name */ + "parameter46.name"?: string; + /** Parameter value */ + "parameter46.value"?: string; + /** Parameter name */ + "parameter47.name"?: string; + /** Parameter value */ + "parameter47.value"?: string; + /** Parameter name */ + "parameter48.name"?: string; + /** Parameter value */ + "parameter48.value"?: string; + /** Parameter name */ + "parameter49.name"?: string; + /** Parameter value */ + "parameter49.value"?: string; + /** Parameter name */ + "parameter50.name"?: string; + /** Parameter value */ + "parameter50.value"?: string; + /** Parameter name */ + "parameter51.name"?: string; + /** Parameter value */ + "parameter51.value"?: string; + /** Parameter name */ + "parameter52.name"?: string; + /** Parameter value */ + "parameter52.value"?: string; + /** Parameter name */ + "parameter53.name"?: string; + /** Parameter value */ + "parameter53.value"?: string; + /** Parameter name */ + "parameter54.name"?: string; + /** Parameter value */ + "parameter54.value"?: string; + /** Parameter name */ + "parameter55.name"?: string; + /** Parameter value */ + "parameter55.value"?: string; + /** Parameter name */ + "parameter56.name"?: string; + /** Parameter value */ + "parameter56.value"?: string; + /** Parameter name */ + "parameter57.name"?: string; + /** Parameter value */ + "parameter57.value"?: string; + /** Parameter name */ + "parameter58.name"?: string; + /** Parameter value */ + "parameter58.value"?: string; + /** Parameter name */ + "parameter59.name"?: string; + /** Parameter value */ + "parameter59.value"?: string; + /** Parameter name */ + "parameter60.name"?: string; + /** Parameter value */ + "parameter60.value"?: string; + /** Parameter name */ + "parameter61.name"?: string; + /** Parameter value */ + "parameter61.value"?: string; + /** Parameter name */ + "parameter62.name"?: string; + /** Parameter value */ + "parameter62.value"?: string; + /** Parameter name */ + "parameter63.name"?: string; + /** Parameter value */ + "parameter63.value"?: string; + /** Parameter name */ + "parameter64.name"?: string; + /** Parameter value */ + "parameter64.value"?: string; + /** Parameter name */ + "parameter65.name"?: string; + /** Parameter value */ + "parameter65.value"?: string; + /** Parameter name */ + "parameter66.name"?: string; + /** Parameter value */ + "parameter66.value"?: string; + /** Parameter name */ + "parameter67.name"?: string; + /** Parameter value */ + "parameter67.value"?: string; + /** Parameter name */ + "parameter68.name"?: string; + /** Parameter value */ + "parameter68.value"?: string; + /** Parameter name */ + "parameter69.name"?: string; + /** Parameter value */ + "parameter69.value"?: string; + /** Parameter name */ + "parameter70.name"?: string; + /** Parameter value */ + "parameter70.value"?: string; + /** Parameter name */ + "parameter71.name"?: string; + /** Parameter value */ + "parameter71.value"?: string; + /** Parameter name */ + "parameter72.name"?: string; + /** Parameter value */ + "parameter72.value"?: string; + /** Parameter name */ + "parameter73.name"?: string; + /** Parameter value */ + "parameter73.value"?: string; + /** Parameter name */ + "parameter74.name"?: string; + /** Parameter value */ + "parameter74.value"?: string; + /** Parameter name */ + "parameter75.name"?: string; + /** Parameter value */ + "parameter75.value"?: string; + /** Parameter name */ + "parameter76.name"?: string; + /** Parameter value */ + "parameter76.value"?: string; + /** Parameter name */ + "parameter77.name"?: string; + /** Parameter value */ + "parameter77.value"?: string; + /** Parameter name */ + "parameter78.name"?: string; + /** Parameter value */ + "parameter78.value"?: string; + /** Parameter name */ + "parameter79.name"?: string; + /** Parameter value */ + "parameter79.value"?: string; + /** Parameter name */ + "parameter80.name"?: string; + /** Parameter value */ + "parameter80.value"?: string; + /** Parameter name */ + "parameter81.name"?: string; + /** Parameter value */ + "parameter81.value"?: string; + /** Parameter name */ + "parameter82.name"?: string; + /** Parameter value */ + "parameter82.value"?: string; + /** Parameter name */ + "parameter83.name"?: string; + /** Parameter value */ + "parameter83.value"?: string; + /** Parameter name */ + "parameter84.name"?: string; + /** Parameter value */ + "parameter84.value"?: string; + /** Parameter name */ + "parameter85.name"?: string; + /** Parameter value */ + "parameter85.value"?: string; + /** Parameter name */ + "parameter86.name"?: string; + /** Parameter value */ + "parameter86.value"?: string; + /** Parameter name */ + "parameter87.name"?: string; + /** Parameter value */ + "parameter87.value"?: string; + /** Parameter name */ + "parameter88.name"?: string; + /** Parameter value */ + "parameter88.value"?: string; + /** Parameter name */ + "parameter89.name"?: string; + /** Parameter value */ + "parameter89.value"?: string; + /** Parameter name */ + "parameter90.name"?: string; + /** Parameter value */ + "parameter90.value"?: string; + /** Parameter name */ + "parameter91.name"?: string; + /** Parameter value */ + "parameter91.value"?: string; + /** Parameter name */ + "parameter92.name"?: string; + /** Parameter value */ + "parameter92.value"?: string; + /** Parameter name */ + "parameter93.name"?: string; + /** Parameter value */ + "parameter93.value"?: string; + /** Parameter name */ + "parameter94.name"?: string; + /** Parameter value */ + "parameter94.value"?: string; + /** Parameter name */ + "parameter95.name"?: string; + /** Parameter value */ + "parameter95.value"?: string; + /** Parameter name */ + "parameter96.name"?: string; + /** Parameter value */ + "parameter96.value"?: string; + /** Parameter name */ + "parameter97.name"?: string; + /** Parameter value */ + "parameter97.value"?: string; + /** Parameter name */ + "parameter98.name"?: string; + /** Parameter value */ + "parameter98.value"?: string; + /** Parameter name */ + "parameter99.name"?: string; + /** Parameter value */ + "parameter99.value"?: string; +} + +export interface SiprecContext { + + /** + * Update a SiprecInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SiprecInstance + */ + update(params: SiprecContextUpdateOptions, callback?: (error: Error | null, item?: SiprecInstance) => any): Promise; + + /** + * Update a SiprecInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SiprecInstance with HTTP metadata + */ + updateWithHttpInfo(params: SiprecContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SiprecContextSolution { + "accountSid": string; + "callSid": string; + "sid": string; +} + +export class SiprecContextImpl implements SiprecContext { + protected _solution: SiprecContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, callSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, callSid, sid, }; + this._uri = `/Accounts/${accountSid}/Calls/${callSid}/Siprec/${sid}.json`; + } + + update(params: SiprecContextUpdateOptions,callback?: (error: Error | null, item?: SiprecInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SiprecInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: SiprecContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SiprecInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SiprecPayload extends SiprecResource {} + +interface SiprecResource { + sid: string; + account_sid: string; + call_sid: string; + name: string; + status: SiprecStatus; + date_updated: Date; + uri: string; +} + +export class SiprecInstance { + protected _solution: SiprecContextSolution; + protected _context?: SiprecContext; + + constructor(protected _version: V2010, payload: SiprecResource, accountSid: string, callSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.callSid = (payload.call_sid); + this.name = (payload.name); + this.status = payload.status; + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.uri = (payload.uri); + + this._solution = { accountSid, callSid, sid: sid, }; + } + + /** + * The SID of the Siprec resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Siprec resource. + */ + accountSid: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Siprec resource is associated with. + */ + callSid: string; + /** + * The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + */ + name: string; + status: SiprecStatus; + /** + * The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): SiprecContext { + this._context = this._context || new SiprecContextImpl(this._version, this._solution.accountSid, this._solution.callSid, this._solution.sid); + return this._context; + } + + /** + * Update a SiprecInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SiprecInstance + */ + update(params: SiprecContextUpdateOptions, callback?: (error: Error | null, item?: SiprecInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: SiprecInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a SiprecInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SiprecInstance with HTTP metadata + */ + updateWithHttpInfo(params: SiprecContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + callSid: this.callSid, + name: this.name, + status: this.status, + dateUpdated: this.dateUpdated, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SiprecSolution { + accountSid: string; + callSid: string; +} + +export interface SiprecListInstance { + _version: V2010; + _solution: SiprecSolution; + _uri: string; + + (sid: string, ): SiprecContext; + get(sid: string, ): SiprecContext; + + + + + /** + * Create a SiprecInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SiprecInstance + */ + create(callback?: (error: Error | null, item?: SiprecInstance) => any): Promise; + /** + * Create a SiprecInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SiprecInstance + */ + create(params: SiprecListInstanceCreateOptions, callback?: (error: Error | null, item?: SiprecInstance) => any): Promise; + + /** + * Create a SiprecInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SiprecInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a SiprecInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SiprecInstance with HTTP metadata + */ + createWithHttpInfo(params: SiprecListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SiprecListInstance(version: V2010, accountSid: string, callSid: string): SiprecListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as SiprecListInstance; + + instance.get = function get(sid, ): SiprecContext { + return new SiprecContextImpl(version, accountSid, callSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, callSid, }; + instance._uri = `/Accounts/${accountSid}/Calls/${callSid}/Siprec.json`; + + instance.create = function create(params?: SiprecListInstanceCreateOptions | ((error: Error | null, items: SiprecInstance) => any), callback?: (error: Error | null, items: SiprecInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["name"] !== undefined) + data["Name"] = params["name"]; + if (params["connectorName"] !== undefined) + data["ConnectorName"] = params["connectorName"]; + if (params["track"] !== undefined) + data["Track"] = params["track"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["parameter1.name"] !== undefined) + data["Parameter1.Name"] = params["parameter1.name"]; + if (params["parameter1.value"] !== undefined) + data["Parameter1.Value"] = params["parameter1.value"]; + if (params["parameter2.name"] !== undefined) + data["Parameter2.Name"] = params["parameter2.name"]; + if (params["parameter2.value"] !== undefined) + data["Parameter2.Value"] = params["parameter2.value"]; + if (params["parameter3.name"] !== undefined) + data["Parameter3.Name"] = params["parameter3.name"]; + if (params["parameter3.value"] !== undefined) + data["Parameter3.Value"] = params["parameter3.value"]; + if (params["parameter4.name"] !== undefined) + data["Parameter4.Name"] = params["parameter4.name"]; + if (params["parameter4.value"] !== undefined) + data["Parameter4.Value"] = params["parameter4.value"]; + if (params["parameter5.name"] !== undefined) + data["Parameter5.Name"] = params["parameter5.name"]; + if (params["parameter5.value"] !== undefined) + data["Parameter5.Value"] = params["parameter5.value"]; + if (params["parameter6.name"] !== undefined) + data["Parameter6.Name"] = params["parameter6.name"]; + if (params["parameter6.value"] !== undefined) + data["Parameter6.Value"] = params["parameter6.value"]; + if (params["parameter7.name"] !== undefined) + data["Parameter7.Name"] = params["parameter7.name"]; + if (params["parameter7.value"] !== undefined) + data["Parameter7.Value"] = params["parameter7.value"]; + if (params["parameter8.name"] !== undefined) + data["Parameter8.Name"] = params["parameter8.name"]; + if (params["parameter8.value"] !== undefined) + data["Parameter8.Value"] = params["parameter8.value"]; + if (params["parameter9.name"] !== undefined) + data["Parameter9.Name"] = params["parameter9.name"]; + if (params["parameter9.value"] !== undefined) + data["Parameter9.Value"] = params["parameter9.value"]; + if (params["parameter10.name"] !== undefined) + data["Parameter10.Name"] = params["parameter10.name"]; + if (params["parameter10.value"] !== undefined) + data["Parameter10.Value"] = params["parameter10.value"]; + if (params["parameter11.name"] !== undefined) + data["Parameter11.Name"] = params["parameter11.name"]; + if (params["parameter11.value"] !== undefined) + data["Parameter11.Value"] = params["parameter11.value"]; + if (params["parameter12.name"] !== undefined) + data["Parameter12.Name"] = params["parameter12.name"]; + if (params["parameter12.value"] !== undefined) + data["Parameter12.Value"] = params["parameter12.value"]; + if (params["parameter13.name"] !== undefined) + data["Parameter13.Name"] = params["parameter13.name"]; + if (params["parameter13.value"] !== undefined) + data["Parameter13.Value"] = params["parameter13.value"]; + if (params["parameter14.name"] !== undefined) + data["Parameter14.Name"] = params["parameter14.name"]; + if (params["parameter14.value"] !== undefined) + data["Parameter14.Value"] = params["parameter14.value"]; + if (params["parameter15.name"] !== undefined) + data["Parameter15.Name"] = params["parameter15.name"]; + if (params["parameter15.value"] !== undefined) + data["Parameter15.Value"] = params["parameter15.value"]; + if (params["parameter16.name"] !== undefined) + data["Parameter16.Name"] = params["parameter16.name"]; + if (params["parameter16.value"] !== undefined) + data["Parameter16.Value"] = params["parameter16.value"]; + if (params["parameter17.name"] !== undefined) + data["Parameter17.Name"] = params["parameter17.name"]; + if (params["parameter17.value"] !== undefined) + data["Parameter17.Value"] = params["parameter17.value"]; + if (params["parameter18.name"] !== undefined) + data["Parameter18.Name"] = params["parameter18.name"]; + if (params["parameter18.value"] !== undefined) + data["Parameter18.Value"] = params["parameter18.value"]; + if (params["parameter19.name"] !== undefined) + data["Parameter19.Name"] = params["parameter19.name"]; + if (params["parameter19.value"] !== undefined) + data["Parameter19.Value"] = params["parameter19.value"]; + if (params["parameter20.name"] !== undefined) + data["Parameter20.Name"] = params["parameter20.name"]; + if (params["parameter20.value"] !== undefined) + data["Parameter20.Value"] = params["parameter20.value"]; + if (params["parameter21.name"] !== undefined) + data["Parameter21.Name"] = params["parameter21.name"]; + if (params["parameter21.value"] !== undefined) + data["Parameter21.Value"] = params["parameter21.value"]; + if (params["parameter22.name"] !== undefined) + data["Parameter22.Name"] = params["parameter22.name"]; + if (params["parameter22.value"] !== undefined) + data["Parameter22.Value"] = params["parameter22.value"]; + if (params["parameter23.name"] !== undefined) + data["Parameter23.Name"] = params["parameter23.name"]; + if (params["parameter23.value"] !== undefined) + data["Parameter23.Value"] = params["parameter23.value"]; + if (params["parameter24.name"] !== undefined) + data["Parameter24.Name"] = params["parameter24.name"]; + if (params["parameter24.value"] !== undefined) + data["Parameter24.Value"] = params["parameter24.value"]; + if (params["parameter25.name"] !== undefined) + data["Parameter25.Name"] = params["parameter25.name"]; + if (params["parameter25.value"] !== undefined) + data["Parameter25.Value"] = params["parameter25.value"]; + if (params["parameter26.name"] !== undefined) + data["Parameter26.Name"] = params["parameter26.name"]; + if (params["parameter26.value"] !== undefined) + data["Parameter26.Value"] = params["parameter26.value"]; + if (params["parameter27.name"] !== undefined) + data["Parameter27.Name"] = params["parameter27.name"]; + if (params["parameter27.value"] !== undefined) + data["Parameter27.Value"] = params["parameter27.value"]; + if (params["parameter28.name"] !== undefined) + data["Parameter28.Name"] = params["parameter28.name"]; + if (params["parameter28.value"] !== undefined) + data["Parameter28.Value"] = params["parameter28.value"]; + if (params["parameter29.name"] !== undefined) + data["Parameter29.Name"] = params["parameter29.name"]; + if (params["parameter29.value"] !== undefined) + data["Parameter29.Value"] = params["parameter29.value"]; + if (params["parameter30.name"] !== undefined) + data["Parameter30.Name"] = params["parameter30.name"]; + if (params["parameter30.value"] !== undefined) + data["Parameter30.Value"] = params["parameter30.value"]; + if (params["parameter31.name"] !== undefined) + data["Parameter31.Name"] = params["parameter31.name"]; + if (params["parameter31.value"] !== undefined) + data["Parameter31.Value"] = params["parameter31.value"]; + if (params["parameter32.name"] !== undefined) + data["Parameter32.Name"] = params["parameter32.name"]; + if (params["parameter32.value"] !== undefined) + data["Parameter32.Value"] = params["parameter32.value"]; + if (params["parameter33.name"] !== undefined) + data["Parameter33.Name"] = params["parameter33.name"]; + if (params["parameter33.value"] !== undefined) + data["Parameter33.Value"] = params["parameter33.value"]; + if (params["parameter34.name"] !== undefined) + data["Parameter34.Name"] = params["parameter34.name"]; + if (params["parameter34.value"] !== undefined) + data["Parameter34.Value"] = params["parameter34.value"]; + if (params["parameter35.name"] !== undefined) + data["Parameter35.Name"] = params["parameter35.name"]; + if (params["parameter35.value"] !== undefined) + data["Parameter35.Value"] = params["parameter35.value"]; + if (params["parameter36.name"] !== undefined) + data["Parameter36.Name"] = params["parameter36.name"]; + if (params["parameter36.value"] !== undefined) + data["Parameter36.Value"] = params["parameter36.value"]; + if (params["parameter37.name"] !== undefined) + data["Parameter37.Name"] = params["parameter37.name"]; + if (params["parameter37.value"] !== undefined) + data["Parameter37.Value"] = params["parameter37.value"]; + if (params["parameter38.name"] !== undefined) + data["Parameter38.Name"] = params["parameter38.name"]; + if (params["parameter38.value"] !== undefined) + data["Parameter38.Value"] = params["parameter38.value"]; + if (params["parameter39.name"] !== undefined) + data["Parameter39.Name"] = params["parameter39.name"]; + if (params["parameter39.value"] !== undefined) + data["Parameter39.Value"] = params["parameter39.value"]; + if (params["parameter40.name"] !== undefined) + data["Parameter40.Name"] = params["parameter40.name"]; + if (params["parameter40.value"] !== undefined) + data["Parameter40.Value"] = params["parameter40.value"]; + if (params["parameter41.name"] !== undefined) + data["Parameter41.Name"] = params["parameter41.name"]; + if (params["parameter41.value"] !== undefined) + data["Parameter41.Value"] = params["parameter41.value"]; + if (params["parameter42.name"] !== undefined) + data["Parameter42.Name"] = params["parameter42.name"]; + if (params["parameter42.value"] !== undefined) + data["Parameter42.Value"] = params["parameter42.value"]; + if (params["parameter43.name"] !== undefined) + data["Parameter43.Name"] = params["parameter43.name"]; + if (params["parameter43.value"] !== undefined) + data["Parameter43.Value"] = params["parameter43.value"]; + if (params["parameter44.name"] !== undefined) + data["Parameter44.Name"] = params["parameter44.name"]; + if (params["parameter44.value"] !== undefined) + data["Parameter44.Value"] = params["parameter44.value"]; + if (params["parameter45.name"] !== undefined) + data["Parameter45.Name"] = params["parameter45.name"]; + if (params["parameter45.value"] !== undefined) + data["Parameter45.Value"] = params["parameter45.value"]; + if (params["parameter46.name"] !== undefined) + data["Parameter46.Name"] = params["parameter46.name"]; + if (params["parameter46.value"] !== undefined) + data["Parameter46.Value"] = params["parameter46.value"]; + if (params["parameter47.name"] !== undefined) + data["Parameter47.Name"] = params["parameter47.name"]; + if (params["parameter47.value"] !== undefined) + data["Parameter47.Value"] = params["parameter47.value"]; + if (params["parameter48.name"] !== undefined) + data["Parameter48.Name"] = params["parameter48.name"]; + if (params["parameter48.value"] !== undefined) + data["Parameter48.Value"] = params["parameter48.value"]; + if (params["parameter49.name"] !== undefined) + data["Parameter49.Name"] = params["parameter49.name"]; + if (params["parameter49.value"] !== undefined) + data["Parameter49.Value"] = params["parameter49.value"]; + if (params["parameter50.name"] !== undefined) + data["Parameter50.Name"] = params["parameter50.name"]; + if (params["parameter50.value"] !== undefined) + data["Parameter50.Value"] = params["parameter50.value"]; + if (params["parameter51.name"] !== undefined) + data["Parameter51.Name"] = params["parameter51.name"]; + if (params["parameter51.value"] !== undefined) + data["Parameter51.Value"] = params["parameter51.value"]; + if (params["parameter52.name"] !== undefined) + data["Parameter52.Name"] = params["parameter52.name"]; + if (params["parameter52.value"] !== undefined) + data["Parameter52.Value"] = params["parameter52.value"]; + if (params["parameter53.name"] !== undefined) + data["Parameter53.Name"] = params["parameter53.name"]; + if (params["parameter53.value"] !== undefined) + data["Parameter53.Value"] = params["parameter53.value"]; + if (params["parameter54.name"] !== undefined) + data["Parameter54.Name"] = params["parameter54.name"]; + if (params["parameter54.value"] !== undefined) + data["Parameter54.Value"] = params["parameter54.value"]; + if (params["parameter55.name"] !== undefined) + data["Parameter55.Name"] = params["parameter55.name"]; + if (params["parameter55.value"] !== undefined) + data["Parameter55.Value"] = params["parameter55.value"]; + if (params["parameter56.name"] !== undefined) + data["Parameter56.Name"] = params["parameter56.name"]; + if (params["parameter56.value"] !== undefined) + data["Parameter56.Value"] = params["parameter56.value"]; + if (params["parameter57.name"] !== undefined) + data["Parameter57.Name"] = params["parameter57.name"]; + if (params["parameter57.value"] !== undefined) + data["Parameter57.Value"] = params["parameter57.value"]; + if (params["parameter58.name"] !== undefined) + data["Parameter58.Name"] = params["parameter58.name"]; + if (params["parameter58.value"] !== undefined) + data["Parameter58.Value"] = params["parameter58.value"]; + if (params["parameter59.name"] !== undefined) + data["Parameter59.Name"] = params["parameter59.name"]; + if (params["parameter59.value"] !== undefined) + data["Parameter59.Value"] = params["parameter59.value"]; + if (params["parameter60.name"] !== undefined) + data["Parameter60.Name"] = params["parameter60.name"]; + if (params["parameter60.value"] !== undefined) + data["Parameter60.Value"] = params["parameter60.value"]; + if (params["parameter61.name"] !== undefined) + data["Parameter61.Name"] = params["parameter61.name"]; + if (params["parameter61.value"] !== undefined) + data["Parameter61.Value"] = params["parameter61.value"]; + if (params["parameter62.name"] !== undefined) + data["Parameter62.Name"] = params["parameter62.name"]; + if (params["parameter62.value"] !== undefined) + data["Parameter62.Value"] = params["parameter62.value"]; + if (params["parameter63.name"] !== undefined) + data["Parameter63.Name"] = params["parameter63.name"]; + if (params["parameter63.value"] !== undefined) + data["Parameter63.Value"] = params["parameter63.value"]; + if (params["parameter64.name"] !== undefined) + data["Parameter64.Name"] = params["parameter64.name"]; + if (params["parameter64.value"] !== undefined) + data["Parameter64.Value"] = params["parameter64.value"]; + if (params["parameter65.name"] !== undefined) + data["Parameter65.Name"] = params["parameter65.name"]; + if (params["parameter65.value"] !== undefined) + data["Parameter65.Value"] = params["parameter65.value"]; + if (params["parameter66.name"] !== undefined) + data["Parameter66.Name"] = params["parameter66.name"]; + if (params["parameter66.value"] !== undefined) + data["Parameter66.Value"] = params["parameter66.value"]; + if (params["parameter67.name"] !== undefined) + data["Parameter67.Name"] = params["parameter67.name"]; + if (params["parameter67.value"] !== undefined) + data["Parameter67.Value"] = params["parameter67.value"]; + if (params["parameter68.name"] !== undefined) + data["Parameter68.Name"] = params["parameter68.name"]; + if (params["parameter68.value"] !== undefined) + data["Parameter68.Value"] = params["parameter68.value"]; + if (params["parameter69.name"] !== undefined) + data["Parameter69.Name"] = params["parameter69.name"]; + if (params["parameter69.value"] !== undefined) + data["Parameter69.Value"] = params["parameter69.value"]; + if (params["parameter70.name"] !== undefined) + data["Parameter70.Name"] = params["parameter70.name"]; + if (params["parameter70.value"] !== undefined) + data["Parameter70.Value"] = params["parameter70.value"]; + if (params["parameter71.name"] !== undefined) + data["Parameter71.Name"] = params["parameter71.name"]; + if (params["parameter71.value"] !== undefined) + data["Parameter71.Value"] = params["parameter71.value"]; + if (params["parameter72.name"] !== undefined) + data["Parameter72.Name"] = params["parameter72.name"]; + if (params["parameter72.value"] !== undefined) + data["Parameter72.Value"] = params["parameter72.value"]; + if (params["parameter73.name"] !== undefined) + data["Parameter73.Name"] = params["parameter73.name"]; + if (params["parameter73.value"] !== undefined) + data["Parameter73.Value"] = params["parameter73.value"]; + if (params["parameter74.name"] !== undefined) + data["Parameter74.Name"] = params["parameter74.name"]; + if (params["parameter74.value"] !== undefined) + data["Parameter74.Value"] = params["parameter74.value"]; + if (params["parameter75.name"] !== undefined) + data["Parameter75.Name"] = params["parameter75.name"]; + if (params["parameter75.value"] !== undefined) + data["Parameter75.Value"] = params["parameter75.value"]; + if (params["parameter76.name"] !== undefined) + data["Parameter76.Name"] = params["parameter76.name"]; + if (params["parameter76.value"] !== undefined) + data["Parameter76.Value"] = params["parameter76.value"]; + if (params["parameter77.name"] !== undefined) + data["Parameter77.Name"] = params["parameter77.name"]; + if (params["parameter77.value"] !== undefined) + data["Parameter77.Value"] = params["parameter77.value"]; + if (params["parameter78.name"] !== undefined) + data["Parameter78.Name"] = params["parameter78.name"]; + if (params["parameter78.value"] !== undefined) + data["Parameter78.Value"] = params["parameter78.value"]; + if (params["parameter79.name"] !== undefined) + data["Parameter79.Name"] = params["parameter79.name"]; + if (params["parameter79.value"] !== undefined) + data["Parameter79.Value"] = params["parameter79.value"]; + if (params["parameter80.name"] !== undefined) + data["Parameter80.Name"] = params["parameter80.name"]; + if (params["parameter80.value"] !== undefined) + data["Parameter80.Value"] = params["parameter80.value"]; + if (params["parameter81.name"] !== undefined) + data["Parameter81.Name"] = params["parameter81.name"]; + if (params["parameter81.value"] !== undefined) + data["Parameter81.Value"] = params["parameter81.value"]; + if (params["parameter82.name"] !== undefined) + data["Parameter82.Name"] = params["parameter82.name"]; + if (params["parameter82.value"] !== undefined) + data["Parameter82.Value"] = params["parameter82.value"]; + if (params["parameter83.name"] !== undefined) + data["Parameter83.Name"] = params["parameter83.name"]; + if (params["parameter83.value"] !== undefined) + data["Parameter83.Value"] = params["parameter83.value"]; + if (params["parameter84.name"] !== undefined) + data["Parameter84.Name"] = params["parameter84.name"]; + if (params["parameter84.value"] !== undefined) + data["Parameter84.Value"] = params["parameter84.value"]; + if (params["parameter85.name"] !== undefined) + data["Parameter85.Name"] = params["parameter85.name"]; + if (params["parameter85.value"] !== undefined) + data["Parameter85.Value"] = params["parameter85.value"]; + if (params["parameter86.name"] !== undefined) + data["Parameter86.Name"] = params["parameter86.name"]; + if (params["parameter86.value"] !== undefined) + data["Parameter86.Value"] = params["parameter86.value"]; + if (params["parameter87.name"] !== undefined) + data["Parameter87.Name"] = params["parameter87.name"]; + if (params["parameter87.value"] !== undefined) + data["Parameter87.Value"] = params["parameter87.value"]; + if (params["parameter88.name"] !== undefined) + data["Parameter88.Name"] = params["parameter88.name"]; + if (params["parameter88.value"] !== undefined) + data["Parameter88.Value"] = params["parameter88.value"]; + if (params["parameter89.name"] !== undefined) + data["Parameter89.Name"] = params["parameter89.name"]; + if (params["parameter89.value"] !== undefined) + data["Parameter89.Value"] = params["parameter89.value"]; + if (params["parameter90.name"] !== undefined) + data["Parameter90.Name"] = params["parameter90.name"]; + if (params["parameter90.value"] !== undefined) + data["Parameter90.Value"] = params["parameter90.value"]; + if (params["parameter91.name"] !== undefined) + data["Parameter91.Name"] = params["parameter91.name"]; + if (params["parameter91.value"] !== undefined) + data["Parameter91.Value"] = params["parameter91.value"]; + if (params["parameter92.name"] !== undefined) + data["Parameter92.Name"] = params["parameter92.name"]; + if (params["parameter92.value"] !== undefined) + data["Parameter92.Value"] = params["parameter92.value"]; + if (params["parameter93.name"] !== undefined) + data["Parameter93.Name"] = params["parameter93.name"]; + if (params["parameter93.value"] !== undefined) + data["Parameter93.Value"] = params["parameter93.value"]; + if (params["parameter94.name"] !== undefined) + data["Parameter94.Name"] = params["parameter94.name"]; + if (params["parameter94.value"] !== undefined) + data["Parameter94.Value"] = params["parameter94.value"]; + if (params["parameter95.name"] !== undefined) + data["Parameter95.Name"] = params["parameter95.name"]; + if (params["parameter95.value"] !== undefined) + data["Parameter95.Value"] = params["parameter95.value"]; + if (params["parameter96.name"] !== undefined) + data["Parameter96.Name"] = params["parameter96.name"]; + if (params["parameter96.value"] !== undefined) + data["Parameter96.Value"] = params["parameter96.value"]; + if (params["parameter97.name"] !== undefined) + data["Parameter97.Name"] = params["parameter97.name"]; + if (params["parameter97.value"] !== undefined) + data["Parameter97.Value"] = params["parameter97.value"]; + if (params["parameter98.name"] !== undefined) + data["Parameter98.Name"] = params["parameter98.name"]; + if (params["parameter98.value"] !== undefined) + data["Parameter98.Value"] = params["parameter98.value"]; + if (params["parameter99.name"] !== undefined) + data["Parameter99.Name"] = params["parameter99.name"]; + if (params["parameter99.value"] !== undefined) + data["Parameter99.Value"] = params["parameter99.value"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SiprecInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: SiprecListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["name"] !== undefined) + data["Name"] = params["name"]; + if (params["connectorName"] !== undefined) + data["ConnectorName"] = params["connectorName"]; + if (params["track"] !== undefined) + data["Track"] = params["track"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["parameter1.name"] !== undefined) + data["Parameter1.Name"] = params["parameter1.name"]; + if (params["parameter1.value"] !== undefined) + data["Parameter1.Value"] = params["parameter1.value"]; + if (params["parameter2.name"] !== undefined) + data["Parameter2.Name"] = params["parameter2.name"]; + if (params["parameter2.value"] !== undefined) + data["Parameter2.Value"] = params["parameter2.value"]; + if (params["parameter3.name"] !== undefined) + data["Parameter3.Name"] = params["parameter3.name"]; + if (params["parameter3.value"] !== undefined) + data["Parameter3.Value"] = params["parameter3.value"]; + if (params["parameter4.name"] !== undefined) + data["Parameter4.Name"] = params["parameter4.name"]; + if (params["parameter4.value"] !== undefined) + data["Parameter4.Value"] = params["parameter4.value"]; + if (params["parameter5.name"] !== undefined) + data["Parameter5.Name"] = params["parameter5.name"]; + if (params["parameter5.value"] !== undefined) + data["Parameter5.Value"] = params["parameter5.value"]; + if (params["parameter6.name"] !== undefined) + data["Parameter6.Name"] = params["parameter6.name"]; + if (params["parameter6.value"] !== undefined) + data["Parameter6.Value"] = params["parameter6.value"]; + if (params["parameter7.name"] !== undefined) + data["Parameter7.Name"] = params["parameter7.name"]; + if (params["parameter7.value"] !== undefined) + data["Parameter7.Value"] = params["parameter7.value"]; + if (params["parameter8.name"] !== undefined) + data["Parameter8.Name"] = params["parameter8.name"]; + if (params["parameter8.value"] !== undefined) + data["Parameter8.Value"] = params["parameter8.value"]; + if (params["parameter9.name"] !== undefined) + data["Parameter9.Name"] = params["parameter9.name"]; + if (params["parameter9.value"] !== undefined) + data["Parameter9.Value"] = params["parameter9.value"]; + if (params["parameter10.name"] !== undefined) + data["Parameter10.Name"] = params["parameter10.name"]; + if (params["parameter10.value"] !== undefined) + data["Parameter10.Value"] = params["parameter10.value"]; + if (params["parameter11.name"] !== undefined) + data["Parameter11.Name"] = params["parameter11.name"]; + if (params["parameter11.value"] !== undefined) + data["Parameter11.Value"] = params["parameter11.value"]; + if (params["parameter12.name"] !== undefined) + data["Parameter12.Name"] = params["parameter12.name"]; + if (params["parameter12.value"] !== undefined) + data["Parameter12.Value"] = params["parameter12.value"]; + if (params["parameter13.name"] !== undefined) + data["Parameter13.Name"] = params["parameter13.name"]; + if (params["parameter13.value"] !== undefined) + data["Parameter13.Value"] = params["parameter13.value"]; + if (params["parameter14.name"] !== undefined) + data["Parameter14.Name"] = params["parameter14.name"]; + if (params["parameter14.value"] !== undefined) + data["Parameter14.Value"] = params["parameter14.value"]; + if (params["parameter15.name"] !== undefined) + data["Parameter15.Name"] = params["parameter15.name"]; + if (params["parameter15.value"] !== undefined) + data["Parameter15.Value"] = params["parameter15.value"]; + if (params["parameter16.name"] !== undefined) + data["Parameter16.Name"] = params["parameter16.name"]; + if (params["parameter16.value"] !== undefined) + data["Parameter16.Value"] = params["parameter16.value"]; + if (params["parameter17.name"] !== undefined) + data["Parameter17.Name"] = params["parameter17.name"]; + if (params["parameter17.value"] !== undefined) + data["Parameter17.Value"] = params["parameter17.value"]; + if (params["parameter18.name"] !== undefined) + data["Parameter18.Name"] = params["parameter18.name"]; + if (params["parameter18.value"] !== undefined) + data["Parameter18.Value"] = params["parameter18.value"]; + if (params["parameter19.name"] !== undefined) + data["Parameter19.Name"] = params["parameter19.name"]; + if (params["parameter19.value"] !== undefined) + data["Parameter19.Value"] = params["parameter19.value"]; + if (params["parameter20.name"] !== undefined) + data["Parameter20.Name"] = params["parameter20.name"]; + if (params["parameter20.value"] !== undefined) + data["Parameter20.Value"] = params["parameter20.value"]; + if (params["parameter21.name"] !== undefined) + data["Parameter21.Name"] = params["parameter21.name"]; + if (params["parameter21.value"] !== undefined) + data["Parameter21.Value"] = params["parameter21.value"]; + if (params["parameter22.name"] !== undefined) + data["Parameter22.Name"] = params["parameter22.name"]; + if (params["parameter22.value"] !== undefined) + data["Parameter22.Value"] = params["parameter22.value"]; + if (params["parameter23.name"] !== undefined) + data["Parameter23.Name"] = params["parameter23.name"]; + if (params["parameter23.value"] !== undefined) + data["Parameter23.Value"] = params["parameter23.value"]; + if (params["parameter24.name"] !== undefined) + data["Parameter24.Name"] = params["parameter24.name"]; + if (params["parameter24.value"] !== undefined) + data["Parameter24.Value"] = params["parameter24.value"]; + if (params["parameter25.name"] !== undefined) + data["Parameter25.Name"] = params["parameter25.name"]; + if (params["parameter25.value"] !== undefined) + data["Parameter25.Value"] = params["parameter25.value"]; + if (params["parameter26.name"] !== undefined) + data["Parameter26.Name"] = params["parameter26.name"]; + if (params["parameter26.value"] !== undefined) + data["Parameter26.Value"] = params["parameter26.value"]; + if (params["parameter27.name"] !== undefined) + data["Parameter27.Name"] = params["parameter27.name"]; + if (params["parameter27.value"] !== undefined) + data["Parameter27.Value"] = params["parameter27.value"]; + if (params["parameter28.name"] !== undefined) + data["Parameter28.Name"] = params["parameter28.name"]; + if (params["parameter28.value"] !== undefined) + data["Parameter28.Value"] = params["parameter28.value"]; + if (params["parameter29.name"] !== undefined) + data["Parameter29.Name"] = params["parameter29.name"]; + if (params["parameter29.value"] !== undefined) + data["Parameter29.Value"] = params["parameter29.value"]; + if (params["parameter30.name"] !== undefined) + data["Parameter30.Name"] = params["parameter30.name"]; + if (params["parameter30.value"] !== undefined) + data["Parameter30.Value"] = params["parameter30.value"]; + if (params["parameter31.name"] !== undefined) + data["Parameter31.Name"] = params["parameter31.name"]; + if (params["parameter31.value"] !== undefined) + data["Parameter31.Value"] = params["parameter31.value"]; + if (params["parameter32.name"] !== undefined) + data["Parameter32.Name"] = params["parameter32.name"]; + if (params["parameter32.value"] !== undefined) + data["Parameter32.Value"] = params["parameter32.value"]; + if (params["parameter33.name"] !== undefined) + data["Parameter33.Name"] = params["parameter33.name"]; + if (params["parameter33.value"] !== undefined) + data["Parameter33.Value"] = params["parameter33.value"]; + if (params["parameter34.name"] !== undefined) + data["Parameter34.Name"] = params["parameter34.name"]; + if (params["parameter34.value"] !== undefined) + data["Parameter34.Value"] = params["parameter34.value"]; + if (params["parameter35.name"] !== undefined) + data["Parameter35.Name"] = params["parameter35.name"]; + if (params["parameter35.value"] !== undefined) + data["Parameter35.Value"] = params["parameter35.value"]; + if (params["parameter36.name"] !== undefined) + data["Parameter36.Name"] = params["parameter36.name"]; + if (params["parameter36.value"] !== undefined) + data["Parameter36.Value"] = params["parameter36.value"]; + if (params["parameter37.name"] !== undefined) + data["Parameter37.Name"] = params["parameter37.name"]; + if (params["parameter37.value"] !== undefined) + data["Parameter37.Value"] = params["parameter37.value"]; + if (params["parameter38.name"] !== undefined) + data["Parameter38.Name"] = params["parameter38.name"]; + if (params["parameter38.value"] !== undefined) + data["Parameter38.Value"] = params["parameter38.value"]; + if (params["parameter39.name"] !== undefined) + data["Parameter39.Name"] = params["parameter39.name"]; + if (params["parameter39.value"] !== undefined) + data["Parameter39.Value"] = params["parameter39.value"]; + if (params["parameter40.name"] !== undefined) + data["Parameter40.Name"] = params["parameter40.name"]; + if (params["parameter40.value"] !== undefined) + data["Parameter40.Value"] = params["parameter40.value"]; + if (params["parameter41.name"] !== undefined) + data["Parameter41.Name"] = params["parameter41.name"]; + if (params["parameter41.value"] !== undefined) + data["Parameter41.Value"] = params["parameter41.value"]; + if (params["parameter42.name"] !== undefined) + data["Parameter42.Name"] = params["parameter42.name"]; + if (params["parameter42.value"] !== undefined) + data["Parameter42.Value"] = params["parameter42.value"]; + if (params["parameter43.name"] !== undefined) + data["Parameter43.Name"] = params["parameter43.name"]; + if (params["parameter43.value"] !== undefined) + data["Parameter43.Value"] = params["parameter43.value"]; + if (params["parameter44.name"] !== undefined) + data["Parameter44.Name"] = params["parameter44.name"]; + if (params["parameter44.value"] !== undefined) + data["Parameter44.Value"] = params["parameter44.value"]; + if (params["parameter45.name"] !== undefined) + data["Parameter45.Name"] = params["parameter45.name"]; + if (params["parameter45.value"] !== undefined) + data["Parameter45.Value"] = params["parameter45.value"]; + if (params["parameter46.name"] !== undefined) + data["Parameter46.Name"] = params["parameter46.name"]; + if (params["parameter46.value"] !== undefined) + data["Parameter46.Value"] = params["parameter46.value"]; + if (params["parameter47.name"] !== undefined) + data["Parameter47.Name"] = params["parameter47.name"]; + if (params["parameter47.value"] !== undefined) + data["Parameter47.Value"] = params["parameter47.value"]; + if (params["parameter48.name"] !== undefined) + data["Parameter48.Name"] = params["parameter48.name"]; + if (params["parameter48.value"] !== undefined) + data["Parameter48.Value"] = params["parameter48.value"]; + if (params["parameter49.name"] !== undefined) + data["Parameter49.Name"] = params["parameter49.name"]; + if (params["parameter49.value"] !== undefined) + data["Parameter49.Value"] = params["parameter49.value"]; + if (params["parameter50.name"] !== undefined) + data["Parameter50.Name"] = params["parameter50.name"]; + if (params["parameter50.value"] !== undefined) + data["Parameter50.Value"] = params["parameter50.value"]; + if (params["parameter51.name"] !== undefined) + data["Parameter51.Name"] = params["parameter51.name"]; + if (params["parameter51.value"] !== undefined) + data["Parameter51.Value"] = params["parameter51.value"]; + if (params["parameter52.name"] !== undefined) + data["Parameter52.Name"] = params["parameter52.name"]; + if (params["parameter52.value"] !== undefined) + data["Parameter52.Value"] = params["parameter52.value"]; + if (params["parameter53.name"] !== undefined) + data["Parameter53.Name"] = params["parameter53.name"]; + if (params["parameter53.value"] !== undefined) + data["Parameter53.Value"] = params["parameter53.value"]; + if (params["parameter54.name"] !== undefined) + data["Parameter54.Name"] = params["parameter54.name"]; + if (params["parameter54.value"] !== undefined) + data["Parameter54.Value"] = params["parameter54.value"]; + if (params["parameter55.name"] !== undefined) + data["Parameter55.Name"] = params["parameter55.name"]; + if (params["parameter55.value"] !== undefined) + data["Parameter55.Value"] = params["parameter55.value"]; + if (params["parameter56.name"] !== undefined) + data["Parameter56.Name"] = params["parameter56.name"]; + if (params["parameter56.value"] !== undefined) + data["Parameter56.Value"] = params["parameter56.value"]; + if (params["parameter57.name"] !== undefined) + data["Parameter57.Name"] = params["parameter57.name"]; + if (params["parameter57.value"] !== undefined) + data["Parameter57.Value"] = params["parameter57.value"]; + if (params["parameter58.name"] !== undefined) + data["Parameter58.Name"] = params["parameter58.name"]; + if (params["parameter58.value"] !== undefined) + data["Parameter58.Value"] = params["parameter58.value"]; + if (params["parameter59.name"] !== undefined) + data["Parameter59.Name"] = params["parameter59.name"]; + if (params["parameter59.value"] !== undefined) + data["Parameter59.Value"] = params["parameter59.value"]; + if (params["parameter60.name"] !== undefined) + data["Parameter60.Name"] = params["parameter60.name"]; + if (params["parameter60.value"] !== undefined) + data["Parameter60.Value"] = params["parameter60.value"]; + if (params["parameter61.name"] !== undefined) + data["Parameter61.Name"] = params["parameter61.name"]; + if (params["parameter61.value"] !== undefined) + data["Parameter61.Value"] = params["parameter61.value"]; + if (params["parameter62.name"] !== undefined) + data["Parameter62.Name"] = params["parameter62.name"]; + if (params["parameter62.value"] !== undefined) + data["Parameter62.Value"] = params["parameter62.value"]; + if (params["parameter63.name"] !== undefined) + data["Parameter63.Name"] = params["parameter63.name"]; + if (params["parameter63.value"] !== undefined) + data["Parameter63.Value"] = params["parameter63.value"]; + if (params["parameter64.name"] !== undefined) + data["Parameter64.Name"] = params["parameter64.name"]; + if (params["parameter64.value"] !== undefined) + data["Parameter64.Value"] = params["parameter64.value"]; + if (params["parameter65.name"] !== undefined) + data["Parameter65.Name"] = params["parameter65.name"]; + if (params["parameter65.value"] !== undefined) + data["Parameter65.Value"] = params["parameter65.value"]; + if (params["parameter66.name"] !== undefined) + data["Parameter66.Name"] = params["parameter66.name"]; + if (params["parameter66.value"] !== undefined) + data["Parameter66.Value"] = params["parameter66.value"]; + if (params["parameter67.name"] !== undefined) + data["Parameter67.Name"] = params["parameter67.name"]; + if (params["parameter67.value"] !== undefined) + data["Parameter67.Value"] = params["parameter67.value"]; + if (params["parameter68.name"] !== undefined) + data["Parameter68.Name"] = params["parameter68.name"]; + if (params["parameter68.value"] !== undefined) + data["Parameter68.Value"] = params["parameter68.value"]; + if (params["parameter69.name"] !== undefined) + data["Parameter69.Name"] = params["parameter69.name"]; + if (params["parameter69.value"] !== undefined) + data["Parameter69.Value"] = params["parameter69.value"]; + if (params["parameter70.name"] !== undefined) + data["Parameter70.Name"] = params["parameter70.name"]; + if (params["parameter70.value"] !== undefined) + data["Parameter70.Value"] = params["parameter70.value"]; + if (params["parameter71.name"] !== undefined) + data["Parameter71.Name"] = params["parameter71.name"]; + if (params["parameter71.value"] !== undefined) + data["Parameter71.Value"] = params["parameter71.value"]; + if (params["parameter72.name"] !== undefined) + data["Parameter72.Name"] = params["parameter72.name"]; + if (params["parameter72.value"] !== undefined) + data["Parameter72.Value"] = params["parameter72.value"]; + if (params["parameter73.name"] !== undefined) + data["Parameter73.Name"] = params["parameter73.name"]; + if (params["parameter73.value"] !== undefined) + data["Parameter73.Value"] = params["parameter73.value"]; + if (params["parameter74.name"] !== undefined) + data["Parameter74.Name"] = params["parameter74.name"]; + if (params["parameter74.value"] !== undefined) + data["Parameter74.Value"] = params["parameter74.value"]; + if (params["parameter75.name"] !== undefined) + data["Parameter75.Name"] = params["parameter75.name"]; + if (params["parameter75.value"] !== undefined) + data["Parameter75.Value"] = params["parameter75.value"]; + if (params["parameter76.name"] !== undefined) + data["Parameter76.Name"] = params["parameter76.name"]; + if (params["parameter76.value"] !== undefined) + data["Parameter76.Value"] = params["parameter76.value"]; + if (params["parameter77.name"] !== undefined) + data["Parameter77.Name"] = params["parameter77.name"]; + if (params["parameter77.value"] !== undefined) + data["Parameter77.Value"] = params["parameter77.value"]; + if (params["parameter78.name"] !== undefined) + data["Parameter78.Name"] = params["parameter78.name"]; + if (params["parameter78.value"] !== undefined) + data["Parameter78.Value"] = params["parameter78.value"]; + if (params["parameter79.name"] !== undefined) + data["Parameter79.Name"] = params["parameter79.name"]; + if (params["parameter79.value"] !== undefined) + data["Parameter79.Value"] = params["parameter79.value"]; + if (params["parameter80.name"] !== undefined) + data["Parameter80.Name"] = params["parameter80.name"]; + if (params["parameter80.value"] !== undefined) + data["Parameter80.Value"] = params["parameter80.value"]; + if (params["parameter81.name"] !== undefined) + data["Parameter81.Name"] = params["parameter81.name"]; + if (params["parameter81.value"] !== undefined) + data["Parameter81.Value"] = params["parameter81.value"]; + if (params["parameter82.name"] !== undefined) + data["Parameter82.Name"] = params["parameter82.name"]; + if (params["parameter82.value"] !== undefined) + data["Parameter82.Value"] = params["parameter82.value"]; + if (params["parameter83.name"] !== undefined) + data["Parameter83.Name"] = params["parameter83.name"]; + if (params["parameter83.value"] !== undefined) + data["Parameter83.Value"] = params["parameter83.value"]; + if (params["parameter84.name"] !== undefined) + data["Parameter84.Name"] = params["parameter84.name"]; + if (params["parameter84.value"] !== undefined) + data["Parameter84.Value"] = params["parameter84.value"]; + if (params["parameter85.name"] !== undefined) + data["Parameter85.Name"] = params["parameter85.name"]; + if (params["parameter85.value"] !== undefined) + data["Parameter85.Value"] = params["parameter85.value"]; + if (params["parameter86.name"] !== undefined) + data["Parameter86.Name"] = params["parameter86.name"]; + if (params["parameter86.value"] !== undefined) + data["Parameter86.Value"] = params["parameter86.value"]; + if (params["parameter87.name"] !== undefined) + data["Parameter87.Name"] = params["parameter87.name"]; + if (params["parameter87.value"] !== undefined) + data["Parameter87.Value"] = params["parameter87.value"]; + if (params["parameter88.name"] !== undefined) + data["Parameter88.Name"] = params["parameter88.name"]; + if (params["parameter88.value"] !== undefined) + data["Parameter88.Value"] = params["parameter88.value"]; + if (params["parameter89.name"] !== undefined) + data["Parameter89.Name"] = params["parameter89.name"]; + if (params["parameter89.value"] !== undefined) + data["Parameter89.Value"] = params["parameter89.value"]; + if (params["parameter90.name"] !== undefined) + data["Parameter90.Name"] = params["parameter90.name"]; + if (params["parameter90.value"] !== undefined) + data["Parameter90.Value"] = params["parameter90.value"]; + if (params["parameter91.name"] !== undefined) + data["Parameter91.Name"] = params["parameter91.name"]; + if (params["parameter91.value"] !== undefined) + data["Parameter91.Value"] = params["parameter91.value"]; + if (params["parameter92.name"] !== undefined) + data["Parameter92.Name"] = params["parameter92.name"]; + if (params["parameter92.value"] !== undefined) + data["Parameter92.Value"] = params["parameter92.value"]; + if (params["parameter93.name"] !== undefined) + data["Parameter93.Name"] = params["parameter93.name"]; + if (params["parameter93.value"] !== undefined) + data["Parameter93.Value"] = params["parameter93.value"]; + if (params["parameter94.name"] !== undefined) + data["Parameter94.Name"] = params["parameter94.name"]; + if (params["parameter94.value"] !== undefined) + data["Parameter94.Value"] = params["parameter94.value"]; + if (params["parameter95.name"] !== undefined) + data["Parameter95.Name"] = params["parameter95.name"]; + if (params["parameter95.value"] !== undefined) + data["Parameter95.Value"] = params["parameter95.value"]; + if (params["parameter96.name"] !== undefined) + data["Parameter96.Name"] = params["parameter96.name"]; + if (params["parameter96.value"] !== undefined) + data["Parameter96.Value"] = params["parameter96.value"]; + if (params["parameter97.name"] !== undefined) + data["Parameter97.Name"] = params["parameter97.name"]; + if (params["parameter97.value"] !== undefined) + data["Parameter97.Value"] = params["parameter97.value"]; + if (params["parameter98.name"] !== undefined) + data["Parameter98.Name"] = params["parameter98.name"]; + if (params["parameter98.value"] !== undefined) + data["Parameter98.Value"] = params["parameter98.value"]; + if (params["parameter99.name"] !== undefined) + data["Parameter99.Name"] = params["parameter99.name"]; + if (params["parameter99.value"] !== undefined) + data["Parameter99.Value"] = params["parameter99.value"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SiprecInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/api/v2010/account/call/stream.ts b/rest/api/v2010/account/call/stream.ts new file mode 100644 index 000000000..461745b86 --- /dev/null +++ b/rest/api/v2010/account/call/stream.ts @@ -0,0 +1,1665 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The status of the Stream. Possible values are `stopped` and `in-progress`. + */ +export type StreamStatus = 'in-progress'|'stopped'; + +/** + * The tracks to be included in the Stream. Possible values are `inbound_track`, `outbound_track`, `both_tracks`. Default value is `inbound_track`. + */ +export type StreamTrack = 'inbound_track'|'outbound_track'|'both_tracks'; + +export type StreamUpdateStatus = 'stopped'; + + +/** + * Options to pass to update a StreamInstance + */ +export interface StreamContextUpdateOptions { + /** */ + "status": StreamUpdateStatus; +} + +/** + * Options to pass to create a StreamInstance + */ +export interface StreamListInstanceCreateOptions { + /** Relative or absolute URL where WebSocket connection will be established. */ + "url": string; + /** The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. */ + "name"?: string; + /** */ + "track"?: StreamTrack; + /** Absolute URL to which Twilio sends status callback HTTP requests. */ + "statusCallback"?: string; + /** The HTTP method Twilio uses when sending `status_callback` requests. Possible values are `GET` and `POST`. Default is `POST`. */ + "statusCallbackMethod"?: string; + /** Parameter name */ + "parameter1.name"?: string; + /** Parameter value */ + "parameter1.value"?: string; + /** Parameter name */ + "parameter2.name"?: string; + /** Parameter value */ + "parameter2.value"?: string; + /** Parameter name */ + "parameter3.name"?: string; + /** Parameter value */ + "parameter3.value"?: string; + /** Parameter name */ + "parameter4.name"?: string; + /** Parameter value */ + "parameter4.value"?: string; + /** Parameter name */ + "parameter5.name"?: string; + /** Parameter value */ + "parameter5.value"?: string; + /** Parameter name */ + "parameter6.name"?: string; + /** Parameter value */ + "parameter6.value"?: string; + /** Parameter name */ + "parameter7.name"?: string; + /** Parameter value */ + "parameter7.value"?: string; + /** Parameter name */ + "parameter8.name"?: string; + /** Parameter value */ + "parameter8.value"?: string; + /** Parameter name */ + "parameter9.name"?: string; + /** Parameter value */ + "parameter9.value"?: string; + /** Parameter name */ + "parameter10.name"?: string; + /** Parameter value */ + "parameter10.value"?: string; + /** Parameter name */ + "parameter11.name"?: string; + /** Parameter value */ + "parameter11.value"?: string; + /** Parameter name */ + "parameter12.name"?: string; + /** Parameter value */ + "parameter12.value"?: string; + /** Parameter name */ + "parameter13.name"?: string; + /** Parameter value */ + "parameter13.value"?: string; + /** Parameter name */ + "parameter14.name"?: string; + /** Parameter value */ + "parameter14.value"?: string; + /** Parameter name */ + "parameter15.name"?: string; + /** Parameter value */ + "parameter15.value"?: string; + /** Parameter name */ + "parameter16.name"?: string; + /** Parameter value */ + "parameter16.value"?: string; + /** Parameter name */ + "parameter17.name"?: string; + /** Parameter value */ + "parameter17.value"?: string; + /** Parameter name */ + "parameter18.name"?: string; + /** Parameter value */ + "parameter18.value"?: string; + /** Parameter name */ + "parameter19.name"?: string; + /** Parameter value */ + "parameter19.value"?: string; + /** Parameter name */ + "parameter20.name"?: string; + /** Parameter value */ + "parameter20.value"?: string; + /** Parameter name */ + "parameter21.name"?: string; + /** Parameter value */ + "parameter21.value"?: string; + /** Parameter name */ + "parameter22.name"?: string; + /** Parameter value */ + "parameter22.value"?: string; + /** Parameter name */ + "parameter23.name"?: string; + /** Parameter value */ + "parameter23.value"?: string; + /** Parameter name */ + "parameter24.name"?: string; + /** Parameter value */ + "parameter24.value"?: string; + /** Parameter name */ + "parameter25.name"?: string; + /** Parameter value */ + "parameter25.value"?: string; + /** Parameter name */ + "parameter26.name"?: string; + /** Parameter value */ + "parameter26.value"?: string; + /** Parameter name */ + "parameter27.name"?: string; + /** Parameter value */ + "parameter27.value"?: string; + /** Parameter name */ + "parameter28.name"?: string; + /** Parameter value */ + "parameter28.value"?: string; + /** Parameter name */ + "parameter29.name"?: string; + /** Parameter value */ + "parameter29.value"?: string; + /** Parameter name */ + "parameter30.name"?: string; + /** Parameter value */ + "parameter30.value"?: string; + /** Parameter name */ + "parameter31.name"?: string; + /** Parameter value */ + "parameter31.value"?: string; + /** Parameter name */ + "parameter32.name"?: string; + /** Parameter value */ + "parameter32.value"?: string; + /** Parameter name */ + "parameter33.name"?: string; + /** Parameter value */ + "parameter33.value"?: string; + /** Parameter name */ + "parameter34.name"?: string; + /** Parameter value */ + "parameter34.value"?: string; + /** Parameter name */ + "parameter35.name"?: string; + /** Parameter value */ + "parameter35.value"?: string; + /** Parameter name */ + "parameter36.name"?: string; + /** Parameter value */ + "parameter36.value"?: string; + /** Parameter name */ + "parameter37.name"?: string; + /** Parameter value */ + "parameter37.value"?: string; + /** Parameter name */ + "parameter38.name"?: string; + /** Parameter value */ + "parameter38.value"?: string; + /** Parameter name */ + "parameter39.name"?: string; + /** Parameter value */ + "parameter39.value"?: string; + /** Parameter name */ + "parameter40.name"?: string; + /** Parameter value */ + "parameter40.value"?: string; + /** Parameter name */ + "parameter41.name"?: string; + /** Parameter value */ + "parameter41.value"?: string; + /** Parameter name */ + "parameter42.name"?: string; + /** Parameter value */ + "parameter42.value"?: string; + /** Parameter name */ + "parameter43.name"?: string; + /** Parameter value */ + "parameter43.value"?: string; + /** Parameter name */ + "parameter44.name"?: string; + /** Parameter value */ + "parameter44.value"?: string; + /** Parameter name */ + "parameter45.name"?: string; + /** Parameter value */ + "parameter45.value"?: string; + /** Parameter name */ + "parameter46.name"?: string; + /** Parameter value */ + "parameter46.value"?: string; + /** Parameter name */ + "parameter47.name"?: string; + /** Parameter value */ + "parameter47.value"?: string; + /** Parameter name */ + "parameter48.name"?: string; + /** Parameter value */ + "parameter48.value"?: string; + /** Parameter name */ + "parameter49.name"?: string; + /** Parameter value */ + "parameter49.value"?: string; + /** Parameter name */ + "parameter50.name"?: string; + /** Parameter value */ + "parameter50.value"?: string; + /** Parameter name */ + "parameter51.name"?: string; + /** Parameter value */ + "parameter51.value"?: string; + /** Parameter name */ + "parameter52.name"?: string; + /** Parameter value */ + "parameter52.value"?: string; + /** Parameter name */ + "parameter53.name"?: string; + /** Parameter value */ + "parameter53.value"?: string; + /** Parameter name */ + "parameter54.name"?: string; + /** Parameter value */ + "parameter54.value"?: string; + /** Parameter name */ + "parameter55.name"?: string; + /** Parameter value */ + "parameter55.value"?: string; + /** Parameter name */ + "parameter56.name"?: string; + /** Parameter value */ + "parameter56.value"?: string; + /** Parameter name */ + "parameter57.name"?: string; + /** Parameter value */ + "parameter57.value"?: string; + /** Parameter name */ + "parameter58.name"?: string; + /** Parameter value */ + "parameter58.value"?: string; + /** Parameter name */ + "parameter59.name"?: string; + /** Parameter value */ + "parameter59.value"?: string; + /** Parameter name */ + "parameter60.name"?: string; + /** Parameter value */ + "parameter60.value"?: string; + /** Parameter name */ + "parameter61.name"?: string; + /** Parameter value */ + "parameter61.value"?: string; + /** Parameter name */ + "parameter62.name"?: string; + /** Parameter value */ + "parameter62.value"?: string; + /** Parameter name */ + "parameter63.name"?: string; + /** Parameter value */ + "parameter63.value"?: string; + /** Parameter name */ + "parameter64.name"?: string; + /** Parameter value */ + "parameter64.value"?: string; + /** Parameter name */ + "parameter65.name"?: string; + /** Parameter value */ + "parameter65.value"?: string; + /** Parameter name */ + "parameter66.name"?: string; + /** Parameter value */ + "parameter66.value"?: string; + /** Parameter name */ + "parameter67.name"?: string; + /** Parameter value */ + "parameter67.value"?: string; + /** Parameter name */ + "parameter68.name"?: string; + /** Parameter value */ + "parameter68.value"?: string; + /** Parameter name */ + "parameter69.name"?: string; + /** Parameter value */ + "parameter69.value"?: string; + /** Parameter name */ + "parameter70.name"?: string; + /** Parameter value */ + "parameter70.value"?: string; + /** Parameter name */ + "parameter71.name"?: string; + /** Parameter value */ + "parameter71.value"?: string; + /** Parameter name */ + "parameter72.name"?: string; + /** Parameter value */ + "parameter72.value"?: string; + /** Parameter name */ + "parameter73.name"?: string; + /** Parameter value */ + "parameter73.value"?: string; + /** Parameter name */ + "parameter74.name"?: string; + /** Parameter value */ + "parameter74.value"?: string; + /** Parameter name */ + "parameter75.name"?: string; + /** Parameter value */ + "parameter75.value"?: string; + /** Parameter name */ + "parameter76.name"?: string; + /** Parameter value */ + "parameter76.value"?: string; + /** Parameter name */ + "parameter77.name"?: string; + /** Parameter value */ + "parameter77.value"?: string; + /** Parameter name */ + "parameter78.name"?: string; + /** Parameter value */ + "parameter78.value"?: string; + /** Parameter name */ + "parameter79.name"?: string; + /** Parameter value */ + "parameter79.value"?: string; + /** Parameter name */ + "parameter80.name"?: string; + /** Parameter value */ + "parameter80.value"?: string; + /** Parameter name */ + "parameter81.name"?: string; + /** Parameter value */ + "parameter81.value"?: string; + /** Parameter name */ + "parameter82.name"?: string; + /** Parameter value */ + "parameter82.value"?: string; + /** Parameter name */ + "parameter83.name"?: string; + /** Parameter value */ + "parameter83.value"?: string; + /** Parameter name */ + "parameter84.name"?: string; + /** Parameter value */ + "parameter84.value"?: string; + /** Parameter name */ + "parameter85.name"?: string; + /** Parameter value */ + "parameter85.value"?: string; + /** Parameter name */ + "parameter86.name"?: string; + /** Parameter value */ + "parameter86.value"?: string; + /** Parameter name */ + "parameter87.name"?: string; + /** Parameter value */ + "parameter87.value"?: string; + /** Parameter name */ + "parameter88.name"?: string; + /** Parameter value */ + "parameter88.value"?: string; + /** Parameter name */ + "parameter89.name"?: string; + /** Parameter value */ + "parameter89.value"?: string; + /** Parameter name */ + "parameter90.name"?: string; + /** Parameter value */ + "parameter90.value"?: string; + /** Parameter name */ + "parameter91.name"?: string; + /** Parameter value */ + "parameter91.value"?: string; + /** Parameter name */ + "parameter92.name"?: string; + /** Parameter value */ + "parameter92.value"?: string; + /** Parameter name */ + "parameter93.name"?: string; + /** Parameter value */ + "parameter93.value"?: string; + /** Parameter name */ + "parameter94.name"?: string; + /** Parameter value */ + "parameter94.value"?: string; + /** Parameter name */ + "parameter95.name"?: string; + /** Parameter value */ + "parameter95.value"?: string; + /** Parameter name */ + "parameter96.name"?: string; + /** Parameter value */ + "parameter96.value"?: string; + /** Parameter name */ + "parameter97.name"?: string; + /** Parameter value */ + "parameter97.value"?: string; + /** Parameter name */ + "parameter98.name"?: string; + /** Parameter value */ + "parameter98.value"?: string; + /** Parameter name */ + "parameter99.name"?: string; + /** Parameter value */ + "parameter99.value"?: string; +} + +export interface StreamContext { + + /** + * Update a StreamInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StreamInstance + */ + update(params: StreamContextUpdateOptions, callback?: (error: Error | null, item?: StreamInstance) => any): Promise; + + /** + * Update a StreamInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StreamInstance with HTTP metadata + */ + updateWithHttpInfo(params: StreamContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface StreamContextSolution { + "accountSid": string; + "callSid": string; + "sid": string; +} + +export class StreamContextImpl implements StreamContext { + protected _solution: StreamContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, callSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, callSid, sid, }; + this._uri = `/Accounts/${accountSid}/Calls/${callSid}/Streams/${sid}.json`; + } + + update(params: StreamContextUpdateOptions,callback?: (error: Error | null, item?: StreamInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new StreamInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: StreamContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new StreamInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface StreamPayload extends StreamResource {} + +interface StreamResource { + sid: string; + account_sid: string; + call_sid: string; + name: string; + status: StreamStatus; + date_updated: Date; + uri: string; +} + +export class StreamInstance { + protected _solution: StreamContextSolution; + protected _context?: StreamContext; + + constructor(protected _version: V2010, payload: StreamResource, accountSid: string, callSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.callSid = (payload.call_sid); + this.name = (payload.name); + this.status = payload.status; + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.uri = (payload.uri); + + this._solution = { accountSid, callSid, sid: sid, }; + } + + /** + * The SID of the Stream resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Stream resource. + */ + accountSid: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Stream resource is associated with. + */ + callSid: string; + /** + * The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + */ + name: string; + status: StreamStatus; + /** + * The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): StreamContext { + this._context = this._context || new StreamContextImpl(this._version, this._solution.accountSid, this._solution.callSid, this._solution.sid); + return this._context; + } + + /** + * Update a StreamInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StreamInstance + */ + update(params: StreamContextUpdateOptions, callback?: (error: Error | null, item?: StreamInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: StreamInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a StreamInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StreamInstance with HTTP metadata + */ + updateWithHttpInfo(params: StreamContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + callSid: this.callSid, + name: this.name, + status: this.status, + dateUpdated: this.dateUpdated, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface StreamSolution { + accountSid: string; + callSid: string; +} + +export interface StreamListInstance { + _version: V2010; + _solution: StreamSolution; + _uri: string; + + (sid: string, ): StreamContext; + get(sid: string, ): StreamContext; + + + + + /** + * Create a StreamInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StreamInstance + */ + create(params: StreamListInstanceCreateOptions, callback?: (error: Error | null, item?: StreamInstance) => any): Promise; + + /** + * Create a StreamInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StreamInstance with HTTP metadata + */ + createWithHttpInfo(params: StreamListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function StreamListInstance(version: V2010, accountSid: string, callSid: string): StreamListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as StreamListInstance; + + instance.get = function get(sid, ): StreamContext { + return new StreamContextImpl(version, accountSid, callSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, callSid, }; + instance._uri = `/Accounts/${accountSid}/Calls/${callSid}/Streams.json`; + + instance.create = function create(params: StreamListInstanceCreateOptions, callback?: (error: Error | null, items: StreamInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["url"] === null || params["url"] === undefined) { + throw new Error('Required parameter "params[\'url\']" missing.'); + } + + let data: any = {}; + + + + data["Url"] = params["url"]; + if (params["name"] !== undefined) + data["Name"] = params["name"]; + if (params["track"] !== undefined) + data["Track"] = params["track"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["parameter1.name"] !== undefined) + data["Parameter1.Name"] = params["parameter1.name"]; + if (params["parameter1.value"] !== undefined) + data["Parameter1.Value"] = params["parameter1.value"]; + if (params["parameter2.name"] !== undefined) + data["Parameter2.Name"] = params["parameter2.name"]; + if (params["parameter2.value"] !== undefined) + data["Parameter2.Value"] = params["parameter2.value"]; + if (params["parameter3.name"] !== undefined) + data["Parameter3.Name"] = params["parameter3.name"]; + if (params["parameter3.value"] !== undefined) + data["Parameter3.Value"] = params["parameter3.value"]; + if (params["parameter4.name"] !== undefined) + data["Parameter4.Name"] = params["parameter4.name"]; + if (params["parameter4.value"] !== undefined) + data["Parameter4.Value"] = params["parameter4.value"]; + if (params["parameter5.name"] !== undefined) + data["Parameter5.Name"] = params["parameter5.name"]; + if (params["parameter5.value"] !== undefined) + data["Parameter5.Value"] = params["parameter5.value"]; + if (params["parameter6.name"] !== undefined) + data["Parameter6.Name"] = params["parameter6.name"]; + if (params["parameter6.value"] !== undefined) + data["Parameter6.Value"] = params["parameter6.value"]; + if (params["parameter7.name"] !== undefined) + data["Parameter7.Name"] = params["parameter7.name"]; + if (params["parameter7.value"] !== undefined) + data["Parameter7.Value"] = params["parameter7.value"]; + if (params["parameter8.name"] !== undefined) + data["Parameter8.Name"] = params["parameter8.name"]; + if (params["parameter8.value"] !== undefined) + data["Parameter8.Value"] = params["parameter8.value"]; + if (params["parameter9.name"] !== undefined) + data["Parameter9.Name"] = params["parameter9.name"]; + if (params["parameter9.value"] !== undefined) + data["Parameter9.Value"] = params["parameter9.value"]; + if (params["parameter10.name"] !== undefined) + data["Parameter10.Name"] = params["parameter10.name"]; + if (params["parameter10.value"] !== undefined) + data["Parameter10.Value"] = params["parameter10.value"]; + if (params["parameter11.name"] !== undefined) + data["Parameter11.Name"] = params["parameter11.name"]; + if (params["parameter11.value"] !== undefined) + data["Parameter11.Value"] = params["parameter11.value"]; + if (params["parameter12.name"] !== undefined) + data["Parameter12.Name"] = params["parameter12.name"]; + if (params["parameter12.value"] !== undefined) + data["Parameter12.Value"] = params["parameter12.value"]; + if (params["parameter13.name"] !== undefined) + data["Parameter13.Name"] = params["parameter13.name"]; + if (params["parameter13.value"] !== undefined) + data["Parameter13.Value"] = params["parameter13.value"]; + if (params["parameter14.name"] !== undefined) + data["Parameter14.Name"] = params["parameter14.name"]; + if (params["parameter14.value"] !== undefined) + data["Parameter14.Value"] = params["parameter14.value"]; + if (params["parameter15.name"] !== undefined) + data["Parameter15.Name"] = params["parameter15.name"]; + if (params["parameter15.value"] !== undefined) + data["Parameter15.Value"] = params["parameter15.value"]; + if (params["parameter16.name"] !== undefined) + data["Parameter16.Name"] = params["parameter16.name"]; + if (params["parameter16.value"] !== undefined) + data["Parameter16.Value"] = params["parameter16.value"]; + if (params["parameter17.name"] !== undefined) + data["Parameter17.Name"] = params["parameter17.name"]; + if (params["parameter17.value"] !== undefined) + data["Parameter17.Value"] = params["parameter17.value"]; + if (params["parameter18.name"] !== undefined) + data["Parameter18.Name"] = params["parameter18.name"]; + if (params["parameter18.value"] !== undefined) + data["Parameter18.Value"] = params["parameter18.value"]; + if (params["parameter19.name"] !== undefined) + data["Parameter19.Name"] = params["parameter19.name"]; + if (params["parameter19.value"] !== undefined) + data["Parameter19.Value"] = params["parameter19.value"]; + if (params["parameter20.name"] !== undefined) + data["Parameter20.Name"] = params["parameter20.name"]; + if (params["parameter20.value"] !== undefined) + data["Parameter20.Value"] = params["parameter20.value"]; + if (params["parameter21.name"] !== undefined) + data["Parameter21.Name"] = params["parameter21.name"]; + if (params["parameter21.value"] !== undefined) + data["Parameter21.Value"] = params["parameter21.value"]; + if (params["parameter22.name"] !== undefined) + data["Parameter22.Name"] = params["parameter22.name"]; + if (params["parameter22.value"] !== undefined) + data["Parameter22.Value"] = params["parameter22.value"]; + if (params["parameter23.name"] !== undefined) + data["Parameter23.Name"] = params["parameter23.name"]; + if (params["parameter23.value"] !== undefined) + data["Parameter23.Value"] = params["parameter23.value"]; + if (params["parameter24.name"] !== undefined) + data["Parameter24.Name"] = params["parameter24.name"]; + if (params["parameter24.value"] !== undefined) + data["Parameter24.Value"] = params["parameter24.value"]; + if (params["parameter25.name"] !== undefined) + data["Parameter25.Name"] = params["parameter25.name"]; + if (params["parameter25.value"] !== undefined) + data["Parameter25.Value"] = params["parameter25.value"]; + if (params["parameter26.name"] !== undefined) + data["Parameter26.Name"] = params["parameter26.name"]; + if (params["parameter26.value"] !== undefined) + data["Parameter26.Value"] = params["parameter26.value"]; + if (params["parameter27.name"] !== undefined) + data["Parameter27.Name"] = params["parameter27.name"]; + if (params["parameter27.value"] !== undefined) + data["Parameter27.Value"] = params["parameter27.value"]; + if (params["parameter28.name"] !== undefined) + data["Parameter28.Name"] = params["parameter28.name"]; + if (params["parameter28.value"] !== undefined) + data["Parameter28.Value"] = params["parameter28.value"]; + if (params["parameter29.name"] !== undefined) + data["Parameter29.Name"] = params["parameter29.name"]; + if (params["parameter29.value"] !== undefined) + data["Parameter29.Value"] = params["parameter29.value"]; + if (params["parameter30.name"] !== undefined) + data["Parameter30.Name"] = params["parameter30.name"]; + if (params["parameter30.value"] !== undefined) + data["Parameter30.Value"] = params["parameter30.value"]; + if (params["parameter31.name"] !== undefined) + data["Parameter31.Name"] = params["parameter31.name"]; + if (params["parameter31.value"] !== undefined) + data["Parameter31.Value"] = params["parameter31.value"]; + if (params["parameter32.name"] !== undefined) + data["Parameter32.Name"] = params["parameter32.name"]; + if (params["parameter32.value"] !== undefined) + data["Parameter32.Value"] = params["parameter32.value"]; + if (params["parameter33.name"] !== undefined) + data["Parameter33.Name"] = params["parameter33.name"]; + if (params["parameter33.value"] !== undefined) + data["Parameter33.Value"] = params["parameter33.value"]; + if (params["parameter34.name"] !== undefined) + data["Parameter34.Name"] = params["parameter34.name"]; + if (params["parameter34.value"] !== undefined) + data["Parameter34.Value"] = params["parameter34.value"]; + if (params["parameter35.name"] !== undefined) + data["Parameter35.Name"] = params["parameter35.name"]; + if (params["parameter35.value"] !== undefined) + data["Parameter35.Value"] = params["parameter35.value"]; + if (params["parameter36.name"] !== undefined) + data["Parameter36.Name"] = params["parameter36.name"]; + if (params["parameter36.value"] !== undefined) + data["Parameter36.Value"] = params["parameter36.value"]; + if (params["parameter37.name"] !== undefined) + data["Parameter37.Name"] = params["parameter37.name"]; + if (params["parameter37.value"] !== undefined) + data["Parameter37.Value"] = params["parameter37.value"]; + if (params["parameter38.name"] !== undefined) + data["Parameter38.Name"] = params["parameter38.name"]; + if (params["parameter38.value"] !== undefined) + data["Parameter38.Value"] = params["parameter38.value"]; + if (params["parameter39.name"] !== undefined) + data["Parameter39.Name"] = params["parameter39.name"]; + if (params["parameter39.value"] !== undefined) + data["Parameter39.Value"] = params["parameter39.value"]; + if (params["parameter40.name"] !== undefined) + data["Parameter40.Name"] = params["parameter40.name"]; + if (params["parameter40.value"] !== undefined) + data["Parameter40.Value"] = params["parameter40.value"]; + if (params["parameter41.name"] !== undefined) + data["Parameter41.Name"] = params["parameter41.name"]; + if (params["parameter41.value"] !== undefined) + data["Parameter41.Value"] = params["parameter41.value"]; + if (params["parameter42.name"] !== undefined) + data["Parameter42.Name"] = params["parameter42.name"]; + if (params["parameter42.value"] !== undefined) + data["Parameter42.Value"] = params["parameter42.value"]; + if (params["parameter43.name"] !== undefined) + data["Parameter43.Name"] = params["parameter43.name"]; + if (params["parameter43.value"] !== undefined) + data["Parameter43.Value"] = params["parameter43.value"]; + if (params["parameter44.name"] !== undefined) + data["Parameter44.Name"] = params["parameter44.name"]; + if (params["parameter44.value"] !== undefined) + data["Parameter44.Value"] = params["parameter44.value"]; + if (params["parameter45.name"] !== undefined) + data["Parameter45.Name"] = params["parameter45.name"]; + if (params["parameter45.value"] !== undefined) + data["Parameter45.Value"] = params["parameter45.value"]; + if (params["parameter46.name"] !== undefined) + data["Parameter46.Name"] = params["parameter46.name"]; + if (params["parameter46.value"] !== undefined) + data["Parameter46.Value"] = params["parameter46.value"]; + if (params["parameter47.name"] !== undefined) + data["Parameter47.Name"] = params["parameter47.name"]; + if (params["parameter47.value"] !== undefined) + data["Parameter47.Value"] = params["parameter47.value"]; + if (params["parameter48.name"] !== undefined) + data["Parameter48.Name"] = params["parameter48.name"]; + if (params["parameter48.value"] !== undefined) + data["Parameter48.Value"] = params["parameter48.value"]; + if (params["parameter49.name"] !== undefined) + data["Parameter49.Name"] = params["parameter49.name"]; + if (params["parameter49.value"] !== undefined) + data["Parameter49.Value"] = params["parameter49.value"]; + if (params["parameter50.name"] !== undefined) + data["Parameter50.Name"] = params["parameter50.name"]; + if (params["parameter50.value"] !== undefined) + data["Parameter50.Value"] = params["parameter50.value"]; + if (params["parameter51.name"] !== undefined) + data["Parameter51.Name"] = params["parameter51.name"]; + if (params["parameter51.value"] !== undefined) + data["Parameter51.Value"] = params["parameter51.value"]; + if (params["parameter52.name"] !== undefined) + data["Parameter52.Name"] = params["parameter52.name"]; + if (params["parameter52.value"] !== undefined) + data["Parameter52.Value"] = params["parameter52.value"]; + if (params["parameter53.name"] !== undefined) + data["Parameter53.Name"] = params["parameter53.name"]; + if (params["parameter53.value"] !== undefined) + data["Parameter53.Value"] = params["parameter53.value"]; + if (params["parameter54.name"] !== undefined) + data["Parameter54.Name"] = params["parameter54.name"]; + if (params["parameter54.value"] !== undefined) + data["Parameter54.Value"] = params["parameter54.value"]; + if (params["parameter55.name"] !== undefined) + data["Parameter55.Name"] = params["parameter55.name"]; + if (params["parameter55.value"] !== undefined) + data["Parameter55.Value"] = params["parameter55.value"]; + if (params["parameter56.name"] !== undefined) + data["Parameter56.Name"] = params["parameter56.name"]; + if (params["parameter56.value"] !== undefined) + data["Parameter56.Value"] = params["parameter56.value"]; + if (params["parameter57.name"] !== undefined) + data["Parameter57.Name"] = params["parameter57.name"]; + if (params["parameter57.value"] !== undefined) + data["Parameter57.Value"] = params["parameter57.value"]; + if (params["parameter58.name"] !== undefined) + data["Parameter58.Name"] = params["parameter58.name"]; + if (params["parameter58.value"] !== undefined) + data["Parameter58.Value"] = params["parameter58.value"]; + if (params["parameter59.name"] !== undefined) + data["Parameter59.Name"] = params["parameter59.name"]; + if (params["parameter59.value"] !== undefined) + data["Parameter59.Value"] = params["parameter59.value"]; + if (params["parameter60.name"] !== undefined) + data["Parameter60.Name"] = params["parameter60.name"]; + if (params["parameter60.value"] !== undefined) + data["Parameter60.Value"] = params["parameter60.value"]; + if (params["parameter61.name"] !== undefined) + data["Parameter61.Name"] = params["parameter61.name"]; + if (params["parameter61.value"] !== undefined) + data["Parameter61.Value"] = params["parameter61.value"]; + if (params["parameter62.name"] !== undefined) + data["Parameter62.Name"] = params["parameter62.name"]; + if (params["parameter62.value"] !== undefined) + data["Parameter62.Value"] = params["parameter62.value"]; + if (params["parameter63.name"] !== undefined) + data["Parameter63.Name"] = params["parameter63.name"]; + if (params["parameter63.value"] !== undefined) + data["Parameter63.Value"] = params["parameter63.value"]; + if (params["parameter64.name"] !== undefined) + data["Parameter64.Name"] = params["parameter64.name"]; + if (params["parameter64.value"] !== undefined) + data["Parameter64.Value"] = params["parameter64.value"]; + if (params["parameter65.name"] !== undefined) + data["Parameter65.Name"] = params["parameter65.name"]; + if (params["parameter65.value"] !== undefined) + data["Parameter65.Value"] = params["parameter65.value"]; + if (params["parameter66.name"] !== undefined) + data["Parameter66.Name"] = params["parameter66.name"]; + if (params["parameter66.value"] !== undefined) + data["Parameter66.Value"] = params["parameter66.value"]; + if (params["parameter67.name"] !== undefined) + data["Parameter67.Name"] = params["parameter67.name"]; + if (params["parameter67.value"] !== undefined) + data["Parameter67.Value"] = params["parameter67.value"]; + if (params["parameter68.name"] !== undefined) + data["Parameter68.Name"] = params["parameter68.name"]; + if (params["parameter68.value"] !== undefined) + data["Parameter68.Value"] = params["parameter68.value"]; + if (params["parameter69.name"] !== undefined) + data["Parameter69.Name"] = params["parameter69.name"]; + if (params["parameter69.value"] !== undefined) + data["Parameter69.Value"] = params["parameter69.value"]; + if (params["parameter70.name"] !== undefined) + data["Parameter70.Name"] = params["parameter70.name"]; + if (params["parameter70.value"] !== undefined) + data["Parameter70.Value"] = params["parameter70.value"]; + if (params["parameter71.name"] !== undefined) + data["Parameter71.Name"] = params["parameter71.name"]; + if (params["parameter71.value"] !== undefined) + data["Parameter71.Value"] = params["parameter71.value"]; + if (params["parameter72.name"] !== undefined) + data["Parameter72.Name"] = params["parameter72.name"]; + if (params["parameter72.value"] !== undefined) + data["Parameter72.Value"] = params["parameter72.value"]; + if (params["parameter73.name"] !== undefined) + data["Parameter73.Name"] = params["parameter73.name"]; + if (params["parameter73.value"] !== undefined) + data["Parameter73.Value"] = params["parameter73.value"]; + if (params["parameter74.name"] !== undefined) + data["Parameter74.Name"] = params["parameter74.name"]; + if (params["parameter74.value"] !== undefined) + data["Parameter74.Value"] = params["parameter74.value"]; + if (params["parameter75.name"] !== undefined) + data["Parameter75.Name"] = params["parameter75.name"]; + if (params["parameter75.value"] !== undefined) + data["Parameter75.Value"] = params["parameter75.value"]; + if (params["parameter76.name"] !== undefined) + data["Parameter76.Name"] = params["parameter76.name"]; + if (params["parameter76.value"] !== undefined) + data["Parameter76.Value"] = params["parameter76.value"]; + if (params["parameter77.name"] !== undefined) + data["Parameter77.Name"] = params["parameter77.name"]; + if (params["parameter77.value"] !== undefined) + data["Parameter77.Value"] = params["parameter77.value"]; + if (params["parameter78.name"] !== undefined) + data["Parameter78.Name"] = params["parameter78.name"]; + if (params["parameter78.value"] !== undefined) + data["Parameter78.Value"] = params["parameter78.value"]; + if (params["parameter79.name"] !== undefined) + data["Parameter79.Name"] = params["parameter79.name"]; + if (params["parameter79.value"] !== undefined) + data["Parameter79.Value"] = params["parameter79.value"]; + if (params["parameter80.name"] !== undefined) + data["Parameter80.Name"] = params["parameter80.name"]; + if (params["parameter80.value"] !== undefined) + data["Parameter80.Value"] = params["parameter80.value"]; + if (params["parameter81.name"] !== undefined) + data["Parameter81.Name"] = params["parameter81.name"]; + if (params["parameter81.value"] !== undefined) + data["Parameter81.Value"] = params["parameter81.value"]; + if (params["parameter82.name"] !== undefined) + data["Parameter82.Name"] = params["parameter82.name"]; + if (params["parameter82.value"] !== undefined) + data["Parameter82.Value"] = params["parameter82.value"]; + if (params["parameter83.name"] !== undefined) + data["Parameter83.Name"] = params["parameter83.name"]; + if (params["parameter83.value"] !== undefined) + data["Parameter83.Value"] = params["parameter83.value"]; + if (params["parameter84.name"] !== undefined) + data["Parameter84.Name"] = params["parameter84.name"]; + if (params["parameter84.value"] !== undefined) + data["Parameter84.Value"] = params["parameter84.value"]; + if (params["parameter85.name"] !== undefined) + data["Parameter85.Name"] = params["parameter85.name"]; + if (params["parameter85.value"] !== undefined) + data["Parameter85.Value"] = params["parameter85.value"]; + if (params["parameter86.name"] !== undefined) + data["Parameter86.Name"] = params["parameter86.name"]; + if (params["parameter86.value"] !== undefined) + data["Parameter86.Value"] = params["parameter86.value"]; + if (params["parameter87.name"] !== undefined) + data["Parameter87.Name"] = params["parameter87.name"]; + if (params["parameter87.value"] !== undefined) + data["Parameter87.Value"] = params["parameter87.value"]; + if (params["parameter88.name"] !== undefined) + data["Parameter88.Name"] = params["parameter88.name"]; + if (params["parameter88.value"] !== undefined) + data["Parameter88.Value"] = params["parameter88.value"]; + if (params["parameter89.name"] !== undefined) + data["Parameter89.Name"] = params["parameter89.name"]; + if (params["parameter89.value"] !== undefined) + data["Parameter89.Value"] = params["parameter89.value"]; + if (params["parameter90.name"] !== undefined) + data["Parameter90.Name"] = params["parameter90.name"]; + if (params["parameter90.value"] !== undefined) + data["Parameter90.Value"] = params["parameter90.value"]; + if (params["parameter91.name"] !== undefined) + data["Parameter91.Name"] = params["parameter91.name"]; + if (params["parameter91.value"] !== undefined) + data["Parameter91.Value"] = params["parameter91.value"]; + if (params["parameter92.name"] !== undefined) + data["Parameter92.Name"] = params["parameter92.name"]; + if (params["parameter92.value"] !== undefined) + data["Parameter92.Value"] = params["parameter92.value"]; + if (params["parameter93.name"] !== undefined) + data["Parameter93.Name"] = params["parameter93.name"]; + if (params["parameter93.value"] !== undefined) + data["Parameter93.Value"] = params["parameter93.value"]; + if (params["parameter94.name"] !== undefined) + data["Parameter94.Name"] = params["parameter94.name"]; + if (params["parameter94.value"] !== undefined) + data["Parameter94.Value"] = params["parameter94.value"]; + if (params["parameter95.name"] !== undefined) + data["Parameter95.Name"] = params["parameter95.name"]; + if (params["parameter95.value"] !== undefined) + data["Parameter95.Value"] = params["parameter95.value"]; + if (params["parameter96.name"] !== undefined) + data["Parameter96.Name"] = params["parameter96.name"]; + if (params["parameter96.value"] !== undefined) + data["Parameter96.Value"] = params["parameter96.value"]; + if (params["parameter97.name"] !== undefined) + data["Parameter97.Name"] = params["parameter97.name"]; + if (params["parameter97.value"] !== undefined) + data["Parameter97.Value"] = params["parameter97.value"]; + if (params["parameter98.name"] !== undefined) + data["Parameter98.Name"] = params["parameter98.name"]; + if (params["parameter98.value"] !== undefined) + data["Parameter98.Value"] = params["parameter98.value"]; + if (params["parameter99.name"] !== undefined) + data["Parameter99.Name"] = params["parameter99.name"]; + if (params["parameter99.value"] !== undefined) + data["Parameter99.Value"] = params["parameter99.value"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new StreamInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: StreamListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["url"] === null || params["url"] === undefined) { + throw new Error('Required parameter "params[\'url\']" missing.'); + } + + let data: any = {}; + + + + data["Url"] = params["url"]; + if (params["name"] !== undefined) + data["Name"] = params["name"]; + if (params["track"] !== undefined) + data["Track"] = params["track"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["parameter1.name"] !== undefined) + data["Parameter1.Name"] = params["parameter1.name"]; + if (params["parameter1.value"] !== undefined) + data["Parameter1.Value"] = params["parameter1.value"]; + if (params["parameter2.name"] !== undefined) + data["Parameter2.Name"] = params["parameter2.name"]; + if (params["parameter2.value"] !== undefined) + data["Parameter2.Value"] = params["parameter2.value"]; + if (params["parameter3.name"] !== undefined) + data["Parameter3.Name"] = params["parameter3.name"]; + if (params["parameter3.value"] !== undefined) + data["Parameter3.Value"] = params["parameter3.value"]; + if (params["parameter4.name"] !== undefined) + data["Parameter4.Name"] = params["parameter4.name"]; + if (params["parameter4.value"] !== undefined) + data["Parameter4.Value"] = params["parameter4.value"]; + if (params["parameter5.name"] !== undefined) + data["Parameter5.Name"] = params["parameter5.name"]; + if (params["parameter5.value"] !== undefined) + data["Parameter5.Value"] = params["parameter5.value"]; + if (params["parameter6.name"] !== undefined) + data["Parameter6.Name"] = params["parameter6.name"]; + if (params["parameter6.value"] !== undefined) + data["Parameter6.Value"] = params["parameter6.value"]; + if (params["parameter7.name"] !== undefined) + data["Parameter7.Name"] = params["parameter7.name"]; + if (params["parameter7.value"] !== undefined) + data["Parameter7.Value"] = params["parameter7.value"]; + if (params["parameter8.name"] !== undefined) + data["Parameter8.Name"] = params["parameter8.name"]; + if (params["parameter8.value"] !== undefined) + data["Parameter8.Value"] = params["parameter8.value"]; + if (params["parameter9.name"] !== undefined) + data["Parameter9.Name"] = params["parameter9.name"]; + if (params["parameter9.value"] !== undefined) + data["Parameter9.Value"] = params["parameter9.value"]; + if (params["parameter10.name"] !== undefined) + data["Parameter10.Name"] = params["parameter10.name"]; + if (params["parameter10.value"] !== undefined) + data["Parameter10.Value"] = params["parameter10.value"]; + if (params["parameter11.name"] !== undefined) + data["Parameter11.Name"] = params["parameter11.name"]; + if (params["parameter11.value"] !== undefined) + data["Parameter11.Value"] = params["parameter11.value"]; + if (params["parameter12.name"] !== undefined) + data["Parameter12.Name"] = params["parameter12.name"]; + if (params["parameter12.value"] !== undefined) + data["Parameter12.Value"] = params["parameter12.value"]; + if (params["parameter13.name"] !== undefined) + data["Parameter13.Name"] = params["parameter13.name"]; + if (params["parameter13.value"] !== undefined) + data["Parameter13.Value"] = params["parameter13.value"]; + if (params["parameter14.name"] !== undefined) + data["Parameter14.Name"] = params["parameter14.name"]; + if (params["parameter14.value"] !== undefined) + data["Parameter14.Value"] = params["parameter14.value"]; + if (params["parameter15.name"] !== undefined) + data["Parameter15.Name"] = params["parameter15.name"]; + if (params["parameter15.value"] !== undefined) + data["Parameter15.Value"] = params["parameter15.value"]; + if (params["parameter16.name"] !== undefined) + data["Parameter16.Name"] = params["parameter16.name"]; + if (params["parameter16.value"] !== undefined) + data["Parameter16.Value"] = params["parameter16.value"]; + if (params["parameter17.name"] !== undefined) + data["Parameter17.Name"] = params["parameter17.name"]; + if (params["parameter17.value"] !== undefined) + data["Parameter17.Value"] = params["parameter17.value"]; + if (params["parameter18.name"] !== undefined) + data["Parameter18.Name"] = params["parameter18.name"]; + if (params["parameter18.value"] !== undefined) + data["Parameter18.Value"] = params["parameter18.value"]; + if (params["parameter19.name"] !== undefined) + data["Parameter19.Name"] = params["parameter19.name"]; + if (params["parameter19.value"] !== undefined) + data["Parameter19.Value"] = params["parameter19.value"]; + if (params["parameter20.name"] !== undefined) + data["Parameter20.Name"] = params["parameter20.name"]; + if (params["parameter20.value"] !== undefined) + data["Parameter20.Value"] = params["parameter20.value"]; + if (params["parameter21.name"] !== undefined) + data["Parameter21.Name"] = params["parameter21.name"]; + if (params["parameter21.value"] !== undefined) + data["Parameter21.Value"] = params["parameter21.value"]; + if (params["parameter22.name"] !== undefined) + data["Parameter22.Name"] = params["parameter22.name"]; + if (params["parameter22.value"] !== undefined) + data["Parameter22.Value"] = params["parameter22.value"]; + if (params["parameter23.name"] !== undefined) + data["Parameter23.Name"] = params["parameter23.name"]; + if (params["parameter23.value"] !== undefined) + data["Parameter23.Value"] = params["parameter23.value"]; + if (params["parameter24.name"] !== undefined) + data["Parameter24.Name"] = params["parameter24.name"]; + if (params["parameter24.value"] !== undefined) + data["Parameter24.Value"] = params["parameter24.value"]; + if (params["parameter25.name"] !== undefined) + data["Parameter25.Name"] = params["parameter25.name"]; + if (params["parameter25.value"] !== undefined) + data["Parameter25.Value"] = params["parameter25.value"]; + if (params["parameter26.name"] !== undefined) + data["Parameter26.Name"] = params["parameter26.name"]; + if (params["parameter26.value"] !== undefined) + data["Parameter26.Value"] = params["parameter26.value"]; + if (params["parameter27.name"] !== undefined) + data["Parameter27.Name"] = params["parameter27.name"]; + if (params["parameter27.value"] !== undefined) + data["Parameter27.Value"] = params["parameter27.value"]; + if (params["parameter28.name"] !== undefined) + data["Parameter28.Name"] = params["parameter28.name"]; + if (params["parameter28.value"] !== undefined) + data["Parameter28.Value"] = params["parameter28.value"]; + if (params["parameter29.name"] !== undefined) + data["Parameter29.Name"] = params["parameter29.name"]; + if (params["parameter29.value"] !== undefined) + data["Parameter29.Value"] = params["parameter29.value"]; + if (params["parameter30.name"] !== undefined) + data["Parameter30.Name"] = params["parameter30.name"]; + if (params["parameter30.value"] !== undefined) + data["Parameter30.Value"] = params["parameter30.value"]; + if (params["parameter31.name"] !== undefined) + data["Parameter31.Name"] = params["parameter31.name"]; + if (params["parameter31.value"] !== undefined) + data["Parameter31.Value"] = params["parameter31.value"]; + if (params["parameter32.name"] !== undefined) + data["Parameter32.Name"] = params["parameter32.name"]; + if (params["parameter32.value"] !== undefined) + data["Parameter32.Value"] = params["parameter32.value"]; + if (params["parameter33.name"] !== undefined) + data["Parameter33.Name"] = params["parameter33.name"]; + if (params["parameter33.value"] !== undefined) + data["Parameter33.Value"] = params["parameter33.value"]; + if (params["parameter34.name"] !== undefined) + data["Parameter34.Name"] = params["parameter34.name"]; + if (params["parameter34.value"] !== undefined) + data["Parameter34.Value"] = params["parameter34.value"]; + if (params["parameter35.name"] !== undefined) + data["Parameter35.Name"] = params["parameter35.name"]; + if (params["parameter35.value"] !== undefined) + data["Parameter35.Value"] = params["parameter35.value"]; + if (params["parameter36.name"] !== undefined) + data["Parameter36.Name"] = params["parameter36.name"]; + if (params["parameter36.value"] !== undefined) + data["Parameter36.Value"] = params["parameter36.value"]; + if (params["parameter37.name"] !== undefined) + data["Parameter37.Name"] = params["parameter37.name"]; + if (params["parameter37.value"] !== undefined) + data["Parameter37.Value"] = params["parameter37.value"]; + if (params["parameter38.name"] !== undefined) + data["Parameter38.Name"] = params["parameter38.name"]; + if (params["parameter38.value"] !== undefined) + data["Parameter38.Value"] = params["parameter38.value"]; + if (params["parameter39.name"] !== undefined) + data["Parameter39.Name"] = params["parameter39.name"]; + if (params["parameter39.value"] !== undefined) + data["Parameter39.Value"] = params["parameter39.value"]; + if (params["parameter40.name"] !== undefined) + data["Parameter40.Name"] = params["parameter40.name"]; + if (params["parameter40.value"] !== undefined) + data["Parameter40.Value"] = params["parameter40.value"]; + if (params["parameter41.name"] !== undefined) + data["Parameter41.Name"] = params["parameter41.name"]; + if (params["parameter41.value"] !== undefined) + data["Parameter41.Value"] = params["parameter41.value"]; + if (params["parameter42.name"] !== undefined) + data["Parameter42.Name"] = params["parameter42.name"]; + if (params["parameter42.value"] !== undefined) + data["Parameter42.Value"] = params["parameter42.value"]; + if (params["parameter43.name"] !== undefined) + data["Parameter43.Name"] = params["parameter43.name"]; + if (params["parameter43.value"] !== undefined) + data["Parameter43.Value"] = params["parameter43.value"]; + if (params["parameter44.name"] !== undefined) + data["Parameter44.Name"] = params["parameter44.name"]; + if (params["parameter44.value"] !== undefined) + data["Parameter44.Value"] = params["parameter44.value"]; + if (params["parameter45.name"] !== undefined) + data["Parameter45.Name"] = params["parameter45.name"]; + if (params["parameter45.value"] !== undefined) + data["Parameter45.Value"] = params["parameter45.value"]; + if (params["parameter46.name"] !== undefined) + data["Parameter46.Name"] = params["parameter46.name"]; + if (params["parameter46.value"] !== undefined) + data["Parameter46.Value"] = params["parameter46.value"]; + if (params["parameter47.name"] !== undefined) + data["Parameter47.Name"] = params["parameter47.name"]; + if (params["parameter47.value"] !== undefined) + data["Parameter47.Value"] = params["parameter47.value"]; + if (params["parameter48.name"] !== undefined) + data["Parameter48.Name"] = params["parameter48.name"]; + if (params["parameter48.value"] !== undefined) + data["Parameter48.Value"] = params["parameter48.value"]; + if (params["parameter49.name"] !== undefined) + data["Parameter49.Name"] = params["parameter49.name"]; + if (params["parameter49.value"] !== undefined) + data["Parameter49.Value"] = params["parameter49.value"]; + if (params["parameter50.name"] !== undefined) + data["Parameter50.Name"] = params["parameter50.name"]; + if (params["parameter50.value"] !== undefined) + data["Parameter50.Value"] = params["parameter50.value"]; + if (params["parameter51.name"] !== undefined) + data["Parameter51.Name"] = params["parameter51.name"]; + if (params["parameter51.value"] !== undefined) + data["Parameter51.Value"] = params["parameter51.value"]; + if (params["parameter52.name"] !== undefined) + data["Parameter52.Name"] = params["parameter52.name"]; + if (params["parameter52.value"] !== undefined) + data["Parameter52.Value"] = params["parameter52.value"]; + if (params["parameter53.name"] !== undefined) + data["Parameter53.Name"] = params["parameter53.name"]; + if (params["parameter53.value"] !== undefined) + data["Parameter53.Value"] = params["parameter53.value"]; + if (params["parameter54.name"] !== undefined) + data["Parameter54.Name"] = params["parameter54.name"]; + if (params["parameter54.value"] !== undefined) + data["Parameter54.Value"] = params["parameter54.value"]; + if (params["parameter55.name"] !== undefined) + data["Parameter55.Name"] = params["parameter55.name"]; + if (params["parameter55.value"] !== undefined) + data["Parameter55.Value"] = params["parameter55.value"]; + if (params["parameter56.name"] !== undefined) + data["Parameter56.Name"] = params["parameter56.name"]; + if (params["parameter56.value"] !== undefined) + data["Parameter56.Value"] = params["parameter56.value"]; + if (params["parameter57.name"] !== undefined) + data["Parameter57.Name"] = params["parameter57.name"]; + if (params["parameter57.value"] !== undefined) + data["Parameter57.Value"] = params["parameter57.value"]; + if (params["parameter58.name"] !== undefined) + data["Parameter58.Name"] = params["parameter58.name"]; + if (params["parameter58.value"] !== undefined) + data["Parameter58.Value"] = params["parameter58.value"]; + if (params["parameter59.name"] !== undefined) + data["Parameter59.Name"] = params["parameter59.name"]; + if (params["parameter59.value"] !== undefined) + data["Parameter59.Value"] = params["parameter59.value"]; + if (params["parameter60.name"] !== undefined) + data["Parameter60.Name"] = params["parameter60.name"]; + if (params["parameter60.value"] !== undefined) + data["Parameter60.Value"] = params["parameter60.value"]; + if (params["parameter61.name"] !== undefined) + data["Parameter61.Name"] = params["parameter61.name"]; + if (params["parameter61.value"] !== undefined) + data["Parameter61.Value"] = params["parameter61.value"]; + if (params["parameter62.name"] !== undefined) + data["Parameter62.Name"] = params["parameter62.name"]; + if (params["parameter62.value"] !== undefined) + data["Parameter62.Value"] = params["parameter62.value"]; + if (params["parameter63.name"] !== undefined) + data["Parameter63.Name"] = params["parameter63.name"]; + if (params["parameter63.value"] !== undefined) + data["Parameter63.Value"] = params["parameter63.value"]; + if (params["parameter64.name"] !== undefined) + data["Parameter64.Name"] = params["parameter64.name"]; + if (params["parameter64.value"] !== undefined) + data["Parameter64.Value"] = params["parameter64.value"]; + if (params["parameter65.name"] !== undefined) + data["Parameter65.Name"] = params["parameter65.name"]; + if (params["parameter65.value"] !== undefined) + data["Parameter65.Value"] = params["parameter65.value"]; + if (params["parameter66.name"] !== undefined) + data["Parameter66.Name"] = params["parameter66.name"]; + if (params["parameter66.value"] !== undefined) + data["Parameter66.Value"] = params["parameter66.value"]; + if (params["parameter67.name"] !== undefined) + data["Parameter67.Name"] = params["parameter67.name"]; + if (params["parameter67.value"] !== undefined) + data["Parameter67.Value"] = params["parameter67.value"]; + if (params["parameter68.name"] !== undefined) + data["Parameter68.Name"] = params["parameter68.name"]; + if (params["parameter68.value"] !== undefined) + data["Parameter68.Value"] = params["parameter68.value"]; + if (params["parameter69.name"] !== undefined) + data["Parameter69.Name"] = params["parameter69.name"]; + if (params["parameter69.value"] !== undefined) + data["Parameter69.Value"] = params["parameter69.value"]; + if (params["parameter70.name"] !== undefined) + data["Parameter70.Name"] = params["parameter70.name"]; + if (params["parameter70.value"] !== undefined) + data["Parameter70.Value"] = params["parameter70.value"]; + if (params["parameter71.name"] !== undefined) + data["Parameter71.Name"] = params["parameter71.name"]; + if (params["parameter71.value"] !== undefined) + data["Parameter71.Value"] = params["parameter71.value"]; + if (params["parameter72.name"] !== undefined) + data["Parameter72.Name"] = params["parameter72.name"]; + if (params["parameter72.value"] !== undefined) + data["Parameter72.Value"] = params["parameter72.value"]; + if (params["parameter73.name"] !== undefined) + data["Parameter73.Name"] = params["parameter73.name"]; + if (params["parameter73.value"] !== undefined) + data["Parameter73.Value"] = params["parameter73.value"]; + if (params["parameter74.name"] !== undefined) + data["Parameter74.Name"] = params["parameter74.name"]; + if (params["parameter74.value"] !== undefined) + data["Parameter74.Value"] = params["parameter74.value"]; + if (params["parameter75.name"] !== undefined) + data["Parameter75.Name"] = params["parameter75.name"]; + if (params["parameter75.value"] !== undefined) + data["Parameter75.Value"] = params["parameter75.value"]; + if (params["parameter76.name"] !== undefined) + data["Parameter76.Name"] = params["parameter76.name"]; + if (params["parameter76.value"] !== undefined) + data["Parameter76.Value"] = params["parameter76.value"]; + if (params["parameter77.name"] !== undefined) + data["Parameter77.Name"] = params["parameter77.name"]; + if (params["parameter77.value"] !== undefined) + data["Parameter77.Value"] = params["parameter77.value"]; + if (params["parameter78.name"] !== undefined) + data["Parameter78.Name"] = params["parameter78.name"]; + if (params["parameter78.value"] !== undefined) + data["Parameter78.Value"] = params["parameter78.value"]; + if (params["parameter79.name"] !== undefined) + data["Parameter79.Name"] = params["parameter79.name"]; + if (params["parameter79.value"] !== undefined) + data["Parameter79.Value"] = params["parameter79.value"]; + if (params["parameter80.name"] !== undefined) + data["Parameter80.Name"] = params["parameter80.name"]; + if (params["parameter80.value"] !== undefined) + data["Parameter80.Value"] = params["parameter80.value"]; + if (params["parameter81.name"] !== undefined) + data["Parameter81.Name"] = params["parameter81.name"]; + if (params["parameter81.value"] !== undefined) + data["Parameter81.Value"] = params["parameter81.value"]; + if (params["parameter82.name"] !== undefined) + data["Parameter82.Name"] = params["parameter82.name"]; + if (params["parameter82.value"] !== undefined) + data["Parameter82.Value"] = params["parameter82.value"]; + if (params["parameter83.name"] !== undefined) + data["Parameter83.Name"] = params["parameter83.name"]; + if (params["parameter83.value"] !== undefined) + data["Parameter83.Value"] = params["parameter83.value"]; + if (params["parameter84.name"] !== undefined) + data["Parameter84.Name"] = params["parameter84.name"]; + if (params["parameter84.value"] !== undefined) + data["Parameter84.Value"] = params["parameter84.value"]; + if (params["parameter85.name"] !== undefined) + data["Parameter85.Name"] = params["parameter85.name"]; + if (params["parameter85.value"] !== undefined) + data["Parameter85.Value"] = params["parameter85.value"]; + if (params["parameter86.name"] !== undefined) + data["Parameter86.Name"] = params["parameter86.name"]; + if (params["parameter86.value"] !== undefined) + data["Parameter86.Value"] = params["parameter86.value"]; + if (params["parameter87.name"] !== undefined) + data["Parameter87.Name"] = params["parameter87.name"]; + if (params["parameter87.value"] !== undefined) + data["Parameter87.Value"] = params["parameter87.value"]; + if (params["parameter88.name"] !== undefined) + data["Parameter88.Name"] = params["parameter88.name"]; + if (params["parameter88.value"] !== undefined) + data["Parameter88.Value"] = params["parameter88.value"]; + if (params["parameter89.name"] !== undefined) + data["Parameter89.Name"] = params["parameter89.name"]; + if (params["parameter89.value"] !== undefined) + data["Parameter89.Value"] = params["parameter89.value"]; + if (params["parameter90.name"] !== undefined) + data["Parameter90.Name"] = params["parameter90.name"]; + if (params["parameter90.value"] !== undefined) + data["Parameter90.Value"] = params["parameter90.value"]; + if (params["parameter91.name"] !== undefined) + data["Parameter91.Name"] = params["parameter91.name"]; + if (params["parameter91.value"] !== undefined) + data["Parameter91.Value"] = params["parameter91.value"]; + if (params["parameter92.name"] !== undefined) + data["Parameter92.Name"] = params["parameter92.name"]; + if (params["parameter92.value"] !== undefined) + data["Parameter92.Value"] = params["parameter92.value"]; + if (params["parameter93.name"] !== undefined) + data["Parameter93.Name"] = params["parameter93.name"]; + if (params["parameter93.value"] !== undefined) + data["Parameter93.Value"] = params["parameter93.value"]; + if (params["parameter94.name"] !== undefined) + data["Parameter94.Name"] = params["parameter94.name"]; + if (params["parameter94.value"] !== undefined) + data["Parameter94.Value"] = params["parameter94.value"]; + if (params["parameter95.name"] !== undefined) + data["Parameter95.Name"] = params["parameter95.name"]; + if (params["parameter95.value"] !== undefined) + data["Parameter95.Value"] = params["parameter95.value"]; + if (params["parameter96.name"] !== undefined) + data["Parameter96.Name"] = params["parameter96.name"]; + if (params["parameter96.value"] !== undefined) + data["Parameter96.Value"] = params["parameter96.value"]; + if (params["parameter97.name"] !== undefined) + data["Parameter97.Name"] = params["parameter97.name"]; + if (params["parameter97.value"] !== undefined) + data["Parameter97.Value"] = params["parameter97.value"]; + if (params["parameter98.name"] !== undefined) + data["Parameter98.Name"] = params["parameter98.name"]; + if (params["parameter98.value"] !== undefined) + data["Parameter98.Value"] = params["parameter98.value"]; + if (params["parameter99.name"] !== undefined) + data["Parameter99.Name"] = params["parameter99.name"]; + if (params["parameter99.value"] !== undefined) + data["Parameter99.Value"] = params["parameter99.value"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new StreamInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/api/v2010/account/call/transcription.ts b/rest/api/v2010/account/call/transcription.ts new file mode 100644 index 000000000..279aa93c4 --- /dev/null +++ b/rest/api/v2010/account/call/transcription.ts @@ -0,0 +1,566 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The status - one of `stopped`, `in-flight` + */ +export type TranscriptionStatus = 'in-progress'|'stopped'; + +/** + * One of `inbound_track`, `outbound_track`, `both_tracks`. + */ +export type TranscriptionTrack = 'inbound_track'|'outbound_track'|'both_tracks'; + +export type TranscriptionUpdateStatus = 'stopped'; + + +/** + * Options to pass to update a TranscriptionInstance + */ +export interface TranscriptionContextUpdateOptions { + /** */ + "status": TranscriptionUpdateStatus; +} + +/** + * Options to pass to create a TranscriptionInstance + */ +export interface TranscriptionListInstanceCreateOptions { + /** The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. */ + "name"?: string; + /** */ + "track"?: TranscriptionTrack; + /** Absolute URL of the status callback. */ + "statusCallbackUrl"?: string; + /** The http method for the status_callback (one of GET, POST). */ + "statusCallbackMethod"?: string; + /** Friendly name given to the Inbound Track */ + "inboundTrackLabel"?: string; + /** Friendly name given to the Outbound Track */ + "outboundTrackLabel"?: string; + /** Indicates if partial results are going to be sent to the customer */ + "partialResults"?: boolean; + /** Language code used by the transcription engine, specified in [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) format */ + "languageCode"?: string; + /** Definition of the transcription engine to be used, among those supported by Twilio */ + "transcriptionEngine"?: string; + /** indicates if the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks */ + "profanityFilter"?: boolean; + /** Recognition model used by the transcription engine, among those supported by the provider */ + "speechModel"?: string; + /** A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. */ + "hints"?: string; + /** The provider will add punctuation to recognition result */ + "enableAutomaticPunctuation"?: boolean; + /** The SID or unique name of the [Intelligence Service](https://www.twilio.com/docs/conversational-intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators */ + "intelligenceService"?: string; + /** The ID of the Conversations Configuration for customizing conversation behavior in Intelligence Service */ + "conversationConfiguration"?: string; + /** The ID of the Conversation for associating this Transcription with an existing Conversation in Intelligence Service */ + "conversationId"?: string; + /** The ID of the RealTimeTranscription Configuration for configuring all the non-default behaviors in one go. */ + "transcriptionConfigurationId"?: string; + /** Whether the callback includes raw provider data. */ + "enableProviderData"?: boolean; +} + +export interface TranscriptionContext { + + /** + * Update a TranscriptionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + update(params: TranscriptionContextUpdateOptions, callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise; + + /** + * Update a TranscriptionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + updateWithHttpInfo(params: TranscriptionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TranscriptionContextSolution { + "accountSid": string; + "callSid": string; + "sid": string; +} + +export class TranscriptionContextImpl implements TranscriptionContext { + protected _solution: TranscriptionContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, callSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, callSid, sid, }; + this._uri = `/Accounts/${accountSid}/Calls/${callSid}/Transcriptions/${sid}.json`; + } + + update(params: TranscriptionContextUpdateOptions,callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: TranscriptionContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new TranscriptionInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TranscriptionPayload extends TranscriptionResource {} + +interface TranscriptionResource { + sid: string; + account_sid: string; + call_sid: string; + name: string; + status: TranscriptionStatus; + date_updated: Date; + uri: string; +} + +export class TranscriptionInstance { + protected _solution: TranscriptionContextSolution; + protected _context?: TranscriptionContext; + + constructor(protected _version: V2010, payload: TranscriptionResource, accountSid: string, callSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.callSid = (payload.call_sid); + this.name = (payload.name); + this.status = payload.status; + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.uri = (payload.uri); + + this._solution = { accountSid, callSid, sid: sid, }; + } + + /** + * The SID of the Transcription resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Transcription resource. + */ + accountSid: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Transcription resource is associated with. + */ + callSid: string; + /** + * The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + */ + name: string; + status: TranscriptionStatus; + /** + * The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + uri: string; + + private get _proxy(): TranscriptionContext { + this._context = this._context || new TranscriptionContextImpl(this._version, this._solution.accountSid, this._solution.callSid, this._solution.sid); + return this._context; + } + + /** + * Update a TranscriptionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + update(params: TranscriptionContextUpdateOptions, callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a TranscriptionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + updateWithHttpInfo(params: TranscriptionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + callSid: this.callSid, + name: this.name, + status: this.status, + dateUpdated: this.dateUpdated, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TranscriptionSolution { + accountSid: string; + callSid: string; +} + +export interface TranscriptionListInstance { + _version: V2010; + _solution: TranscriptionSolution; + _uri: string; + + (sid: string, ): TranscriptionContext; + get(sid: string, ): TranscriptionContext; + + + + + /** + * Create a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + create(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise; + /** + * Create a TranscriptionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + create(params: TranscriptionListInstanceCreateOptions, callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise; + + /** + * Create a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a TranscriptionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + createWithHttpInfo(params: TranscriptionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TranscriptionListInstance(version: V2010, accountSid: string, callSid: string): TranscriptionListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as TranscriptionListInstance; + + instance.get = function get(sid, ): TranscriptionContext { + return new TranscriptionContextImpl(version, accountSid, callSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, callSid, }; + instance._uri = `/Accounts/${accountSid}/Calls/${callSid}/Transcriptions.json`; + + instance.create = function create(params?: TranscriptionListInstanceCreateOptions | ((error: Error | null, items: TranscriptionInstance) => any), callback?: (error: Error | null, items: TranscriptionInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["name"] !== undefined) + data["Name"] = params["name"]; + if (params["track"] !== undefined) + data["Track"] = params["track"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["inboundTrackLabel"] !== undefined) + data["InboundTrackLabel"] = params["inboundTrackLabel"]; + if (params["outboundTrackLabel"] !== undefined) + data["OutboundTrackLabel"] = params["outboundTrackLabel"]; + if (params["partialResults"] !== undefined) + data["PartialResults"] = serialize.bool(params["partialResults"]); + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["transcriptionEngine"] !== undefined) + data["TranscriptionEngine"] = params["transcriptionEngine"]; + if (params["profanityFilter"] !== undefined) + data["ProfanityFilter"] = serialize.bool(params["profanityFilter"]); + if (params["speechModel"] !== undefined) + data["SpeechModel"] = params["speechModel"]; + if (params["hints"] !== undefined) + data["Hints"] = params["hints"]; + if (params["enableAutomaticPunctuation"] !== undefined) + data["EnableAutomaticPunctuation"] = serialize.bool(params["enableAutomaticPunctuation"]); + if (params["intelligenceService"] !== undefined) + data["IntelligenceService"] = params["intelligenceService"]; + if (params["conversationConfiguration"] !== undefined) + data["ConversationConfiguration"] = params["conversationConfiguration"]; + if (params["conversationId"] !== undefined) + data["ConversationId"] = params["conversationId"]; + if (params["transcriptionConfigurationId"] !== undefined) + data["TranscriptionConfigurationId"] = params["transcriptionConfigurationId"]; + if (params["enableProviderData"] !== undefined) + data["EnableProviderData"] = serialize.bool(params["enableProviderData"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: TranscriptionListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["name"] !== undefined) + data["Name"] = params["name"]; + if (params["track"] !== undefined) + data["Track"] = params["track"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["inboundTrackLabel"] !== undefined) + data["InboundTrackLabel"] = params["inboundTrackLabel"]; + if (params["outboundTrackLabel"] !== undefined) + data["OutboundTrackLabel"] = params["outboundTrackLabel"]; + if (params["partialResults"] !== undefined) + data["PartialResults"] = serialize.bool(params["partialResults"]); + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["transcriptionEngine"] !== undefined) + data["TranscriptionEngine"] = params["transcriptionEngine"]; + if (params["profanityFilter"] !== undefined) + data["ProfanityFilter"] = serialize.bool(params["profanityFilter"]); + if (params["speechModel"] !== undefined) + data["SpeechModel"] = params["speechModel"]; + if (params["hints"] !== undefined) + data["Hints"] = params["hints"]; + if (params["enableAutomaticPunctuation"] !== undefined) + data["EnableAutomaticPunctuation"] = serialize.bool(params["enableAutomaticPunctuation"]); + if (params["intelligenceService"] !== undefined) + data["IntelligenceService"] = params["intelligenceService"]; + if (params["conversationConfiguration"] !== undefined) + data["ConversationConfiguration"] = params["conversationConfiguration"]; + if (params["conversationId"] !== undefined) + data["ConversationId"] = params["conversationId"]; + if (params["transcriptionConfigurationId"] !== undefined) + data["TranscriptionConfigurationId"] = params["transcriptionConfigurationId"]; + if (params["enableProviderData"] !== undefined) + data["EnableProviderData"] = serialize.bool(params["enableProviderData"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new TranscriptionInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/api/v2010/account/call/userDefinedMessage.ts b/rest/api/v2010/account/call/userDefinedMessage.ts new file mode 100644 index 000000000..d94bc83f0 --- /dev/null +++ b/rest/api/v2010/account/call/userDefinedMessage.ts @@ -0,0 +1,232 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to create a UserDefinedMessageInstance + */ +export interface UserDefinedMessageListInstanceCreateOptions { + /** The User Defined Message in the form of URL-encoded JSON string. */ + "content": string; + /** A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. */ + "idempotencyKey"?: string; +} + + +export interface UserDefinedMessageSolution { + accountSid: string; + callSid: string; +} + +export interface UserDefinedMessageListInstance { + _version: V2010; + _solution: UserDefinedMessageSolution; + _uri: string; + + + + /** + * Create a UserDefinedMessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserDefinedMessageInstance + */ + create(params: UserDefinedMessageListInstanceCreateOptions, callback?: (error: Error | null, item?: UserDefinedMessageInstance) => any): Promise; + + /** + * Create a UserDefinedMessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserDefinedMessageInstance with HTTP metadata + */ + createWithHttpInfo(params: UserDefinedMessageListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserDefinedMessageListInstance(version: V2010, accountSid: string, callSid: string): UserDefinedMessageListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = {} as UserDefinedMessageListInstance; + + instance._version = version; + instance._solution = { accountSid, callSid, }; + instance._uri = `/Accounts/${accountSid}/Calls/${callSid}/UserDefinedMessages.json`; + + instance.create = function create(params: UserDefinedMessageListInstanceCreateOptions, callback?: (error: Error | null, items: UserDefinedMessageInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["content"] === null || params["content"] === undefined) { + throw new Error('Required parameter "params[\'content\']" missing.'); + } + + let data: any = {}; + + + + data["Content"] = params["content"]; + if (params["idempotencyKey"] !== undefined) + data["IdempotencyKey"] = params["idempotencyKey"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserDefinedMessageInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: UserDefinedMessageListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["content"] === null || params["content"] === undefined) { + throw new Error('Required parameter "params[\'content\']" missing.'); + } + + let data: any = {}; + + + + data["Content"] = params["content"]; + if (params["idempotencyKey"] !== undefined) + data["IdempotencyKey"] = params["idempotencyKey"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserDefinedMessageInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface UserDefinedMessagePayload extends UserDefinedMessageResource {} + +interface UserDefinedMessageResource { + account_sid: string; + call_sid: string; + sid: string; + date_created: Date; +} + +export class UserDefinedMessageInstance { + + constructor(protected _version: V2010, payload: UserDefinedMessageResource, accountSid: string, callSid: string) { + + this.accountSid = (payload.account_sid); + this.callSid = (payload.call_sid); + this.sid = (payload.sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created User Defined Message. + */ + accountSid: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message is associated with. + */ + callSid: string; + /** + * The SID that uniquely identifies this User Defined Message. + */ + sid: string; + /** + * The date that this User Defined Message was created, given in RFC 2822 format. + */ + dateCreated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + callSid: this.callSid, + sid: this.sid, + dateCreated: this.dateCreated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/api/v2010/account/call/userDefinedMessageSubscription.ts b/rest/api/v2010/account/call/userDefinedMessageSubscription.ts new file mode 100644 index 000000000..322461c83 --- /dev/null +++ b/rest/api/v2010/account/call/userDefinedMessageSubscription.ts @@ -0,0 +1,389 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + +/** + * Options to pass to create a UserDefinedMessageSubscriptionInstance + */ +export interface UserDefinedMessageSubscriptionListInstanceCreateOptions { + /** The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). */ + "callback": string; + /** A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. */ + "idempotencyKey"?: string; + /** The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. */ + "method"?: string; +} + +export interface UserDefinedMessageSubscriptionContext { + + /** + * Remove a UserDefinedMessageSubscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a UserDefinedMessageSubscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserDefinedMessageSubscriptionContextSolution { + "accountSid": string; + "callSid": string; + "sid": string; +} + +export class UserDefinedMessageSubscriptionContextImpl implements UserDefinedMessageSubscriptionContext { + protected _solution: UserDefinedMessageSubscriptionContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, callSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, callSid, sid, }; + this._uri = `/Accounts/${accountSid}/Calls/${callSid}/UserDefinedMessageSubscriptions/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserDefinedMessageSubscriptionPayload extends UserDefinedMessageSubscriptionResource {} + +interface UserDefinedMessageSubscriptionResource { + account_sid: string; + call_sid: string; + sid: string; + date_created: Date; + uri: string; +} + +export class UserDefinedMessageSubscriptionInstance { + protected _solution: UserDefinedMessageSubscriptionContextSolution; + protected _context?: UserDefinedMessageSubscriptionContext; + + constructor(protected _version: V2010, payload: UserDefinedMessageSubscriptionResource, accountSid: string, callSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.callSid = (payload.call_sid); + this.sid = (payload.sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.uri = (payload.uri); + + this._solution = { accountSid, callSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that subscribed to the User Defined Messages. + */ + accountSid: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message Subscription is associated with. This refers to the Call SID that is producing the User Defined Messages. + */ + callSid: string; + /** + * The SID that uniquely identifies this User Defined Message Subscription. + */ + sid: string; + /** + * The date that this User Defined Message Subscription was created, given in RFC 2822 format. + */ + dateCreated: Date; + /** + * The URI of the User Defined Message Subscription Resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): UserDefinedMessageSubscriptionContext { + this._context = this._context || new UserDefinedMessageSubscriptionContextImpl(this._version, this._solution.accountSid, this._solution.callSid, this._solution.sid); + return this._context; + } + + /** + * Remove a UserDefinedMessageSubscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserDefinedMessageSubscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + callSid: this.callSid, + sid: this.sid, + dateCreated: this.dateCreated, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserDefinedMessageSubscriptionSolution { + accountSid: string; + callSid: string; +} + +export interface UserDefinedMessageSubscriptionListInstance { + _version: V2010; + _solution: UserDefinedMessageSubscriptionSolution; + _uri: string; + + (sid: string, ): UserDefinedMessageSubscriptionContext; + get(sid: string, ): UserDefinedMessageSubscriptionContext; + + + + + /** + * Create a UserDefinedMessageSubscriptionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserDefinedMessageSubscriptionInstance + */ + create(params: UserDefinedMessageSubscriptionListInstanceCreateOptions, callback?: (error: Error | null, item?: UserDefinedMessageSubscriptionInstance) => any): Promise; + + /** + * Create a UserDefinedMessageSubscriptionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserDefinedMessageSubscriptionInstance with HTTP metadata + */ + createWithHttpInfo(params: UserDefinedMessageSubscriptionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserDefinedMessageSubscriptionListInstance(version: V2010, accountSid: string, callSid: string): UserDefinedMessageSubscriptionListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as UserDefinedMessageSubscriptionListInstance; + + instance.get = function get(sid, ): UserDefinedMessageSubscriptionContext { + return new UserDefinedMessageSubscriptionContextImpl(version, accountSid, callSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, callSid, }; + instance._uri = `/Accounts/${accountSid}/Calls/${callSid}/UserDefinedMessageSubscriptions.json`; + + instance.create = function create(params: UserDefinedMessageSubscriptionListInstanceCreateOptions, callback?: (error: Error | null, items: UserDefinedMessageSubscriptionInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["callback"] === null || params["callback"] === undefined) { + throw new Error('Required parameter "params[\'callback\']" missing.'); + } + + let data: any = {}; + + + + data["Callback"] = params["callback"]; + if (params["idempotencyKey"] !== undefined) + data["IdempotencyKey"] = params["idempotencyKey"]; + if (params["method"] !== undefined) + data["Method"] = params["method"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserDefinedMessageSubscriptionInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: UserDefinedMessageSubscriptionListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["callback"] === null || params["callback"] === undefined) { + throw new Error('Required parameter "params[\'callback\']" missing.'); + } + + let data: any = {}; + + + + data["Callback"] = params["callback"]; + if (params["idempotencyKey"] !== undefined) + data["IdempotencyKey"] = params["idempotencyKey"]; + if (params["method"] !== undefined) + data["Method"] = params["method"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserDefinedMessageSubscriptionInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/api/v2010/account/conference.ts b/rest/api/v2010/account/conference.ts new file mode 100644 index 000000000..a6ea74b3f --- /dev/null +++ b/rest/api/v2010/account/conference.ts @@ -0,0 +1,893 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { ParticipantListInstance } from "./conference/participant"; +import { RecordingListInstance } from "./conference/recording"; + + +/** + * The reason why a conference ended. When a conference is in progress, will be `null`. When conference is completed, can be: `conference-ended-via-api`, `participant-with-end-conference-on-exit-left`, `participant-with-end-conference-on-exit-kicked`, `last-participant-kicked`, or `last-participant-left`. + */ +export type ConferenceReasonConferenceEnded = 'conference-ended-via-api'|'participant-with-end-conference-on-exit-left'|'participant-with-end-conference-on-exit-kicked'|'last-participant-kicked'|'last-participant-left'; + +/** + * The status of this conference. Can be: `init`, `in-progress`, or `completed`. + */ +export type ConferenceStatus = 'init'|'in-progress'|'completed'; + +export type ConferenceUpdateStatus = 'completed'; + + + +/** + * Options to pass to update a ConferenceInstance + */ +export interface ConferenceContextUpdateOptions { + /** */ + "status"?: ConferenceUpdateStatus; + /** The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. */ + "announceUrl"?: string; + /** The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` */ + "announceMethod"?: string; +} + +/** + * Options to pass to each + */ +export interface ConferenceListInstanceEachOptions { + /** Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. */ + "dateCreated"?: Date; + /** Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. */ + "dateCreatedBefore"?: Date; + /** Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. */ + "dateCreatedAfter"?: Date; + /** Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. */ + "dateUpdated"?: Date; + /** Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. */ + "dateUpdatedBefore"?: Date; + /** Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. */ + "dateUpdatedAfter"?: Date; + /** The string that identifies the Conference resources to read. */ + "friendlyName"?: string; + /** The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. */ + "status"?: ConferenceStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConferenceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConferenceListInstanceOptions { + /** Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. */ + "dateCreated"?: Date; + /** Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. */ + "dateCreatedBefore"?: Date; + /** Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. */ + "dateCreatedAfter"?: Date; + /** Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. */ + "dateUpdated"?: Date; + /** Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. */ + "dateUpdatedBefore"?: Date; + /** Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. */ + "dateUpdatedAfter"?: Date; + /** The string that identifies the Conference resources to read. */ + "friendlyName"?: string; + /** The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. */ + "status"?: ConferenceStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConferenceListInstancePageOptions { + /** Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. */ + "dateCreated"?: Date; + /** Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. */ + "dateCreatedBefore"?: Date; + /** Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. */ + "dateCreatedAfter"?: Date; + /** Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. */ + "dateUpdated"?: Date; + /** Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. */ + "dateUpdatedBefore"?: Date; + /** Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. */ + "dateUpdatedAfter"?: Date; + /** The string that identifies the Conference resources to read. */ + "friendlyName"?: string; + /** The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. */ + "status"?: ConferenceStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ConferenceContext { + participants: ParticipantListInstance; + recordings: RecordingListInstance; + + /** + * Fetch a ConferenceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance + */ + fetch(callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise + + /** + * Fetch a ConferenceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ConferenceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance + */ + update(callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise; + /** + * Update a ConferenceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance + */ + update(params: ConferenceContextUpdateOptions, callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise; + + /** + * Update a ConferenceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConferenceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConferenceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConferenceContextSolution { + "accountSid": string; + "sid": string; +} + +export class ConferenceContextImpl implements ConferenceContext { + protected _solution: ConferenceContextSolution; + protected _uri: string; + + protected _participants?: ParticipantListInstance; + protected _recordings?: RecordingListInstance; + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Conferences/${sid}.json`; + } + + get participants(): ParticipantListInstance { + this._participants = this._participants || ParticipantListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._participants; + } + + get recordings(): RecordingListInstance { + this._recordings = this._recordings || RecordingListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._recordings; + } + + fetch(callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConferenceInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConferenceInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ConferenceContextUpdateOptions | ((error: Error | null, item?: ConferenceInstance) => any),callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["announceUrl"] !== undefined) + data["AnnounceUrl"] = params["announceUrl"]; + if (params["announceMethod"] !== undefined) + data["AnnounceMethod"] = params["announceMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConferenceInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ConferenceContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["announceUrl"] !== undefined) + data["AnnounceUrl"] = params["announceUrl"]; + if (params["announceMethod"] !== undefined) + data["AnnounceMethod"] = params["announceMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConferenceInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConferencePayload extends TwilioResponsePayload { + conferences: ConferenceResource[]; +} + +interface ConferenceResource { + account_sid: string; + date_created: Date; + date_updated: Date; + api_version: string; + friendly_name: string; + region: string; + sid: string; + status: ConferenceStatus; + uri: string; + subresource_uris: Record; + reason_conference_ended: ConferenceReasonConferenceEnded; + call_sid_ending_conference: string; +} + +export class ConferenceInstance { + protected _solution: ConferenceContextSolution; + protected _context?: ConferenceContext; + + constructor(protected _version: V2010, payload: ConferenceResource, accountSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.apiVersion = (payload.api_version); + this.friendlyName = (payload.friendly_name); + this.region = (payload.region); + this.sid = (payload.sid); + this.status = payload.status; + this.uri = (payload.uri); + this.subresourceUris = (payload.subresource_uris); + this.reasonConferenceEnded = payload.reason_conference_ended; + this.callSidEndingConference = (payload.call_sid_ending_conference); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Conference resource. + */ + accountSid: string; + /** + * The date and time in UTC that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in UTC that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The API version used to create this conference. + */ + apiVersion: string; + /** + * A string that you assigned to describe this conference room. Maximum length is 128 characters. + */ + friendlyName: string; + /** + * A string that represents the Twilio Region where the conference audio was mixed. May be `us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, and `jp1`. Basic conference audio will always be mixed in `us1`. Global Conference audio will be mixed nearest to the majority of participants. + */ + region: string; + /** + * The unique, Twilio-provided string used to identify this Conference resource. + */ + sid: string; + status: ConferenceStatus; + /** + * The URI of this resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * A list of related resources identified by their URIs relative to `https://api.twilio.com`. + */ + subresourceUris: Record; + reasonConferenceEnded: ConferenceReasonConferenceEnded; + /** + * The call SID that caused the conference to end. + */ + callSidEndingConference: string; + + private get _proxy(): ConferenceContext { + this._context = this._context || new ConferenceContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a ConferenceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance + */ + fetch(callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConferenceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ConferenceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance + */ + update(callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise; + /** + * Update a ConferenceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance + */ + update(params: ConferenceContextUpdateOptions, callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConferenceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConferenceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConferenceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the participants. + */ + participants(): ParticipantListInstance { + return this._proxy.participants; + } + + /** + * Access the recordings. + */ + recordings(): RecordingListInstance { + return this._proxy.recordings; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + apiVersion: this.apiVersion, + friendlyName: this.friendlyName, + region: this.region, + sid: this.sid, + status: this.status, + uri: this.uri, + subresourceUris: this.subresourceUris, + reasonConferenceEnded: this.reasonConferenceEnded, + callSidEndingConference: this.callSidEndingConference, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConferenceSolution { + accountSid: string; +} + +export interface ConferenceListInstance { + _version: V2010; + _solution: ConferenceSolution; + _uri: string; + + (sid: string, ): ConferenceContext; + get(sid: string, ): ConferenceContext; + + + + + + + + /** + * Streams ConferenceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConferenceInstance, done: (err?: Error) => void) => void): void; + each(params: ConferenceListInstanceEachOptions, callback?: (item: ConferenceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConferenceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConferenceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConferenceListInstanceEachOptions, callback?: (item: ConferenceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConferenceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConferencePage) => any): Promise; + /** + * Retrieve a single target page of ConferenceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConferenceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConferenceInstance[]) => any): Promise; + list(params: ConferenceListInstanceOptions, callback?: (error: Error | null, items: ConferenceInstance[]) => any): Promise; + /** + * Lists ConferenceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConferenceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConferenceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConferencePage) => any): Promise; + page(params: ConferenceListInstancePageOptions, callback?: (error: Error | null, items: ConferencePage) => any): Promise; + /** + * Retrieve a single page of ConferenceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConferenceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConferenceListInstance(version: V2010, accountSid: string): ConferenceListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ConferenceListInstance; + + instance.get = function get(sid, ): ConferenceContext { + return new ConferenceContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Conferences.json`; + + instance.page = function page(params?: ConferenceListInstancePageOptions | ((error: Error | null, items: ConferencePage) => any), callback?: (error: Error | null, items: ConferencePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601Date(params["dateCreated"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreated<"] = serialize.iso8601Date(params["dateCreatedBefore"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreated>"] = serialize.iso8601Date(params["dateCreatedAfter"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601Date(params["dateUpdated"]); + if (params["dateUpdatedBefore"] !== undefined) + data["DateUpdated<"] = serialize.iso8601Date(params["dateUpdatedBefore"]); + if (params["dateUpdatedAfter"] !== undefined) + data["DateUpdated>"] = serialize.iso8601Date(params["dateUpdatedAfter"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConferencePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConferencePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConferencePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConferenceListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601Date(params["dateCreated"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreated<"] = serialize.iso8601Date(params["dateCreatedBefore"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreated>"] = serialize.iso8601Date(params["dateCreatedAfter"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601Date(params["dateUpdated"]); + if (params["dateUpdatedBefore"] !== undefined) + data["DateUpdated<"] = serialize.iso8601Date(params["dateUpdatedBefore"]); + if (params["dateUpdatedAfter"] !== undefined) + data["DateUpdated>"] = serialize.iso8601Date(params["dateUpdatedAfter"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConferencePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConferencePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConferencePage extends Page { +/** +* Initialize the ConferencePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: ConferenceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ConferenceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConferenceResource): ConferenceInstance { + + return new ConferenceInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/conference/participant.ts b/rest/api/v2010/account/conference/participant.ts new file mode 100644 index 000000000..db2638793 --- /dev/null +++ b/rest/api/v2010/account/conference/participant.ts @@ -0,0 +1,1434 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The status of the participant\'s call in a session. Can be: `queued`, `connecting`, `ringing`, `connected`, `complete`, or `failed`. + */ +export type ParticipantStatus = 'queued'|'connecting'|'ringing'|'connected'|'complete'|'failed'; + + + + +/** + * Options to pass to update a ParticipantInstance + */ +export interface ParticipantContextUpdateOptions { + /** Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. */ + "muted"?: boolean; + /** Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. */ + "hold"?: boolean; + /** The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. */ + "holdUrl"?: string; + /** The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. */ + "holdMethod"?: string; + /** The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. */ + "announceUrl"?: string; + /** The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "announceMethod"?: string; + /** The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `\\\'\\\'`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). */ + "waitUrl"?: string; + /** The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. */ + "waitMethod"?: string; + /** Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. */ + "beepOnExit"?: boolean; + /** Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. */ + "endConferenceOnExit"?: boolean; + /** Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. */ + "coaching"?: boolean; + /** The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. */ + "callSidToCoach"?: string; +} + +/** + * Options to pass to create a ParticipantInstance + */ +export interface ParticipantListInstanceCreateOptions { + /** The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. */ + "from": string; + /** The phone number, SIP address, Client, TwiML App identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. TwiML App identifiers are formatted `app:`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. */ + "to": string; + /** The URL we should call using the `status_callback_method` to send status information to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. */ + "statusCallbackMethod"?: string; + /** The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. */ + "statusCallbackEvent"?: Array; + /** A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. */ + "label"?: string; + /** The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. */ + "timeout"?: number; + /** Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. */ + "record"?: boolean; + /** Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. */ + "muted"?: boolean; + /** Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. */ + "beep"?: string; + /** Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. */ + "startConferenceOnEnter"?: boolean; + /** Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. */ + "endConferenceOnExit"?: boolean; + /** The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `\\\'\\\'`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). */ + "waitUrl"?: string; + /** The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. */ + "waitMethod"?: string; + /** Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. */ + "earlyMedia"?: boolean; + /** The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. */ + "maxParticipants"?: number; + /** Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. */ + "conferenceRecord"?: string; + /** Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. */ + "conferenceTrim"?: string; + /** The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. */ + "conferenceStatusCallback"?: string; + /** The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "conferenceStatusCallbackMethod"?: string; + /** The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. */ + "conferenceStatusCallbackEvent"?: Array; + /** The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. */ + "recordingChannels"?: string; + /** The URL that we should call using the `recording_status_callback_method` when the recording status changes. */ + "recordingStatusCallback"?: string; + /** The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "recordingStatusCallbackMethod"?: string; + /** The SIP username used for authentication. */ + "sipAuthUsername"?: string; + /** The SIP password for authentication. */ + "sipAuthPassword"?: string; + /** The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. */ + "region"?: string; + /** The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. */ + "conferenceRecordingStatusCallback"?: string; + /** The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "conferenceRecordingStatusCallbackMethod"?: string; + /** The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `\\\'in-progress completed failed\\\'`. */ + "recordingStatusCallbackEvent"?: Array; + /** The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `\\\'in-progress completed failed\\\'` */ + "conferenceRecordingStatusCallbackEvent"?: Array; + /** Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. */ + "coaching"?: boolean; + /** The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. */ + "callSidToCoach"?: string; + /** Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant\\\'s audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. */ + "jitterBufferSize"?: string; + /** The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) */ + "byoc"?: string; + /** The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. */ + "callerId"?: string; + /** The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party\\\'s phone. (Branded Calls Beta) */ + "callReason"?: string; + /** The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. */ + "recordingTrack"?: string; + /** The identifier of the configuration to be used when creating and processing the recording */ + "recordingConfigurationId"?: string; + /** The maximum duration of the call in seconds. Constraints depend on account and configuration. */ + "timeLimit"?: number; + /** Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). */ + "machineDetection"?: string; + /** The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. */ + "machineDetectionTimeout"?: number; + /** The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. */ + "machineDetectionSpeechThreshold"?: number; + /** The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. */ + "machineDetectionSpeechEndThreshold"?: number; + /** The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. */ + "machineDetectionSilenceTimeout"?: number; + /** The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. */ + "amdStatusCallback"?: string; + /** The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. */ + "amdStatusCallbackMethod"?: string; + /** Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. */ + "trim"?: string; + /** A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call\\\'s call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. */ + "callToken"?: string; + /** The STIR/SHAKEN passport for this call, provided as a base64 encoded string. Multiple passports (at max 5) are comma separated and provided as base64 encoded string */ + "passports"?: string; + /** The URL that we should use to deliver `push call notification`. */ + "clientNotificationUrl"?: string; + /** The name that populates the display name in the From header. Must be between 2 and 255 characters. Only applicable for calls to sip address. */ + "callerDisplayName"?: string; + /** The emergency caller\\\'s GPS coordinates in decimal degrees format. Format: \\\"latitude longitude\\\" (space-separated) - Latitude: decimal degrees, range -90.0 to +90.0 (negative for South, positive for North) - Longitude: decimal degrees, range -180.0 to +180.0 (negative for West, positive for East) - Precision: up to 6 decimal places recommended for meter-level accuracy Note: If the value exceeds 150 characters, only the first 150 characters will be used. */ + "emergencyCallerPosition"?: string; + /** The emergency caller\\\'s physical location description within a building or facility. Note: If the value exceeds 20 characters, only the first 20 characters will be used. */ + "emergencyCallerLocation"?: string; + /** The emergency caller\\\'s organization or entity name. Note: If the value exceeds 20 characters, only the first 20 characters will be used. */ + "emergencyName"?: string; + /** The emergency caller\\\'s street address including street number and street name. Note: If the value exceeds 60 characters, only the first 60 characters will be used. */ + "emergencyAddress"?: string; + /** The emergency caller\\\'s postal code or ZIP code. Note: If the value exceeds 20 characters, only the first 20 characters will be used. */ + "emergencyZipCode"?: string; + /** The emergency caller\\\'s city or municipality name. Should be the official city name as recognized by local authorities. Used in combination with state and country for emergency call routing. Note: If the value exceeds 20 characters, only the first 20 characters will be used. */ + "emergencyCity"?: string; + /** The emergency caller\\\'s state or province. Note: If the value exceeds 20 characters, only the first 20 characters will be used. */ + "emergencyState"?: string; + /** The emergency caller\\\'s country. Currently supported US and CA only. Note: If the value exceeds 20 characters, only the first 20 characters will be used. */ + "emergencyCountry"?: string; +} + +/** + * Options to pass to each + */ +export interface ParticipantListInstanceEachOptions { + /** Whether to return only participants that are muted. Can be: `true` or `false`. */ + "muted"?: boolean; + /** Whether to return only participants that are on hold. Can be: `true` or `false`. */ + "hold"?: boolean; + /** Whether to return only participants who are coaching another call. Can be: `true` or `false`. */ + "coaching"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ParticipantListInstanceOptions { + /** Whether to return only participants that are muted. Can be: `true` or `false`. */ + "muted"?: boolean; + /** Whether to return only participants that are on hold. Can be: `true` or `false`. */ + "hold"?: boolean; + /** Whether to return only participants who are coaching another call. Can be: `true` or `false`. */ + "coaching"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ParticipantListInstancePageOptions { + /** Whether to return only participants that are muted. Can be: `true` or `false`. */ + "muted"?: boolean; + /** Whether to return only participants that are on hold. Can be: `true` or `false`. */ + "hold"?: boolean; + /** Whether to return only participants who are coaching another call. Can be: `true` or `false`. */ + "coaching"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ParticipantContext { + + /** + * Remove a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Update a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + /** + * Update a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ParticipantContextSolution { + "accountSid": string; + "conferenceSid": string; + "callSid": string; +} + +export class ParticipantContextImpl implements ParticipantContext { + protected _solution: ParticipantContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, conferenceSid: string, callSid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(conferenceSid)) { + throw new Error('Parameter \'conferenceSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + this._solution = { accountSid, conferenceSid, callSid, }; + this._uri = `/Accounts/${accountSid}/Conferences/${conferenceSid}/Participants/${callSid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.conferenceSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.conferenceSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ParticipantContextUpdateOptions | ((error: Error | null, item?: ParticipantInstance) => any),callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["muted"] !== undefined) + data["Muted"] = serialize.bool(params["muted"]); + if (params["hold"] !== undefined) + data["Hold"] = serialize.bool(params["hold"]); + if (params["holdUrl"] !== undefined) + data["HoldUrl"] = params["holdUrl"]; + if (params["holdMethod"] !== undefined) + data["HoldMethod"] = params["holdMethod"]; + if (params["announceUrl"] !== undefined) + data["AnnounceUrl"] = params["announceUrl"]; + if (params["announceMethod"] !== undefined) + data["AnnounceMethod"] = params["announceMethod"]; + if (params["waitUrl"] !== undefined) + data["WaitUrl"] = params["waitUrl"]; + if (params["waitMethod"] !== undefined) + data["WaitMethod"] = params["waitMethod"]; + if (params["beepOnExit"] !== undefined) + data["BeepOnExit"] = serialize.bool(params["beepOnExit"]); + if (params["endConferenceOnExit"] !== undefined) + data["EndConferenceOnExit"] = serialize.bool(params["endConferenceOnExit"]); + if (params["coaching"] !== undefined) + data["Coaching"] = serialize.bool(params["coaching"]); + if (params["callSidToCoach"] !== undefined) + data["CallSidToCoach"] = params["callSidToCoach"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.conferenceSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ParticipantContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["muted"] !== undefined) + data["Muted"] = serialize.bool(params["muted"]); + if (params["hold"] !== undefined) + data["Hold"] = serialize.bool(params["hold"]); + if (params["holdUrl"] !== undefined) + data["HoldUrl"] = params["holdUrl"]; + if (params["holdMethod"] !== undefined) + data["HoldMethod"] = params["holdMethod"]; + if (params["announceUrl"] !== undefined) + data["AnnounceUrl"] = params["announceUrl"]; + if (params["announceMethod"] !== undefined) + data["AnnounceMethod"] = params["announceMethod"]; + if (params["waitUrl"] !== undefined) + data["WaitUrl"] = params["waitUrl"]; + if (params["waitMethod"] !== undefined) + data["WaitMethod"] = params["waitMethod"]; + if (params["beepOnExit"] !== undefined) + data["BeepOnExit"] = serialize.bool(params["beepOnExit"]); + if (params["endConferenceOnExit"] !== undefined) + data["EndConferenceOnExit"] = serialize.bool(params["endConferenceOnExit"]); + if (params["coaching"] !== undefined) + data["Coaching"] = serialize.bool(params["coaching"]); + if (params["callSidToCoach"] !== undefined) + data["CallSidToCoach"] = params["callSidToCoach"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.conferenceSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ParticipantPayload extends TwilioResponsePayload { + participants: ParticipantResource[]; +} + +interface ParticipantResource { + account_sid: string; + call_sid: string; + label: string; + call_sid_to_coach: string; + coaching: boolean; + conference_sid: string; + date_created: Date; + date_updated: Date; + end_conference_on_exit: boolean; + muted: boolean; + hold: boolean; + start_conference_on_enter: boolean; + status: ParticipantStatus; + queue_time: string; + uri: string; +} + +export class ParticipantInstance { + protected _solution: ParticipantContextSolution; + protected _context?: ParticipantContext; + + constructor(protected _version: V2010, payload: ParticipantResource, accountSid: string, conferenceSid: string, callSid?: string) { + + this.accountSid = (payload.account_sid); + this.callSid = (payload.call_sid); + this.label = (payload.label); + this.callSidToCoach = (payload.call_sid_to_coach); + this.coaching = (payload.coaching); + this.conferenceSid = (payload.conference_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.endConferenceOnExit = (payload.end_conference_on_exit); + this.muted = (payload.muted); + this.hold = (payload.hold); + this.startConferenceOnEnter = (payload.start_conference_on_enter); + this.status = payload.status; + this.queueTime = (payload.queue_time); + this.uri = (payload.uri); + + this._solution = { accountSid, conferenceSid, callSid: callSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resource. + */ + accountSid: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Participant resource is associated with. + */ + callSid: string; + /** + * The user-specified label of this participant, if one was given when the participant was created. This may be used to fetch, update or delete the participant. + */ + label: string; + /** + * The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + */ + callSidToCoach: string; + /** + * Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + */ + coaching: boolean; + /** + * The SID of the conference the participant is in. + */ + conferenceSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * Whether the conference ends when the participant leaves. Can be: `true` or `false` and the default is `false`. If `true`, the conference ends and all other participants drop out when the participant leaves. + */ + endConferenceOnExit: boolean; + /** + * Whether the participant is muted. Can be `true` or `false`. + */ + muted: boolean; + /** + * Whether the participant is on hold. Can be `true` or `false`. + */ + hold: boolean; + /** + * Whether the conference starts when the participant joins the conference, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + */ + startConferenceOnEnter: boolean; + status: ParticipantStatus; + /** + * The wait time in milliseconds before participant\'s call is placed. Only available in the response to a create participant request. + */ + queueTime: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): ParticipantContext { + this._context = this._context || new ParticipantContextImpl(this._version, this._solution.accountSid, this._solution.conferenceSid, this._solution.callSid); + return this._context; + } + + /** + * Remove a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Update a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + callSid: this.callSid, + label: this.label, + callSidToCoach: this.callSidToCoach, + coaching: this.coaching, + conferenceSid: this.conferenceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + endConferenceOnExit: this.endConferenceOnExit, + muted: this.muted, + hold: this.hold, + startConferenceOnEnter: this.startConferenceOnEnter, + status: this.status, + queueTime: this.queueTime, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ParticipantSolution { + accountSid: string; + conferenceSid: string; +} + +export interface ParticipantListInstance { + _version: V2010; + _solution: ParticipantSolution; + _uri: string; + + (callSid: string, ): ParticipantContext; + get(callSid: string, ): ParticipantContext; + + + + + + + + + /** + * Create a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + create(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + /** + * Create a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + createWithHttpInfo(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ParticipantInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + each(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ParticipantInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + /** + * Retrieve a single target page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ParticipantInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise; + list(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise; + /** + * Lists ParticipantInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + page(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + /** + * Retrieve a single page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ParticipantListInstance(version: V2010, accountSid: string, conferenceSid: string): ParticipantListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(conferenceSid)) { + throw new Error('Parameter \'conferenceSid\' is not valid.'); + } + + const instance = ((callSid, ) => instance.get(callSid, )) as ParticipantListInstance; + + instance.get = function get(callSid, ): ParticipantContext { + return new ParticipantContextImpl(version, accountSid, conferenceSid, callSid); + } + + instance._version = version; + instance._solution = { accountSid, conferenceSid, }; + instance._uri = `/Accounts/${accountSid}/Conferences/${conferenceSid}/Participants.json`; + + instance.create = function create(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, items: ParticipantInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["from"] === null || params["from"] === undefined) { + throw new Error('Required parameter "params[\'from\']" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + let data: any = {}; + + + + data["From"] = params["from"]; + + data["To"] = params["to"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["statusCallbackEvent"] !== undefined) + data["StatusCallbackEvent"] = serialize.map(params["statusCallbackEvent"], (e: string) => (e)); + if (params["label"] !== undefined) + data["Label"] = params["label"]; + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["record"] !== undefined) + data["Record"] = serialize.bool(params["record"]); + if (params["muted"] !== undefined) + data["Muted"] = serialize.bool(params["muted"]); + if (params["beep"] !== undefined) + data["Beep"] = params["beep"]; + if (params["startConferenceOnEnter"] !== undefined) + data["StartConferenceOnEnter"] = serialize.bool(params["startConferenceOnEnter"]); + if (params["endConferenceOnExit"] !== undefined) + data["EndConferenceOnExit"] = serialize.bool(params["endConferenceOnExit"]); + if (params["waitUrl"] !== undefined) + data["WaitUrl"] = params["waitUrl"]; + if (params["waitMethod"] !== undefined) + data["WaitMethod"] = params["waitMethod"]; + if (params["earlyMedia"] !== undefined) + data["EarlyMedia"] = serialize.bool(params["earlyMedia"]); + if (params["maxParticipants"] !== undefined) + data["MaxParticipants"] = params["maxParticipants"]; + if (params["conferenceRecord"] !== undefined) + data["ConferenceRecord"] = params["conferenceRecord"]; + if (params["conferenceTrim"] !== undefined) + data["ConferenceTrim"] = params["conferenceTrim"]; + if (params["conferenceStatusCallback"] !== undefined) + data["ConferenceStatusCallback"] = params["conferenceStatusCallback"]; + if (params["conferenceStatusCallbackMethod"] !== undefined) + data["ConferenceStatusCallbackMethod"] = params["conferenceStatusCallbackMethod"]; + if (params["conferenceStatusCallbackEvent"] !== undefined) + data["ConferenceStatusCallbackEvent"] = serialize.map(params["conferenceStatusCallbackEvent"], (e: string) => (e)); + if (params["recordingChannels"] !== undefined) + data["RecordingChannels"] = params["recordingChannels"]; + if (params["recordingStatusCallback"] !== undefined) + data["RecordingStatusCallback"] = params["recordingStatusCallback"]; + if (params["recordingStatusCallbackMethod"] !== undefined) + data["RecordingStatusCallbackMethod"] = params["recordingStatusCallbackMethod"]; + if (params["sipAuthUsername"] !== undefined) + data["SipAuthUsername"] = params["sipAuthUsername"]; + if (params["sipAuthPassword"] !== undefined) + data["SipAuthPassword"] = params["sipAuthPassword"]; + if (params["region"] !== undefined) + data["Region"] = params["region"]; + if (params["conferenceRecordingStatusCallback"] !== undefined) + data["ConferenceRecordingStatusCallback"] = params["conferenceRecordingStatusCallback"]; + if (params["conferenceRecordingStatusCallbackMethod"] !== undefined) + data["ConferenceRecordingStatusCallbackMethod"] = params["conferenceRecordingStatusCallbackMethod"]; + if (params["recordingStatusCallbackEvent"] !== undefined) + data["RecordingStatusCallbackEvent"] = serialize.map(params["recordingStatusCallbackEvent"], (e: string) => (e)); + if (params["conferenceRecordingStatusCallbackEvent"] !== undefined) + data["ConferenceRecordingStatusCallbackEvent"] = serialize.map(params["conferenceRecordingStatusCallbackEvent"], (e: string) => (e)); + if (params["coaching"] !== undefined) + data["Coaching"] = serialize.bool(params["coaching"]); + if (params["callSidToCoach"] !== undefined) + data["CallSidToCoach"] = params["callSidToCoach"]; + if (params["jitterBufferSize"] !== undefined) + data["JitterBufferSize"] = params["jitterBufferSize"]; + if (params["byoc"] !== undefined) + data["Byoc"] = params["byoc"]; + if (params["callerId"] !== undefined) + data["CallerId"] = params["callerId"]; + if (params["callReason"] !== undefined) + data["CallReason"] = params["callReason"]; + if (params["recordingTrack"] !== undefined) + data["RecordingTrack"] = params["recordingTrack"]; + if (params["recordingConfigurationId"] !== undefined) + data["RecordingConfigurationId"] = params["recordingConfigurationId"]; + if (params["timeLimit"] !== undefined) + data["TimeLimit"] = params["timeLimit"]; + if (params["machineDetection"] !== undefined) + data["MachineDetection"] = params["machineDetection"]; + if (params["machineDetectionTimeout"] !== undefined) + data["MachineDetectionTimeout"] = params["machineDetectionTimeout"]; + if (params["machineDetectionSpeechThreshold"] !== undefined) + data["MachineDetectionSpeechThreshold"] = params["machineDetectionSpeechThreshold"]; + if (params["machineDetectionSpeechEndThreshold"] !== undefined) + data["MachineDetectionSpeechEndThreshold"] = params["machineDetectionSpeechEndThreshold"]; + if (params["machineDetectionSilenceTimeout"] !== undefined) + data["MachineDetectionSilenceTimeout"] = params["machineDetectionSilenceTimeout"]; + if (params["amdStatusCallback"] !== undefined) + data["AmdStatusCallback"] = params["amdStatusCallback"]; + if (params["amdStatusCallbackMethod"] !== undefined) + data["AmdStatusCallbackMethod"] = params["amdStatusCallbackMethod"]; + if (params["trim"] !== undefined) + data["Trim"] = params["trim"]; + if (params["callToken"] !== undefined) + data["CallToken"] = params["callToken"]; + if (params["passports"] !== undefined) + data["Passports"] = params["passports"]; + if (params["clientNotificationUrl"] !== undefined) + data["ClientNotificationUrl"] = params["clientNotificationUrl"]; + if (params["callerDisplayName"] !== undefined) + data["CallerDisplayName"] = params["callerDisplayName"]; + if (params["emergencyCallerPosition"] !== undefined) + data["EmergencyCallerPosition"] = params["emergencyCallerPosition"]; + if (params["emergencyCallerLocation"] !== undefined) + data["EmergencyCallerLocation"] = params["emergencyCallerLocation"]; + if (params["emergencyName"] !== undefined) + data["EmergencyName"] = params["emergencyName"]; + if (params["emergencyAddress"] !== undefined) + data["EmergencyAddress"] = params["emergencyAddress"]; + if (params["emergencyZipCode"] !== undefined) + data["EmergencyZipCode"] = params["emergencyZipCode"]; + if (params["emergencyCity"] !== undefined) + data["EmergencyCity"] = params["emergencyCity"]; + if (params["emergencyState"] !== undefined) + data["EmergencyState"] = params["emergencyState"]; + if (params["emergencyCountry"] !== undefined) + data["EmergencyCountry"] = params["emergencyCountry"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.conferenceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["from"] === null || params["from"] === undefined) { + throw new Error('Required parameter "params[\'from\']" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + let data: any = {}; + + + + data["From"] = params["from"]; + + data["To"] = params["to"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["statusCallbackEvent"] !== undefined) + data["StatusCallbackEvent"] = serialize.map(params["statusCallbackEvent"], (e: string) => (e)); + if (params["label"] !== undefined) + data["Label"] = params["label"]; + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["record"] !== undefined) + data["Record"] = serialize.bool(params["record"]); + if (params["muted"] !== undefined) + data["Muted"] = serialize.bool(params["muted"]); + if (params["beep"] !== undefined) + data["Beep"] = params["beep"]; + if (params["startConferenceOnEnter"] !== undefined) + data["StartConferenceOnEnter"] = serialize.bool(params["startConferenceOnEnter"]); + if (params["endConferenceOnExit"] !== undefined) + data["EndConferenceOnExit"] = serialize.bool(params["endConferenceOnExit"]); + if (params["waitUrl"] !== undefined) + data["WaitUrl"] = params["waitUrl"]; + if (params["waitMethod"] !== undefined) + data["WaitMethod"] = params["waitMethod"]; + if (params["earlyMedia"] !== undefined) + data["EarlyMedia"] = serialize.bool(params["earlyMedia"]); + if (params["maxParticipants"] !== undefined) + data["MaxParticipants"] = params["maxParticipants"]; + if (params["conferenceRecord"] !== undefined) + data["ConferenceRecord"] = params["conferenceRecord"]; + if (params["conferenceTrim"] !== undefined) + data["ConferenceTrim"] = params["conferenceTrim"]; + if (params["conferenceStatusCallback"] !== undefined) + data["ConferenceStatusCallback"] = params["conferenceStatusCallback"]; + if (params["conferenceStatusCallbackMethod"] !== undefined) + data["ConferenceStatusCallbackMethod"] = params["conferenceStatusCallbackMethod"]; + if (params["conferenceStatusCallbackEvent"] !== undefined) + data["ConferenceStatusCallbackEvent"] = serialize.map(params["conferenceStatusCallbackEvent"], (e: string) => (e)); + if (params["recordingChannels"] !== undefined) + data["RecordingChannels"] = params["recordingChannels"]; + if (params["recordingStatusCallback"] !== undefined) + data["RecordingStatusCallback"] = params["recordingStatusCallback"]; + if (params["recordingStatusCallbackMethod"] !== undefined) + data["RecordingStatusCallbackMethod"] = params["recordingStatusCallbackMethod"]; + if (params["sipAuthUsername"] !== undefined) + data["SipAuthUsername"] = params["sipAuthUsername"]; + if (params["sipAuthPassword"] !== undefined) + data["SipAuthPassword"] = params["sipAuthPassword"]; + if (params["region"] !== undefined) + data["Region"] = params["region"]; + if (params["conferenceRecordingStatusCallback"] !== undefined) + data["ConferenceRecordingStatusCallback"] = params["conferenceRecordingStatusCallback"]; + if (params["conferenceRecordingStatusCallbackMethod"] !== undefined) + data["ConferenceRecordingStatusCallbackMethod"] = params["conferenceRecordingStatusCallbackMethod"]; + if (params["recordingStatusCallbackEvent"] !== undefined) + data["RecordingStatusCallbackEvent"] = serialize.map(params["recordingStatusCallbackEvent"], (e: string) => (e)); + if (params["conferenceRecordingStatusCallbackEvent"] !== undefined) + data["ConferenceRecordingStatusCallbackEvent"] = serialize.map(params["conferenceRecordingStatusCallbackEvent"], (e: string) => (e)); + if (params["coaching"] !== undefined) + data["Coaching"] = serialize.bool(params["coaching"]); + if (params["callSidToCoach"] !== undefined) + data["CallSidToCoach"] = params["callSidToCoach"]; + if (params["jitterBufferSize"] !== undefined) + data["JitterBufferSize"] = params["jitterBufferSize"]; + if (params["byoc"] !== undefined) + data["Byoc"] = params["byoc"]; + if (params["callerId"] !== undefined) + data["CallerId"] = params["callerId"]; + if (params["callReason"] !== undefined) + data["CallReason"] = params["callReason"]; + if (params["recordingTrack"] !== undefined) + data["RecordingTrack"] = params["recordingTrack"]; + if (params["recordingConfigurationId"] !== undefined) + data["RecordingConfigurationId"] = params["recordingConfigurationId"]; + if (params["timeLimit"] !== undefined) + data["TimeLimit"] = params["timeLimit"]; + if (params["machineDetection"] !== undefined) + data["MachineDetection"] = params["machineDetection"]; + if (params["machineDetectionTimeout"] !== undefined) + data["MachineDetectionTimeout"] = params["machineDetectionTimeout"]; + if (params["machineDetectionSpeechThreshold"] !== undefined) + data["MachineDetectionSpeechThreshold"] = params["machineDetectionSpeechThreshold"]; + if (params["machineDetectionSpeechEndThreshold"] !== undefined) + data["MachineDetectionSpeechEndThreshold"] = params["machineDetectionSpeechEndThreshold"]; + if (params["machineDetectionSilenceTimeout"] !== undefined) + data["MachineDetectionSilenceTimeout"] = params["machineDetectionSilenceTimeout"]; + if (params["amdStatusCallback"] !== undefined) + data["AmdStatusCallback"] = params["amdStatusCallback"]; + if (params["amdStatusCallbackMethod"] !== undefined) + data["AmdStatusCallbackMethod"] = params["amdStatusCallbackMethod"]; + if (params["trim"] !== undefined) + data["Trim"] = params["trim"]; + if (params["callToken"] !== undefined) + data["CallToken"] = params["callToken"]; + if (params["passports"] !== undefined) + data["Passports"] = params["passports"]; + if (params["clientNotificationUrl"] !== undefined) + data["ClientNotificationUrl"] = params["clientNotificationUrl"]; + if (params["callerDisplayName"] !== undefined) + data["CallerDisplayName"] = params["callerDisplayName"]; + if (params["emergencyCallerPosition"] !== undefined) + data["EmergencyCallerPosition"] = params["emergencyCallerPosition"]; + if (params["emergencyCallerLocation"] !== undefined) + data["EmergencyCallerLocation"] = params["emergencyCallerLocation"]; + if (params["emergencyName"] !== undefined) + data["EmergencyName"] = params["emergencyName"]; + if (params["emergencyAddress"] !== undefined) + data["EmergencyAddress"] = params["emergencyAddress"]; + if (params["emergencyZipCode"] !== undefined) + data["EmergencyZipCode"] = params["emergencyZipCode"]; + if (params["emergencyCity"] !== undefined) + data["EmergencyCity"] = params["emergencyCity"]; + if (params["emergencyState"] !== undefined) + data["EmergencyState"] = params["emergencyState"]; + if (params["emergencyCountry"] !== undefined) + data["EmergencyCountry"] = params["emergencyCountry"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.conferenceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ParticipantPage) => any), callback?: (error: Error | null, items: ParticipantPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["muted"] !== undefined) + data["Muted"] = serialize.bool(params["muted"]); + if (params["hold"] !== undefined) + data["Hold"] = serialize.bool(params["hold"]); + if (params["coaching"] !== undefined) + data["Coaching"] = serialize.bool(params["coaching"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ParticipantPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ParticipantPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["muted"] !== undefined) + data["Muted"] = serialize.bool(params["muted"]); + if (params["hold"] !== undefined) + data["Hold"] = serialize.bool(params["hold"]); + if (params["coaching"] !== undefined) + data["Coaching"] = serialize.bool(params["coaching"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ParticipantPage extends Page { +/** +* Initialize the ParticipantPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: ParticipantSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ParticipantInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ParticipantResource): ParticipantInstance { + + return new ParticipantInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.conferenceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/conference/recording.ts b/rest/api/v2010/account/conference/recording.ts new file mode 100644 index 000000000..feb0d4cc7 --- /dev/null +++ b/rest/api/v2010/account/conference/recording.ts @@ -0,0 +1,899 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * How the recording was created. Can be: `DialVerb`, `Conference`, `OutboundAPI`, `Trunking`, `RecordVerb`, `StartCallRecordingAPI`, `StartConferenceRecordingAPI`. + */ +export type RecordingSource = 'DialVerb'|'Conference'|'OutboundAPI'|'Trunking'|'RecordVerb'|'StartCallRecordingAPI'|'StartConferenceRecordingAPI'; + +/** + * The status of the recording. Can be: `processing`, `completed` and `absent`. For more detailed statuses on in-progress recordings, check out how to [Update a Recording Resource](https://www.twilio.com/docs/voice/api/recording#update-a-recording-resource). + */ +export type RecordingStatus = 'in-progress'|'paused'|'stopped'|'processing'|'completed'|'absent'; + + + + +/** + * Options to pass to update a RecordingInstance + */ +export interface RecordingContextUpdateOptions { + /** */ + "status": RecordingStatus; + /** Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. */ + "pauseBehavior"?: string; +} + +/** + * Options to pass to each + */ +export interface RecordingListInstanceEachOptions { + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreated"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedBefore"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RecordingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RecordingListInstanceOptions { + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreated"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedBefore"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RecordingListInstancePageOptions { + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreated"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedBefore"?: Date; + /** The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. */ + "dateCreatedAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RecordingContext { + + /** + * Remove a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a RecordingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise; + + /** + * Update a RecordingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RecordingContextSolution { + "accountSid": string; + "conferenceSid": string; + "sid": string; +} + +export class RecordingContextImpl implements RecordingContext { + protected _solution: RecordingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, conferenceSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(conferenceSid)) { + throw new Error('Parameter \'conferenceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, conferenceSid, sid, }; + this._uri = `/Accounts/${accountSid}/Conferences/${conferenceSid}/Recordings/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.conferenceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.conferenceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: RecordingContextUpdateOptions,callback?: (error: Error | null, item?: RecordingInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + if (params["pauseBehavior"] !== undefined) + data["PauseBehavior"] = params["pauseBehavior"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.conferenceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: RecordingContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + if (params["pauseBehavior"] !== undefined) + data["PauseBehavior"] = params["pauseBehavior"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.conferenceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RecordingPayload extends TwilioResponsePayload { + recordings: RecordingResource[]; +} + +interface RecordingResource { + account_sid: string; + api_version: string; + call_sid: string; + conference_sid: string; + date_created: Date; + date_updated: Date; + start_time: Date; + duration: string; + sid: string; + price: string; + price_unit: string; + status: RecordingStatus; + channels: number; + source: RecordingSource; + error_code: number; + encryption_details: any; + uri: string; +} + +export class RecordingInstance { + protected _solution: RecordingContextSolution; + protected _context?: RecordingContext; + + constructor(protected _version: V2010, payload: RecordingResource, accountSid: string, conferenceSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.callSid = (payload.call_sid); + this.conferenceSid = (payload.conference_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.startTime = deserialize.rfc2822DateTime(payload.start_time); + this.duration = (payload.duration); + this.sid = (payload.sid); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.status = payload.status; + this.channels = deserialize.integer(payload.channels); + this.source = payload.source; + this.errorCode = deserialize.integer(payload.error_code); + this.encryptionDetails = (payload.encryption_details); + this.uri = (payload.uri); + + this._solution = { accountSid, conferenceSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference Recording resource. + */ + accountSid: string; + /** + * The API version used to create the recording. + */ + apiVersion: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Conference Recording resource is associated with. + */ + callSid: string; + /** + * The Conference SID that identifies the conference associated with the recording. + */ + conferenceSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + startTime: Date; + /** + * The length of the recording in seconds. + */ + duration: string; + /** + * The unique string that that we created to identify the Conference Recording resource. + */ + sid: string; + /** + * The one-time cost of creating the recording in the `price_unit` currency. + */ + price: string; + /** + * The currency used in the `price` property. Example: `USD`. + */ + priceUnit: string; + status: RecordingStatus; + /** + * The number of channels in the final recording file. Can be: `1`, or `2`. Separating a two leg call into two separate channels of the recording file is supported in [Dial](https://www.twilio.com/docs/voice/twiml/dial#attributes-record) and [Outbound Rest API](https://www.twilio.com/docs/voice/make-calls) record options. + */ + channels: number; + source: RecordingSource; + /** + * The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + */ + errorCode: number; + /** + * How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + */ + encryptionDetails: any; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): RecordingContext { + this._context = this._context || new RecordingContextImpl(this._version, this._solution.accountSid, this._solution.conferenceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RecordingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a RecordingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + callSid: this.callSid, + conferenceSid: this.conferenceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + startTime: this.startTime, + duration: this.duration, + sid: this.sid, + price: this.price, + priceUnit: this.priceUnit, + status: this.status, + channels: this.channels, + source: this.source, + errorCode: this.errorCode, + encryptionDetails: this.encryptionDetails, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RecordingSolution { + accountSid: string; + conferenceSid: string; +} + +export interface RecordingListInstance { + _version: V2010; + _solution: RecordingSolution; + _uri: string; + + (sid: string, ): RecordingContext; + get(sid: string, ): RecordingContext; + + + + + + + + + + /** + * Streams RecordingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + each(params: RecordingListInstanceEachOptions, callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RecordingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RecordingListInstanceEachOptions, callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RecordingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RecordingPage) => any): Promise; + /** + * Retrieve a single target page of RecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RecordingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RecordingInstance[]) => any): Promise; + list(params: RecordingListInstanceOptions, callback?: (error: Error | null, items: RecordingInstance[]) => any): Promise; + /** + * Lists RecordingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RecordingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RecordingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RecordingPage) => any): Promise; + page(params: RecordingListInstancePageOptions, callback?: (error: Error | null, items: RecordingPage) => any): Promise; + /** + * Retrieve a single page of RecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RecordingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RecordingListInstance(version: V2010, accountSid: string, conferenceSid: string): RecordingListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(conferenceSid)) { + throw new Error('Parameter \'conferenceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RecordingListInstance; + + instance.get = function get(sid, ): RecordingContext { + return new RecordingContextImpl(version, accountSid, conferenceSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, conferenceSid, }; + instance._uri = `/Accounts/${accountSid}/Conferences/${conferenceSid}/Recordings.json`; + + instance.page = function page(params?: RecordingListInstancePageOptions | ((error: Error | null, items: RecordingPage) => any), callback?: (error: Error | null, items: RecordingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601Date(params["dateCreated"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreated<"] = serialize.iso8601Date(params["dateCreatedBefore"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreated>"] = serialize.iso8601Date(params["dateCreatedAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RecordingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RecordingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RecordingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RecordingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601Date(params["dateCreated"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreated<"] = serialize.iso8601Date(params["dateCreatedBefore"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreated>"] = serialize.iso8601Date(params["dateCreatedAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RecordingPage extends Page { +/** +* Initialize the RecordingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: RecordingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RecordingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RecordingResource): RecordingInstance { + + return new RecordingInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.conferenceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/connectApp.ts b/rest/api/v2010/account/connectApp.ts new file mode 100644 index 000000000..6dc343e12 --- /dev/null +++ b/rest/api/v2010/account/connectApp.ts @@ -0,0 +1,883 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The set of permissions that your ConnectApp requests. + */ +export type ConnectAppPermission = 'get-all'|'post-all'; + + + + +/** + * Options to pass to update a ConnectAppInstance + */ +export interface ConnectAppContextUpdateOptions { + /** The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. */ + "authorizeRedirectUrl"?: string; + /** The company name to set for the Connect App. */ + "companyName"?: string; + /** The HTTP method to use when calling `deauthorize_callback_url`. */ + "deauthorizeCallbackMethod"?: string; + /** The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. */ + "deauthorizeCallbackUrl"?: string; + /** A description of the Connect App. */ + "description"?: string; + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** A public URL where users can obtain more information about this Connect App. */ + "homepageUrl"?: string; + /** A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. */ + "permissions"?: Array; +} + +/** + * Options to pass to each + */ +export interface ConnectAppListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConnectAppInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConnectAppListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConnectAppListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ConnectAppContext { + + /** + * Remove a ConnectAppInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ConnectAppInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ConnectAppInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance + */ + fetch(callback?: (error: Error | null, item?: ConnectAppInstance) => any): Promise + + /** + * Fetch a ConnectAppInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ConnectAppInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance + */ + update(callback?: (error: Error | null, item?: ConnectAppInstance) => any): Promise; + /** + * Update a ConnectAppInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance + */ + update(params: ConnectAppContextUpdateOptions, callback?: (error: Error | null, item?: ConnectAppInstance) => any): Promise; + + /** + * Update a ConnectAppInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConnectAppInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConnectAppContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConnectAppContextSolution { + "accountSid": string; + "sid": string; +} + +export class ConnectAppContextImpl implements ConnectAppContext { + protected _solution: ConnectAppContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/ConnectApps/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ConnectAppInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConnectAppInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConnectAppInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ConnectAppContextUpdateOptions | ((error: Error | null, item?: ConnectAppInstance) => any),callback?: (error: Error | null, item?: ConnectAppInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["authorizeRedirectUrl"] !== undefined) + data["AuthorizeRedirectUrl"] = params["authorizeRedirectUrl"]; + if (params["companyName"] !== undefined) + data["CompanyName"] = params["companyName"]; + if (params["deauthorizeCallbackMethod"] !== undefined) + data["DeauthorizeCallbackMethod"] = params["deauthorizeCallbackMethod"]; + if (params["deauthorizeCallbackUrl"] !== undefined) + data["DeauthorizeCallbackUrl"] = params["deauthorizeCallbackUrl"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["homepageUrl"] !== undefined) + data["HomepageUrl"] = params["homepageUrl"]; + if (params["permissions"] !== undefined) + data["Permissions"] = serialize.map(params["permissions"], (e: ConnectAppPermission) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConnectAppInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ConnectAppContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["authorizeRedirectUrl"] !== undefined) + data["AuthorizeRedirectUrl"] = params["authorizeRedirectUrl"]; + if (params["companyName"] !== undefined) + data["CompanyName"] = params["companyName"]; + if (params["deauthorizeCallbackMethod"] !== undefined) + data["DeauthorizeCallbackMethod"] = params["deauthorizeCallbackMethod"]; + if (params["deauthorizeCallbackUrl"] !== undefined) + data["DeauthorizeCallbackUrl"] = params["deauthorizeCallbackUrl"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["homepageUrl"] !== undefined) + data["HomepageUrl"] = params["homepageUrl"]; + if (params["permissions"] !== undefined) + data["Permissions"] = serialize.map(params["permissions"], (e: ConnectAppPermission) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConnectAppInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConnectAppPayload extends TwilioResponsePayload { + connect_apps: ConnectAppResource[]; +} + +interface ConnectAppResource { + account_sid: string; + authorize_redirect_url: string; + company_name: string; + deauthorize_callback_method: string; + deauthorize_callback_url: string; + description: string; + friendly_name: string; + homepage_url: string; + permissions: Array; + sid: string; + uri: string; +} + +export class ConnectAppInstance { + protected _solution: ConnectAppContextSolution; + protected _context?: ConnectAppContext; + + constructor(protected _version: V2010, payload: ConnectAppResource, accountSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.authorizeRedirectUrl = (payload.authorize_redirect_url); + this.companyName = (payload.company_name); + this.deauthorizeCallbackMethod = (payload.deauthorize_callback_method); + this.deauthorizeCallbackUrl = (payload.deauthorize_callback_url); + this.description = (payload.description); + this.friendlyName = (payload.friendly_name); + this.homepageUrl = (payload.homepage_url); + this.permissions = (payload.permissions); + this.sid = (payload.sid); + this.uri = (payload.uri); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ConnectApp resource. + */ + accountSid: string; + /** + * The URL we redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + */ + authorizeRedirectUrl: string; + /** + * The company name set for the Connect App. + */ + companyName: string; + /** + * The HTTP method we use to call `deauthorize_callback_url`. + */ + deauthorizeCallbackMethod: string; + /** + * The URL we call using the `deauthorize_callback_method` to de-authorize the Connect App. + */ + deauthorizeCallbackUrl: string; + /** + * The description of the Connect App. + */ + description: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The public URL where users can obtain more information about this Connect App. + */ + homepageUrl: string; + /** + * The set of permissions that your ConnectApp requests. + */ + permissions: Array; + /** + * The unique string that that we created to identify the ConnectApp resource. + */ + sid: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): ConnectAppContext { + this._context = this._context || new ConnectAppContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ConnectAppInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ConnectAppInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ConnectAppInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance + */ + fetch(callback?: (error: Error | null, item?: ConnectAppInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConnectAppInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ConnectAppInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance + */ + update(callback?: (error: Error | null, item?: ConnectAppInstance) => any): Promise; + /** + * Update a ConnectAppInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance + */ + update(params: ConnectAppContextUpdateOptions, callback?: (error: Error | null, item?: ConnectAppInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ConnectAppInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConnectAppInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConnectAppInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectAppInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConnectAppContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + authorizeRedirectUrl: this.authorizeRedirectUrl, + companyName: this.companyName, + deauthorizeCallbackMethod: this.deauthorizeCallbackMethod, + deauthorizeCallbackUrl: this.deauthorizeCallbackUrl, + description: this.description, + friendlyName: this.friendlyName, + homepageUrl: this.homepageUrl, + permissions: this.permissions, + sid: this.sid, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConnectAppSolution { + accountSid: string; +} + +export interface ConnectAppListInstance { + _version: V2010; + _solution: ConnectAppSolution; + _uri: string; + + (sid: string, ): ConnectAppContext; + get(sid: string, ): ConnectAppContext; + + + + + + + + + + /** + * Streams ConnectAppInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectAppListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConnectAppInstance, done: (err?: Error) => void) => void): void; + each(params: ConnectAppListInstanceEachOptions, callback?: (item: ConnectAppInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConnectAppInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectAppListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConnectAppInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConnectAppListInstanceEachOptions, callback?: (item: ConnectAppInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConnectAppInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConnectAppPage) => any): Promise; + /** + * Retrieve a single target page of ConnectAppInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConnectAppInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectAppListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConnectAppInstance[]) => any): Promise; + list(params: ConnectAppListInstanceOptions, callback?: (error: Error | null, items: ConnectAppInstance[]) => any): Promise; + /** + * Lists ConnectAppInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectAppListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConnectAppListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConnectAppInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectAppListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConnectAppPage) => any): Promise; + page(params: ConnectAppListInstancePageOptions, callback?: (error: Error | null, items: ConnectAppPage) => any): Promise; + /** + * Retrieve a single page of ConnectAppInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectAppListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConnectAppListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConnectAppListInstance(version: V2010, accountSid: string): ConnectAppListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ConnectAppListInstance; + + instance.get = function get(sid, ): ConnectAppContext { + return new ConnectAppContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/ConnectApps.json`; + + instance.page = function page(params?: ConnectAppListInstancePageOptions | ((error: Error | null, items: ConnectAppPage) => any), callback?: (error: Error | null, items: ConnectAppPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConnectAppPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConnectAppPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConnectAppPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConnectAppListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConnectAppPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConnectAppPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConnectAppPage extends Page { +/** +* Initialize the ConnectAppPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: ConnectAppSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ConnectAppInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConnectAppResource): ConnectAppInstance { + + return new ConnectAppInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/incomingPhoneNumber.ts b/rest/api/v2010/account/incomingPhoneNumber.ts new file mode 100644 index 000000000..500a57dca --- /dev/null +++ b/rest/api/v2010/account/incomingPhoneNumber.ts @@ -0,0 +1,1478 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { AssignedAddOnListInstance } from "./incomingPhoneNumber/assignedAddOn"; +import { LocalListInstance } from "./incomingPhoneNumber/local"; +import { MobileListInstance } from "./incomingPhoneNumber/mobile"; +import { TollFreeListInstance } from "./incomingPhoneNumber/tollFree"; +import { PhoneNumberCapabilities } from "../../../../interfaces"; + + +/** + * Whether the phone number requires an [Address](https://www.twilio.com/docs/usage/api/address) registered with Twilio. Can be: `none`, `any`, `local`, or `foreign`. + */ +export type IncomingPhoneNumberAddressRequirement = 'none'|'any'|'local'|'foreign'; + +/** + * The status of address registration with emergency services. A registered emergency address will be used during handling of emergency calls from this number. + */ +export type IncomingPhoneNumberEmergencyAddressStatus = 'registered'|'unregistered'|'pending-registration'|'registration-failure'|'pending-unregistration'|'unregistration-failure'; + +/** + * The parameter displays if emergency calling is enabled for this number. Active numbers may place emergency calls by dialing valid emergency numbers for the country. + */ +export type IncomingPhoneNumberEmergencyStatus = 'Active'|'Inactive'; + +export type IncomingPhoneNumberVoiceReceiveMode = 'voice'|'fax'; + + + + +/** + * Options to pass to update a IncomingPhoneNumberInstance + */ +export interface IncomingPhoneNumberContextUpdateOptions { + /** The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). */ + "accountSid"?: string; + /** The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. */ + "apiVersion"?: string; + /** A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. */ + "friendlyName"?: string; + /** The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. */ + "smsApplicationSid"?: string; + /** The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "smsFallbackMethod"?: string; + /** The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. */ + "smsFallbackUrl"?: string; + /** The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "smsMethod"?: string; + /** The URL we should call when the phone number receives an incoming SMS message. */ + "smsUrl"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "statusCallbackMethod"?: string; + /** The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. */ + "voiceApplicationSid"?: string; + /** Whether to lookup the caller\\\'s name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. */ + "voiceCallerIdLookup"?: boolean; + /** The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "voiceMethod"?: string; + /** The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. */ + "voiceUrl"?: string; + /** */ + "emergencyStatus"?: IncomingPhoneNumberEmergencyStatus; + /** The SID of the emergency address configuration to use for emergency calling from this phone number. */ + "emergencyAddressSid"?: string; + /** The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. */ + "trunkSid"?: string; + /** */ + "voiceReceiveMode"?: IncomingPhoneNumberVoiceReceiveMode; + /** The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. */ + "identitySid"?: string; + /** The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. */ + "addressSid"?: string; + /** The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. */ + "bundleSid"?: string; +} + +/** + * Options to pass to create a IncomingPhoneNumberInstance + */ +export interface IncomingPhoneNumberListInstanceCreateOptions { + /** The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. */ + "apiVersion"?: string; + /** A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. */ + "friendlyName"?: string; + /** The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. */ + "smsApplicationSid"?: string; + /** The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "smsFallbackMethod"?: string; + /** The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. */ + "smsFallbackUrl"?: string; + /** The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "smsMethod"?: string; + /** The URL we should call when the new phone number receives an incoming SMS message. */ + "smsUrl"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "statusCallbackMethod"?: string; + /** The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. */ + "voiceApplicationSid"?: string; + /** Whether to lookup the caller\\\'s name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. */ + "voiceCallerIdLookup"?: boolean; + /** The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "voiceMethod"?: string; + /** The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. */ + "voiceUrl"?: string; + /** */ + "emergencyStatus"?: IncomingPhoneNumberEmergencyStatus; + /** The SID of the emergency address configuration to use for emergency calling from the new phone number. */ + "emergencyAddressSid"?: string; + /** The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. */ + "trunkSid"?: string; + /** The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. */ + "identitySid"?: string; + /** The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. */ + "addressSid"?: string; + /** */ + "voiceReceiveMode"?: IncomingPhoneNumberVoiceReceiveMode; + /** The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. */ + "bundleSid"?: string; + /** The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. */ + "phoneNumber"?: string; + /** The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). */ + "areaCode"?: string; +} + +/** + * Options to pass to each + */ +export interface IncomingPhoneNumberListInstanceEachOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the IncomingPhoneNumber resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: IncomingPhoneNumberInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface IncomingPhoneNumberListInstanceOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the IncomingPhoneNumber resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface IncomingPhoneNumberListInstancePageOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the IncomingPhoneNumber resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface IncomingPhoneNumberContext { + assignedAddOns: AssignedAddOnListInstance; + + /** + * Remove a IncomingPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a IncomingPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a IncomingPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise + + /** + * Fetch a IncomingPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a IncomingPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance + */ + update(callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise; + /** + * Update a IncomingPhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance + */ + update(params: IncomingPhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise; + + /** + * Update a IncomingPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a IncomingPhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(params: IncomingPhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface IncomingPhoneNumberContextSolution { + "accountSid": string; + "sid": string; +} + +export class IncomingPhoneNumberContextImpl implements IncomingPhoneNumberContext { + protected _solution: IncomingPhoneNumberContextSolution; + protected _uri: string; + + protected _assignedAddOns?: AssignedAddOnListInstance; + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/IncomingPhoneNumbers/${sid}.json`; + } + + get assignedAddOns(): AssignedAddOnListInstance { + this._assignedAddOns = this._assignedAddOns || AssignedAddOnListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._assignedAddOns; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new IncomingPhoneNumberInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new IncomingPhoneNumberInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: IncomingPhoneNumberContextUpdateOptions | ((error: Error | null, item?: IncomingPhoneNumberInstance) => any),callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceApplicationSid"] !== undefined) + data["VoiceApplicationSid"] = params["voiceApplicationSid"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["emergencyStatus"] !== undefined) + data["EmergencyStatus"] = params["emergencyStatus"]; + if (params["emergencyAddressSid"] !== undefined) + data["EmergencyAddressSid"] = params["emergencyAddressSid"]; + if (params["trunkSid"] !== undefined) + data["TrunkSid"] = params["trunkSid"]; + if (params["voiceReceiveMode"] !== undefined) + data["VoiceReceiveMode"] = params["voiceReceiveMode"]; + if (params["identitySid"] !== undefined) + data["IdentitySid"] = params["identitySid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["bundleSid"] !== undefined) + data["BundleSid"] = params["bundleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IncomingPhoneNumberInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: IncomingPhoneNumberContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceApplicationSid"] !== undefined) + data["VoiceApplicationSid"] = params["voiceApplicationSid"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["emergencyStatus"] !== undefined) + data["EmergencyStatus"] = params["emergencyStatus"]; + if (params["emergencyAddressSid"] !== undefined) + data["EmergencyAddressSid"] = params["emergencyAddressSid"]; + if (params["trunkSid"] !== undefined) + data["TrunkSid"] = params["trunkSid"]; + if (params["voiceReceiveMode"] !== undefined) + data["VoiceReceiveMode"] = params["voiceReceiveMode"]; + if (params["identitySid"] !== undefined) + data["IdentitySid"] = params["identitySid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["bundleSid"] !== undefined) + data["BundleSid"] = params["bundleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new IncomingPhoneNumberInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface IncomingPhoneNumberPayload extends TwilioResponsePayload { + incoming_phone_numbers: IncomingPhoneNumberResource[]; +} + +interface IncomingPhoneNumberResource { + account_sid: string; + address_sid: string; + address_requirements: IncomingPhoneNumberAddressRequirement; + api_version: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; + date_created: Date; + date_updated: Date; + friendly_name: string; + identity_sid: string; + phone_number: string; + origin: string; + sid: string; + sms_application_sid: string; + sms_fallback_method: string; + sms_fallback_url: string; + sms_method: string; + sms_url: string; + status_callback: string; + status_callback_method: string; + trunk_sid: string; + uri: string; + voice_receive_mode: IncomingPhoneNumberVoiceReceiveMode; + voice_application_sid: string; + voice_caller_id_lookup: boolean; + voice_fallback_method: string; + voice_fallback_url: string; + voice_method: string; + voice_url: string; + emergency_status: IncomingPhoneNumberEmergencyStatus; + emergency_address_sid: string; + emergency_address_status: IncomingPhoneNumberEmergencyAddressStatus; + bundle_sid: string; + status: string; + type: string; +} + +export class IncomingPhoneNumberInstance { + protected _solution: IncomingPhoneNumberContextSolution; + protected _context?: IncomingPhoneNumberContext; + + constructor(protected _version: V2010, payload: IncomingPhoneNumberResource, accountSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.addressSid = (payload.address_sid); + this.addressRequirements = payload.address_requirements; + this.apiVersion = (payload.api_version); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.identitySid = (payload.identity_sid); + this.phoneNumber = (payload.phone_number); + this.origin = (payload.origin); + this.sid = (payload.sid); + this.smsApplicationSid = (payload.sms_application_sid); + this.smsFallbackMethod = (payload.sms_fallback_method); + this.smsFallbackUrl = (payload.sms_fallback_url); + this.smsMethod = (payload.sms_method); + this.smsUrl = (payload.sms_url); + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.trunkSid = (payload.trunk_sid); + this.uri = (payload.uri); + this.voiceReceiveMode = payload.voice_receive_mode; + this.voiceApplicationSid = (payload.voice_application_sid); + this.voiceCallerIdLookup = (payload.voice_caller_id_lookup); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceMethod = (payload.voice_method); + this.voiceUrl = (payload.voice_url); + this.emergencyStatus = payload.emergency_status; + this.emergencyAddressSid = (payload.emergency_address_sid); + this.emergencyAddressStatus = payload.emergency_address_status; + this.bundleSid = (payload.bundle_sid); + this.status = (payload.status); + this.type = (payload.type); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this IncomingPhoneNumber resource. + */ + accountSid: string; + /** + * The SID of the Address resource associated with the phone number. + */ + addressSid: string; + addressRequirements: IncomingPhoneNumberAddressRequirement; + /** + * The API version used to start a new TwiML session. + */ + apiVersion: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + */ + identitySid: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The phone number\'s origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + */ + origin: string; + /** + * The unique string that that we created to identify this IncomingPhoneNumber resource. + */ + sid: string; + /** + * The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + */ + smsApplicationSid: string; + /** + * The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + */ + smsFallbackMethod: string; + /** + * The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + */ + smsFallbackUrl: string; + /** + * The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + */ + smsMethod: string; + /** + * The URL we call when the phone number receives an incoming SMS message. + */ + smsUrl: string; + /** + * The URL we call using the `status_callback_method` to send status information to your application. + */ + statusCallback: string; + /** + * The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + */ + statusCallbackMethod: string; + /** + * The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + */ + trunkSid: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + voiceReceiveMode: IncomingPhoneNumberVoiceReceiveMode; + /** + * The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + */ + voiceApplicationSid: string; + /** + * Whether we look up the caller\'s caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + */ + voiceCallerIdLookup: boolean; + /** + * The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + */ + voiceFallbackMethod: string; + /** + * The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + */ + voiceFallbackUrl: string; + /** + * The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + */ + voiceMethod: string; + /** + * The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + */ + voiceUrl: string; + emergencyStatus: IncomingPhoneNumberEmergencyStatus; + /** + * The SID of the emergency address configuration that we use for emergency calling from this phone number. + */ + emergencyAddressSid: string; + emergencyAddressStatus: IncomingPhoneNumberEmergencyAddressStatus; + /** + * The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + */ + bundleSid: string; + status: string; + /** + * The phone number type. + */ + type: string; + + private get _proxy(): IncomingPhoneNumberContext { + this._context = this._context || new IncomingPhoneNumberContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a IncomingPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a IncomingPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a IncomingPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a IncomingPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a IncomingPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance + */ + update(callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise; + /** + * Update a IncomingPhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance + */ + update(params: IncomingPhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a IncomingPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a IncomingPhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(params: IncomingPhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the assignedAddOns. + */ + assignedAddOns(): AssignedAddOnListInstance { + return this._proxy.assignedAddOns; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + addressSid: this.addressSid, + addressRequirements: this.addressRequirements, + apiVersion: this.apiVersion, + beta: this.beta, + capabilities: this.capabilities, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + identitySid: this.identitySid, + phoneNumber: this.phoneNumber, + origin: this.origin, + sid: this.sid, + smsApplicationSid: this.smsApplicationSid, + smsFallbackMethod: this.smsFallbackMethod, + smsFallbackUrl: this.smsFallbackUrl, + smsMethod: this.smsMethod, + smsUrl: this.smsUrl, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + trunkSid: this.trunkSid, + uri: this.uri, + voiceReceiveMode: this.voiceReceiveMode, + voiceApplicationSid: this.voiceApplicationSid, + voiceCallerIdLookup: this.voiceCallerIdLookup, + voiceFallbackMethod: this.voiceFallbackMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceMethod: this.voiceMethod, + voiceUrl: this.voiceUrl, + emergencyStatus: this.emergencyStatus, + emergencyAddressSid: this.emergencyAddressSid, + emergencyAddressStatus: this.emergencyAddressStatus, + bundleSid: this.bundleSid, + status: this.status, + type: this.type, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface IncomingPhoneNumberSolution { + accountSid: string; +} + +export interface IncomingPhoneNumberListInstance { + _version: V2010; + _solution: IncomingPhoneNumberSolution; + _uri: string; + + (sid: string, ): IncomingPhoneNumberContext; + get(sid: string, ): IncomingPhoneNumberContext; + + _local?: LocalListInstance; + local: LocalListInstance; + _mobile?: MobileListInstance; + mobile: MobileListInstance; + _tollFree?: TollFreeListInstance; + tollFree: TollFreeListInstance; + + + + + + + + /** + * Create a IncomingPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance + */ + create(callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise; + /** + * Create a IncomingPhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance + */ + create(params: IncomingPhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, item?: IncomingPhoneNumberInstance) => any): Promise; + + /** + * Create a IncomingPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a IncomingPhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IncomingPhoneNumberInstance with HTTP metadata + */ + createWithHttpInfo(params: IncomingPhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams IncomingPhoneNumberInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IncomingPhoneNumberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: IncomingPhoneNumberInstance, done: (err?: Error) => void) => void): void; + each(params: IncomingPhoneNumberListInstanceEachOptions, callback?: (item: IncomingPhoneNumberInstance, done: (err?: Error) => void) => void): void; + /** + * Streams IncomingPhoneNumberInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IncomingPhoneNumberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: IncomingPhoneNumberInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: IncomingPhoneNumberListInstanceEachOptions, callback?: (item: IncomingPhoneNumberInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of IncomingPhoneNumberInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: IncomingPhoneNumberPage) => any): Promise; + /** + * Retrieve a single target page of IncomingPhoneNumberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists IncomingPhoneNumberInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IncomingPhoneNumberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: IncomingPhoneNumberInstance[]) => any): Promise; + list(params: IncomingPhoneNumberListInstanceOptions, callback?: (error: Error | null, items: IncomingPhoneNumberInstance[]) => any): Promise; + /** + * Lists IncomingPhoneNumberInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IncomingPhoneNumberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: IncomingPhoneNumberListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of IncomingPhoneNumberInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IncomingPhoneNumberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: IncomingPhoneNumberPage) => any): Promise; + page(params: IncomingPhoneNumberListInstancePageOptions, callback?: (error: Error | null, items: IncomingPhoneNumberPage) => any): Promise; + /** + * Retrieve a single page of IncomingPhoneNumberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IncomingPhoneNumberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: IncomingPhoneNumberListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function IncomingPhoneNumberListInstance(version: V2010, accountSid: string): IncomingPhoneNumberListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as IncomingPhoneNumberListInstance; + + instance.get = function get(sid, ): IncomingPhoneNumberContext { + return new IncomingPhoneNumberContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/IncomingPhoneNumbers.json`; + + Object.defineProperty(instance, "local", { + get: function local() { + if (!instance._local) { + instance._local = LocalListInstance(instance._version, instance._solution.accountSid); + } + return instance._local; + } + }); + + Object.defineProperty(instance, "mobile", { + get: function mobile() { + if (!instance._mobile) { + instance._mobile = MobileListInstance(instance._version, instance._solution.accountSid); + } + return instance._mobile; + } + }); + + Object.defineProperty(instance, "tollFree", { + get: function tollFree() { + if (!instance._tollFree) { + instance._tollFree = TollFreeListInstance(instance._version, instance._solution.accountSid); + } + return instance._tollFree; + } + }); + + instance.create = function create(params?: IncomingPhoneNumberListInstanceCreateOptions | ((error: Error | null, items: IncomingPhoneNumberInstance) => any), callback?: (error: Error | null, items: IncomingPhoneNumberInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceApplicationSid"] !== undefined) + data["VoiceApplicationSid"] = params["voiceApplicationSid"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["emergencyStatus"] !== undefined) + data["EmergencyStatus"] = params["emergencyStatus"]; + if (params["emergencyAddressSid"] !== undefined) + data["EmergencyAddressSid"] = params["emergencyAddressSid"]; + if (params["trunkSid"] !== undefined) + data["TrunkSid"] = params["trunkSid"]; + if (params["identitySid"] !== undefined) + data["IdentitySid"] = params["identitySid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["voiceReceiveMode"] !== undefined) + data["VoiceReceiveMode"] = params["voiceReceiveMode"]; + if (params["bundleSid"] !== undefined) + data["BundleSid"] = params["bundleSid"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IncomingPhoneNumberInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: IncomingPhoneNumberListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceApplicationSid"] !== undefined) + data["VoiceApplicationSid"] = params["voiceApplicationSid"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["emergencyStatus"] !== undefined) + data["EmergencyStatus"] = params["emergencyStatus"]; + if (params["emergencyAddressSid"] !== undefined) + data["EmergencyAddressSid"] = params["emergencyAddressSid"]; + if (params["trunkSid"] !== undefined) + data["TrunkSid"] = params["trunkSid"]; + if (params["identitySid"] !== undefined) + data["IdentitySid"] = params["identitySid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["voiceReceiveMode"] !== undefined) + data["VoiceReceiveMode"] = params["voiceReceiveMode"]; + if (params["bundleSid"] !== undefined) + data["BundleSid"] = params["bundleSid"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["areaCode"] !== undefined) + data["AreaCode"] = params["areaCode"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new IncomingPhoneNumberInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: IncomingPhoneNumberListInstancePageOptions | ((error: Error | null, items: IncomingPhoneNumberPage) => any), callback?: (error: Error | null, items: IncomingPhoneNumberPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["origin"] !== undefined) + data["Origin"] = params["origin"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new IncomingPhoneNumberPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: IncomingPhoneNumberPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new IncomingPhoneNumberPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: IncomingPhoneNumberListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["origin"] !== undefined) + data["Origin"] = params["origin"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IncomingPhoneNumberPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IncomingPhoneNumberPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class IncomingPhoneNumberPage extends Page { +/** +* Initialize the IncomingPhoneNumberPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: IncomingPhoneNumberSolution) { + super(version, response, solution); + } + + /** + * Build an instance of IncomingPhoneNumberInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: IncomingPhoneNumberResource): IncomingPhoneNumberInstance { + + return new IncomingPhoneNumberInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/incomingPhoneNumber/assignedAddOn.ts b/rest/api/v2010/account/incomingPhoneNumber/assignedAddOn.ts new file mode 100644 index 000000000..0a190ecb2 --- /dev/null +++ b/rest/api/v2010/account/incomingPhoneNumber/assignedAddOn.ts @@ -0,0 +1,800 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { AssignedAddOnExtensionListInstance } from "./assignedAddOn/assignedAddOnExtension"; + + + + + +/** + * Options to pass to create a AssignedAddOnInstance + */ +export interface AssignedAddOnListInstanceCreateOptions { + /** The SID that identifies the Add-on installation. */ + "installedAddOnSid": string; +} + +/** + * Options to pass to each + */ +export interface AssignedAddOnListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AssignedAddOnInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AssignedAddOnListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AssignedAddOnListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AssignedAddOnContext { + extensions: AssignedAddOnExtensionListInstance; + + /** + * Remove a AssignedAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AssignedAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a AssignedAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssignedAddOnInstance + */ + fetch(callback?: (error: Error | null, item?: AssignedAddOnInstance) => any): Promise + + /** + * Fetch a AssignedAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssignedAddOnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AssignedAddOnContextSolution { + "accountSid": string; + "resourceSid": string; + "sid": string; +} + +export class AssignedAddOnContextImpl implements AssignedAddOnContext { + protected _solution: AssignedAddOnContextSolution; + protected _uri: string; + + protected _extensions?: AssignedAddOnExtensionListInstance; + + constructor(protected _version: V2010, accountSid: string, resourceSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(resourceSid)) { + throw new Error('Parameter \'resourceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, resourceSid, sid, }; + this._uri = `/Accounts/${accountSid}/IncomingPhoneNumbers/${resourceSid}/AssignedAddOns/${sid}.json`; + } + + get extensions(): AssignedAddOnExtensionListInstance { + this._extensions = this._extensions || AssignedAddOnExtensionListInstance(this._version, this._solution.accountSid, this._solution.resourceSid, this._solution.sid); + return this._extensions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AssignedAddOnInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AssignedAddOnInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.resourceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AssignedAddOnInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.resourceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AssignedAddOnPayload extends TwilioResponsePayload { + assigned_add_ons: AssignedAddOnResource[]; +} + +interface AssignedAddOnResource { + sid: string; + account_sid: string; + resource_sid: string; + friendly_name: string; + description: string; + configuration: any; + unique_name: string; + date_created: Date; + date_updated: Date; + uri: string; + subresource_uris: Record; +} + +export class AssignedAddOnInstance { + protected _solution: AssignedAddOnContextSolution; + protected _context?: AssignedAddOnContext; + + constructor(protected _version: V2010, payload: AssignedAddOnResource, accountSid: string, resourceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.resourceSid = (payload.resource_sid); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.configuration = (payload.configuration); + this.uniqueName = (payload.unique_name); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.uri = (payload.uri); + this.subresourceUris = (payload.subresource_uris); + + this._solution = { accountSid, resourceSid, sid: sid, }; + } + + /** + * The unique string that that we created to identify the resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + */ + accountSid: string; + /** + * The SID of the Phone Number to which the Add-on is assigned. + */ + resourceSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * A short description of the functionality that the Add-on provides. + */ + description: string; + /** + * A JSON string that represents the current configuration of this Add-on installation. + */ + configuration: any; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. + */ + uniqueName: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * A list of related resources identified by their relative URIs. + */ + subresourceUris: Record; + + private get _proxy(): AssignedAddOnContext { + this._context = this._context || new AssignedAddOnContextImpl(this._version, this._solution.accountSid, this._solution.resourceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a AssignedAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AssignedAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AssignedAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssignedAddOnInstance + */ + fetch(callback?: (error: Error | null, item?: AssignedAddOnInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AssignedAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssignedAddOnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the extensions. + */ + extensions(): AssignedAddOnExtensionListInstance { + return this._proxy.extensions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + resourceSid: this.resourceSid, + friendlyName: this.friendlyName, + description: this.description, + configuration: this.configuration, + uniqueName: this.uniqueName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + uri: this.uri, + subresourceUris: this.subresourceUris, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AssignedAddOnSolution { + accountSid: string; + resourceSid: string; +} + +export interface AssignedAddOnListInstance { + _version: V2010; + _solution: AssignedAddOnSolution; + _uri: string; + + (sid: string, ): AssignedAddOnContext; + get(sid: string, ): AssignedAddOnContext; + + + + + + + /** + * Create a AssignedAddOnInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssignedAddOnInstance + */ + create(params: AssignedAddOnListInstanceCreateOptions, callback?: (error: Error | null, item?: AssignedAddOnInstance) => any): Promise; + + /** + * Create a AssignedAddOnInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssignedAddOnInstance with HTTP metadata + */ + createWithHttpInfo(params: AssignedAddOnListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams AssignedAddOnInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AssignedAddOnInstance, done: (err?: Error) => void) => void): void; + each(params: AssignedAddOnListInstanceEachOptions, callback?: (item: AssignedAddOnInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AssignedAddOnInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AssignedAddOnInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AssignedAddOnListInstanceEachOptions, callback?: (item: AssignedAddOnInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AssignedAddOnInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AssignedAddOnPage) => any): Promise; + /** + * Retrieve a single target page of AssignedAddOnInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AssignedAddOnInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AssignedAddOnInstance[]) => any): Promise; + list(params: AssignedAddOnListInstanceOptions, callback?: (error: Error | null, items: AssignedAddOnInstance[]) => any): Promise; + /** + * Lists AssignedAddOnInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AssignedAddOnListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AssignedAddOnInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AssignedAddOnPage) => any): Promise; + page(params: AssignedAddOnListInstancePageOptions, callback?: (error: Error | null, items: AssignedAddOnPage) => any): Promise; + /** + * Retrieve a single page of AssignedAddOnInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AssignedAddOnListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AssignedAddOnListInstance(version: V2010, accountSid: string, resourceSid: string): AssignedAddOnListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(resourceSid)) { + throw new Error('Parameter \'resourceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as AssignedAddOnListInstance; + + instance.get = function get(sid, ): AssignedAddOnContext { + return new AssignedAddOnContextImpl(version, accountSid, resourceSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, resourceSid, }; + instance._uri = `/Accounts/${accountSid}/IncomingPhoneNumbers/${resourceSid}/AssignedAddOns.json`; + + instance.create = function create(params: AssignedAddOnListInstanceCreateOptions, callback?: (error: Error | null, items: AssignedAddOnInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["installedAddOnSid"] === null || params["installedAddOnSid"] === undefined) { + throw new Error('Required parameter "params[\'installedAddOnSid\']" missing.'); + } + + let data: any = {}; + + + + data["InstalledAddOnSid"] = params["installedAddOnSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AssignedAddOnInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.resourceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AssignedAddOnListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["installedAddOnSid"] === null || params["installedAddOnSid"] === undefined) { + throw new Error('Required parameter "params[\'installedAddOnSid\']" missing.'); + } + + let data: any = {}; + + + + data["InstalledAddOnSid"] = params["installedAddOnSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AssignedAddOnInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.resourceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AssignedAddOnListInstancePageOptions | ((error: Error | null, items: AssignedAddOnPage) => any), callback?: (error: Error | null, items: AssignedAddOnPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AssignedAddOnPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AssignedAddOnPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AssignedAddOnPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AssignedAddOnListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssignedAddOnPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssignedAddOnPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AssignedAddOnPage extends Page { +/** +* Initialize the AssignedAddOnPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AssignedAddOnSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AssignedAddOnInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AssignedAddOnResource): AssignedAddOnInstance { + + return new AssignedAddOnInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.resourceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/incomingPhoneNumber/assignedAddOn/assignedAddOnExtension.ts b/rest/api/v2010/account/incomingPhoneNumber/assignedAddOn/assignedAddOnExtension.ts new file mode 100644 index 000000000..4af8cb0a3 --- /dev/null +++ b/rest/api/v2010/account/incomingPhoneNumber/assignedAddOn/assignedAddOnExtension.ts @@ -0,0 +1,605 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../../base/Page"; +import Response from "../../../../../../http/response"; +import V2010 from "../../../../V2010"; +const deserialize = require("../../../../../../base/deserialize"); +const serialize = require("../../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../../base/utility"; +import { ApiResponse } from "../../../../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface AssignedAddOnExtensionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AssignedAddOnExtensionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AssignedAddOnExtensionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AssignedAddOnExtensionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AssignedAddOnExtensionContext { + + /** + * Fetch a AssignedAddOnExtensionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssignedAddOnExtensionInstance + */ + fetch(callback?: (error: Error | null, item?: AssignedAddOnExtensionInstance) => any): Promise + + /** + * Fetch a AssignedAddOnExtensionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssignedAddOnExtensionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AssignedAddOnExtensionContextSolution { + "accountSid": string; + "resourceSid": string; + "assignedAddOnSid": string; + "sid": string; +} + +export class AssignedAddOnExtensionContextImpl implements AssignedAddOnExtensionContext { + protected _solution: AssignedAddOnExtensionContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, resourceSid: string, assignedAddOnSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(resourceSid)) { + throw new Error('Parameter \'resourceSid\' is not valid.'); + } + + if (!isValidPathParam(assignedAddOnSid)) { + throw new Error('Parameter \'assignedAddOnSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, resourceSid, assignedAddOnSid, sid, }; + this._uri = `/Accounts/${accountSid}/IncomingPhoneNumbers/${resourceSid}/AssignedAddOns/${assignedAddOnSid}/Extensions/${sid}.json`; + } + + fetch(callback?: (error: Error | null, item?: AssignedAddOnExtensionInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AssignedAddOnExtensionInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.resourceSid, instance._solution.assignedAddOnSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AssignedAddOnExtensionInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.resourceSid, instance._solution.assignedAddOnSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AssignedAddOnExtensionPayload extends TwilioResponsePayload { + extensions: AssignedAddOnExtensionResource[]; +} + +interface AssignedAddOnExtensionResource { + sid: string; + account_sid: string; + resource_sid: string; + assigned_add_on_sid: string; + friendly_name: string; + product_name: string; + unique_name: string; + uri: string; + enabled: boolean; +} + +export class AssignedAddOnExtensionInstance { + protected _solution: AssignedAddOnExtensionContextSolution; + protected _context?: AssignedAddOnExtensionContext; + + constructor(protected _version: V2010, payload: AssignedAddOnExtensionResource, accountSid: string, resourceSid: string, assignedAddOnSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.resourceSid = (payload.resource_sid); + this.assignedAddOnSid = (payload.assigned_add_on_sid); + this.friendlyName = (payload.friendly_name); + this.productName = (payload.product_name); + this.uniqueName = (payload.unique_name); + this.uri = (payload.uri); + this.enabled = (payload.enabled); + + this._solution = { accountSid, resourceSid, assignedAddOnSid, sid: sid, }; + } + + /** + * The unique string that that we created to identify the resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + */ + accountSid: string; + /** + * The SID of the Phone Number to which the Add-on is assigned. + */ + resourceSid: string; + /** + * The SID that uniquely identifies the assigned Add-on installation. + */ + assignedAddOnSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * A string that you assigned to describe the Product this Extension is used within. + */ + productName: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. + */ + uniqueName: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * Whether the Extension will be invoked. + */ + enabled: boolean; + + private get _proxy(): AssignedAddOnExtensionContext { + this._context = this._context || new AssignedAddOnExtensionContextImpl(this._version, this._solution.accountSid, this._solution.resourceSid, this._solution.assignedAddOnSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a AssignedAddOnExtensionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssignedAddOnExtensionInstance + */ + fetch(callback?: (error: Error | null, item?: AssignedAddOnExtensionInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AssignedAddOnExtensionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssignedAddOnExtensionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + resourceSid: this.resourceSid, + assignedAddOnSid: this.assignedAddOnSid, + friendlyName: this.friendlyName, + productName: this.productName, + uniqueName: this.uniqueName, + uri: this.uri, + enabled: this.enabled, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AssignedAddOnExtensionSolution { + accountSid: string; + resourceSid: string; + assignedAddOnSid: string; +} + +export interface AssignedAddOnExtensionListInstance { + _version: V2010; + _solution: AssignedAddOnExtensionSolution; + _uri: string; + + (sid: string, ): AssignedAddOnExtensionContext; + get(sid: string, ): AssignedAddOnExtensionContext; + + + + + + /** + * Streams AssignedAddOnExtensionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnExtensionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AssignedAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + each(params: AssignedAddOnExtensionListInstanceEachOptions, callback?: (item: AssignedAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AssignedAddOnExtensionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnExtensionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AssignedAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AssignedAddOnExtensionListInstanceEachOptions, callback?: (item: AssignedAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AssignedAddOnExtensionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AssignedAddOnExtensionPage) => any): Promise; + /** + * Retrieve a single target page of AssignedAddOnExtensionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AssignedAddOnExtensionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnExtensionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AssignedAddOnExtensionInstance[]) => any): Promise; + list(params: AssignedAddOnExtensionListInstanceOptions, callback?: (error: Error | null, items: AssignedAddOnExtensionInstance[]) => any): Promise; + /** + * Lists AssignedAddOnExtensionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnExtensionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AssignedAddOnExtensionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AssignedAddOnExtensionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnExtensionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AssignedAddOnExtensionPage) => any): Promise; + page(params: AssignedAddOnExtensionListInstancePageOptions, callback?: (error: Error | null, items: AssignedAddOnExtensionPage) => any): Promise; + /** + * Retrieve a single page of AssignedAddOnExtensionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssignedAddOnExtensionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AssignedAddOnExtensionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AssignedAddOnExtensionListInstance(version: V2010, accountSid: string, resourceSid: string, assignedAddOnSid: string): AssignedAddOnExtensionListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(resourceSid)) { + throw new Error('Parameter \'resourceSid\' is not valid.'); + } + + if (!isValidPathParam(assignedAddOnSid)) { + throw new Error('Parameter \'assignedAddOnSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as AssignedAddOnExtensionListInstance; + + instance.get = function get(sid, ): AssignedAddOnExtensionContext { + return new AssignedAddOnExtensionContextImpl(version, accountSid, resourceSid, assignedAddOnSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, resourceSid, assignedAddOnSid, }; + instance._uri = `/Accounts/${accountSid}/IncomingPhoneNumbers/${resourceSid}/AssignedAddOns/${assignedAddOnSid}/Extensions.json`; + + instance.page = function page(params?: AssignedAddOnExtensionListInstancePageOptions | ((error: Error | null, items: AssignedAddOnExtensionPage) => any), callback?: (error: Error | null, items: AssignedAddOnExtensionPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AssignedAddOnExtensionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AssignedAddOnExtensionPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AssignedAddOnExtensionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AssignedAddOnExtensionListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssignedAddOnExtensionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssignedAddOnExtensionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AssignedAddOnExtensionPage extends Page { +/** +* Initialize the AssignedAddOnExtensionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AssignedAddOnExtensionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AssignedAddOnExtensionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AssignedAddOnExtensionResource): AssignedAddOnExtensionInstance { + + return new AssignedAddOnExtensionInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.resourceSid, + this._solution.assignedAddOnSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/incomingPhoneNumber/local.ts b/rest/api/v2010/account/incomingPhoneNumber/local.ts new file mode 100644 index 000000000..19c05b898 --- /dev/null +++ b/rest/api/v2010/account/incomingPhoneNumber/local.ts @@ -0,0 +1,886 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../../interfaces"; + + +/** + * Whether the phone number requires an [Address](https://www.twilio.com/docs/usage/api/address) registered with Twilio. Can be: `none`, `any`, `local`, or `foreign`. + */ +export type LocalAddressRequirement = 'none'|'any'|'local'|'foreign'; + +/** + * The status of address registration with emergency services. A registered emergency address will be used during handling of emergency calls from this number. + */ +export type LocalEmergencyAddressStatus = 'registered'|'unregistered'|'pending-registration'|'registration-failure'|'pending-unregistration'|'unregistration-failure'; + +/** + * The parameter displays if emergency calling is enabled for this number. Active numbers may place emergency calls by dialing valid emergency numbers for the country. + */ +export type LocalEmergencyStatus = 'Active'|'Inactive'; + +export type LocalVoiceReceiveMode = 'voice'|'fax'; + + +/** + * Options to pass to create a LocalInstance + */ +export interface LocalListInstanceCreateOptions { + /** The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. */ + "phoneNumber": string; + /** The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. */ + "apiVersion"?: string; + /** A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. */ + "friendlyName"?: string; + /** The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. */ + "smsApplicationSid"?: string; + /** The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "smsFallbackMethod"?: string; + /** The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. */ + "smsFallbackUrl"?: string; + /** The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "smsMethod"?: string; + /** The URL we should call when the new phone number receives an incoming SMS message. */ + "smsUrl"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "statusCallbackMethod"?: string; + /** The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. */ + "voiceApplicationSid"?: string; + /** Whether to lookup the caller\\\'s name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. */ + "voiceCallerIdLookup"?: boolean; + /** The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "voiceMethod"?: string; + /** The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. */ + "voiceUrl"?: string; + /** The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. */ + "identitySid"?: string; + /** The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. */ + "addressSid"?: string; + /** */ + "emergencyStatus"?: LocalEmergencyStatus; + /** The SID of the emergency address configuration to use for emergency calling from the new phone number. */ + "emergencyAddressSid"?: string; + /** The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. */ + "trunkSid"?: string; + /** */ + "voiceReceiveMode"?: LocalVoiceReceiveMode; + /** The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. */ + "bundleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface LocalListInstanceEachOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: LocalInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface LocalListInstanceOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface LocalListInstancePageOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface LocalSolution { + accountSid: string; +} + +export interface LocalListInstance { + _version: V2010; + _solution: LocalSolution; + _uri: string; + + + + /** + * Create a LocalInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LocalInstance + */ + create(params: LocalListInstanceCreateOptions, callback?: (error: Error | null, item?: LocalInstance) => any): Promise; + + /** + * Create a LocalInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LocalInstance with HTTP metadata + */ + createWithHttpInfo(params: LocalListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams LocalInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: LocalInstance, done: (err?: Error) => void) => void): void; + each(params: LocalListInstanceEachOptions, callback?: (item: LocalInstance, done: (err?: Error) => void) => void): void; + /** + * Streams LocalInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: LocalInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: LocalListInstanceEachOptions, callback?: (item: LocalInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of LocalInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: LocalPage) => any): Promise; + /** + * Retrieve a single target page of LocalInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists LocalInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: LocalInstance[]) => any): Promise; + list(params: LocalListInstanceOptions, callback?: (error: Error | null, items: LocalInstance[]) => any): Promise; + /** + * Lists LocalInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: LocalListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of LocalInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: LocalPage) => any): Promise; + page(params: LocalListInstancePageOptions, callback?: (error: Error | null, items: LocalPage) => any): Promise; + /** + * Retrieve a single page of LocalInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LocalListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: LocalListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function LocalListInstance(version: V2010, accountSid: string): LocalListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as LocalListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/IncomingPhoneNumbers/Local.json`; + + instance.create = function create(params: LocalListInstanceCreateOptions, callback?: (error: Error | null, items: LocalInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceApplicationSid"] !== undefined) + data["VoiceApplicationSid"] = params["voiceApplicationSid"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["identitySid"] !== undefined) + data["IdentitySid"] = params["identitySid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["emergencyStatus"] !== undefined) + data["EmergencyStatus"] = params["emergencyStatus"]; + if (params["emergencyAddressSid"] !== undefined) + data["EmergencyAddressSid"] = params["emergencyAddressSid"]; + if (params["trunkSid"] !== undefined) + data["TrunkSid"] = params["trunkSid"]; + if (params["voiceReceiveMode"] !== undefined) + data["VoiceReceiveMode"] = params["voiceReceiveMode"]; + if (params["bundleSid"] !== undefined) + data["BundleSid"] = params["bundleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new LocalInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: LocalListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceApplicationSid"] !== undefined) + data["VoiceApplicationSid"] = params["voiceApplicationSid"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["identitySid"] !== undefined) + data["IdentitySid"] = params["identitySid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["emergencyStatus"] !== undefined) + data["EmergencyStatus"] = params["emergencyStatus"]; + if (params["emergencyAddressSid"] !== undefined) + data["EmergencyAddressSid"] = params["emergencyAddressSid"]; + if (params["trunkSid"] !== undefined) + data["TrunkSid"] = params["trunkSid"]; + if (params["voiceReceiveMode"] !== undefined) + data["VoiceReceiveMode"] = params["voiceReceiveMode"]; + if (params["bundleSid"] !== undefined) + data["BundleSid"] = params["bundleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new LocalInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: LocalListInstancePageOptions | ((error: Error | null, items: LocalPage) => any), callback?: (error: Error | null, items: LocalPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["origin"] !== undefined) + data["Origin"] = params["origin"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new LocalPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: LocalPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new LocalPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: LocalListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["origin"] !== undefined) + data["Origin"] = params["origin"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new LocalPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new LocalPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface LocalPayload extends TwilioResponsePayload { + incoming_phone_numbers: LocalResource[]; +} + +interface LocalResource { + account_sid: string; + address_sid: string; + address_requirements: LocalAddressRequirement; + api_version: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; + date_created: Date; + date_updated: Date; + friendly_name: string; + identity_sid: string; + phone_number: string; + origin: string; + sid: string; + sms_application_sid: string; + sms_fallback_method: string; + sms_fallback_url: string; + sms_method: string; + sms_url: string; + status_callback: string; + status_callback_method: string; + trunk_sid: string; + uri: string; + voice_receive_mode: LocalVoiceReceiveMode; + voice_application_sid: string; + voice_caller_id_lookup: boolean; + voice_fallback_method: string; + voice_fallback_url: string; + voice_method: string; + voice_url: string; + emergency_status: LocalEmergencyStatus; + emergency_address_sid: string; + emergency_address_status: LocalEmergencyAddressStatus; + bundle_sid: string; + status: string; +} + +export class LocalInstance { + + constructor(protected _version: V2010, payload: LocalResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.addressSid = (payload.address_sid); + this.addressRequirements = payload.address_requirements; + this.apiVersion = (payload.api_version); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.identitySid = (payload.identity_sid); + this.phoneNumber = (payload.phone_number); + this.origin = (payload.origin); + this.sid = (payload.sid); + this.smsApplicationSid = (payload.sms_application_sid); + this.smsFallbackMethod = (payload.sms_fallback_method); + this.smsFallbackUrl = (payload.sms_fallback_url); + this.smsMethod = (payload.sms_method); + this.smsUrl = (payload.sms_url); + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.trunkSid = (payload.trunk_sid); + this.uri = (payload.uri); + this.voiceReceiveMode = payload.voice_receive_mode; + this.voiceApplicationSid = (payload.voice_application_sid); + this.voiceCallerIdLookup = (payload.voice_caller_id_lookup); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceMethod = (payload.voice_method); + this.voiceUrl = (payload.voice_url); + this.emergencyStatus = payload.emergency_status; + this.emergencyAddressSid = (payload.emergency_address_sid); + this.emergencyAddressStatus = payload.emergency_address_status; + this.bundleSid = (payload.bundle_sid); + this.status = (payload.status); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + */ + accountSid: string; + /** + * The SID of the Address resource associated with the phone number. + */ + addressSid: string; + addressRequirements: LocalAddressRequirement; + /** + * The API version used to start a new TwiML session. + */ + apiVersion: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + */ + identitySid: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The phone number\'s origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + */ + origin: string; + /** + * The unique string that that we created to identify the resource. + */ + sid: string; + /** + * The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + */ + smsApplicationSid: string; + /** + * The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + */ + smsFallbackMethod: string; + /** + * The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + */ + smsFallbackUrl: string; + /** + * The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + */ + smsMethod: string; + /** + * The URL we call when the phone number receives an incoming SMS message. + */ + smsUrl: string; + /** + * The URL we call using the `status_callback_method` to send status information to your application. + */ + statusCallback: string; + /** + * The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + */ + statusCallbackMethod: string; + /** + * The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + */ + trunkSid: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + voiceReceiveMode: LocalVoiceReceiveMode; + /** + * The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + */ + voiceApplicationSid: string; + /** + * Whether we look up the caller\'s caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + */ + voiceCallerIdLookup: boolean; + /** + * The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + */ + voiceFallbackMethod: string; + /** + * The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + */ + voiceFallbackUrl: string; + /** + * The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + */ + voiceMethod: string; + /** + * The URL we call when this phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + */ + voiceUrl: string; + emergencyStatus: LocalEmergencyStatus; + /** + * The SID of the emergency address configuration that we use for emergency calling from this phone number. + */ + emergencyAddressSid: string; + emergencyAddressStatus: LocalEmergencyAddressStatus; + /** + * The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + */ + bundleSid: string; + status: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + addressSid: this.addressSid, + addressRequirements: this.addressRequirements, + apiVersion: this.apiVersion, + beta: this.beta, + capabilities: this.capabilities, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + identitySid: this.identitySid, + phoneNumber: this.phoneNumber, + origin: this.origin, + sid: this.sid, + smsApplicationSid: this.smsApplicationSid, + smsFallbackMethod: this.smsFallbackMethod, + smsFallbackUrl: this.smsFallbackUrl, + smsMethod: this.smsMethod, + smsUrl: this.smsUrl, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + trunkSid: this.trunkSid, + uri: this.uri, + voiceReceiveMode: this.voiceReceiveMode, + voiceApplicationSid: this.voiceApplicationSid, + voiceCallerIdLookup: this.voiceCallerIdLookup, + voiceFallbackMethod: this.voiceFallbackMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceMethod: this.voiceMethod, + voiceUrl: this.voiceUrl, + emergencyStatus: this.emergencyStatus, + emergencyAddressSid: this.emergencyAddressSid, + emergencyAddressStatus: this.emergencyAddressStatus, + bundleSid: this.bundleSid, + status: this.status, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class LocalPage extends Page { +/** +* Initialize the LocalPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: LocalSolution) { + super(version, response, solution); + } + + /** + * Build an instance of LocalInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: LocalResource): LocalInstance { + + return new LocalInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/incomingPhoneNumber/mobile.ts b/rest/api/v2010/account/incomingPhoneNumber/mobile.ts new file mode 100644 index 000000000..0fb22b1ba --- /dev/null +++ b/rest/api/v2010/account/incomingPhoneNumber/mobile.ts @@ -0,0 +1,886 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../../interfaces"; + + +/** + * Whether the phone number requires an [Address](https://www.twilio.com/docs/usage/api/address) registered with Twilio. Can be: `none`, `any`, `local`, or `foreign`. + */ +export type MobileAddressRequirement = 'none'|'any'|'local'|'foreign'; + +/** + * The status of address registration with emergency services. A registered emergency address will be used during handling of emergency calls from this number. + */ +export type MobileEmergencyAddressStatus = 'registered'|'unregistered'|'pending-registration'|'registration-failure'|'pending-unregistration'|'unregistration-failure'; + +/** + * The parameter displays if emergency calling is enabled for this number. Active numbers may place emergency calls by dialing valid emergency numbers for the country. + */ +export type MobileEmergencyStatus = 'Active'|'Inactive'; + +export type MobileVoiceReceiveMode = 'voice'|'fax'; + + +/** + * Options to pass to create a MobileInstance + */ +export interface MobileListInstanceCreateOptions { + /** The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. */ + "phoneNumber": string; + /** The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. */ + "apiVersion"?: string; + /** A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. */ + "friendlyName"?: string; + /** The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. */ + "smsApplicationSid"?: string; + /** The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "smsFallbackMethod"?: string; + /** The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. */ + "smsFallbackUrl"?: string; + /** The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "smsMethod"?: string; + /** The URL we should call when the new phone number receives an incoming SMS message. */ + "smsUrl"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "statusCallbackMethod"?: string; + /** The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. */ + "voiceApplicationSid"?: string; + /** Whether to lookup the caller\\\'s name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. */ + "voiceCallerIdLookup"?: boolean; + /** The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "voiceMethod"?: string; + /** The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. */ + "voiceUrl"?: string; + /** The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. */ + "identitySid"?: string; + /** The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. */ + "addressSid"?: string; + /** */ + "emergencyStatus"?: MobileEmergencyStatus; + /** The SID of the emergency address configuration to use for emergency calling from the new phone number. */ + "emergencyAddressSid"?: string; + /** The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. */ + "trunkSid"?: string; + /** */ + "voiceReceiveMode"?: MobileVoiceReceiveMode; + /** The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. */ + "bundleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface MobileListInstanceEachOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MobileInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MobileListInstanceOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MobileListInstancePageOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface MobileSolution { + accountSid: string; +} + +export interface MobileListInstance { + _version: V2010; + _solution: MobileSolution; + _uri: string; + + + + /** + * Create a MobileInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MobileInstance + */ + create(params: MobileListInstanceCreateOptions, callback?: (error: Error | null, item?: MobileInstance) => any): Promise; + + /** + * Create a MobileInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MobileInstance with HTTP metadata + */ + createWithHttpInfo(params: MobileListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MobileInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MobileInstance, done: (err?: Error) => void) => void): void; + each(params: MobileListInstanceEachOptions, callback?: (item: MobileInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MobileInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MobileInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MobileListInstanceEachOptions, callback?: (item: MobileInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MobileInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MobilePage) => any): Promise; + /** + * Retrieve a single target page of MobileInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MobileInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MobileInstance[]) => any): Promise; + list(params: MobileListInstanceOptions, callback?: (error: Error | null, items: MobileInstance[]) => any): Promise; + /** + * Lists MobileInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MobileListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MobileInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MobilePage) => any): Promise; + page(params: MobileListInstancePageOptions, callback?: (error: Error | null, items: MobilePage) => any): Promise; + /** + * Retrieve a single page of MobileInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MobileListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MobileListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MobileListInstance(version: V2010, accountSid: string): MobileListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as MobileListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/IncomingPhoneNumbers/Mobile.json`; + + instance.create = function create(params: MobileListInstanceCreateOptions, callback?: (error: Error | null, items: MobileInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceApplicationSid"] !== undefined) + data["VoiceApplicationSid"] = params["voiceApplicationSid"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["identitySid"] !== undefined) + data["IdentitySid"] = params["identitySid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["emergencyStatus"] !== undefined) + data["EmergencyStatus"] = params["emergencyStatus"]; + if (params["emergencyAddressSid"] !== undefined) + data["EmergencyAddressSid"] = params["emergencyAddressSid"]; + if (params["trunkSid"] !== undefined) + data["TrunkSid"] = params["trunkSid"]; + if (params["voiceReceiveMode"] !== undefined) + data["VoiceReceiveMode"] = params["voiceReceiveMode"]; + if (params["bundleSid"] !== undefined) + data["BundleSid"] = params["bundleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MobileInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MobileListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceApplicationSid"] !== undefined) + data["VoiceApplicationSid"] = params["voiceApplicationSid"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["identitySid"] !== undefined) + data["IdentitySid"] = params["identitySid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["emergencyStatus"] !== undefined) + data["EmergencyStatus"] = params["emergencyStatus"]; + if (params["emergencyAddressSid"] !== undefined) + data["EmergencyAddressSid"] = params["emergencyAddressSid"]; + if (params["trunkSid"] !== undefined) + data["TrunkSid"] = params["trunkSid"]; + if (params["voiceReceiveMode"] !== undefined) + data["VoiceReceiveMode"] = params["voiceReceiveMode"]; + if (params["bundleSid"] !== undefined) + data["BundleSid"] = params["bundleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MobileInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MobileListInstancePageOptions | ((error: Error | null, items: MobilePage) => any), callback?: (error: Error | null, items: MobilePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["origin"] !== undefined) + data["Origin"] = params["origin"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MobilePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MobilePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MobilePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MobileListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["origin"] !== undefined) + data["Origin"] = params["origin"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MobilePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MobilePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface MobilePayload extends TwilioResponsePayload { + incoming_phone_numbers: MobileResource[]; +} + +interface MobileResource { + account_sid: string; + address_sid: string; + address_requirements: MobileAddressRequirement; + api_version: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; + date_created: Date; + date_updated: Date; + friendly_name: string; + identity_sid: string; + phone_number: string; + origin: string; + sid: string; + sms_application_sid: string; + sms_fallback_method: string; + sms_fallback_url: string; + sms_method: string; + sms_url: string; + status_callback: string; + status_callback_method: string; + trunk_sid: string; + uri: string; + voice_receive_mode: MobileVoiceReceiveMode; + voice_application_sid: string; + voice_caller_id_lookup: boolean; + voice_fallback_method: string; + voice_fallback_url: string; + voice_method: string; + voice_url: string; + emergency_status: MobileEmergencyStatus; + emergency_address_sid: string; + emergency_address_status: MobileEmergencyAddressStatus; + bundle_sid: string; + status: string; +} + +export class MobileInstance { + + constructor(protected _version: V2010, payload: MobileResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.addressSid = (payload.address_sid); + this.addressRequirements = payload.address_requirements; + this.apiVersion = (payload.api_version); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.identitySid = (payload.identity_sid); + this.phoneNumber = (payload.phone_number); + this.origin = (payload.origin); + this.sid = (payload.sid); + this.smsApplicationSid = (payload.sms_application_sid); + this.smsFallbackMethod = (payload.sms_fallback_method); + this.smsFallbackUrl = (payload.sms_fallback_url); + this.smsMethod = (payload.sms_method); + this.smsUrl = (payload.sms_url); + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.trunkSid = (payload.trunk_sid); + this.uri = (payload.uri); + this.voiceReceiveMode = payload.voice_receive_mode; + this.voiceApplicationSid = (payload.voice_application_sid); + this.voiceCallerIdLookup = (payload.voice_caller_id_lookup); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceMethod = (payload.voice_method); + this.voiceUrl = (payload.voice_url); + this.emergencyStatus = payload.emergency_status; + this.emergencyAddressSid = (payload.emergency_address_sid); + this.emergencyAddressStatus = payload.emergency_address_status; + this.bundleSid = (payload.bundle_sid); + this.status = (payload.status); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + */ + accountSid: string; + /** + * The SID of the Address resource associated with the phone number. + */ + addressSid: string; + addressRequirements: MobileAddressRequirement; + /** + * The API version used to start a new TwiML session. + */ + apiVersion: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + */ + identitySid: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The phone number\'s origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + */ + origin: string; + /** + * The unique string that that we created to identify the resource. + */ + sid: string; + /** + * The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + */ + smsApplicationSid: string; + /** + * The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + */ + smsFallbackMethod: string; + /** + * The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + */ + smsFallbackUrl: string; + /** + * The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + */ + smsMethod: string; + /** + * The URL we call when the phone number receives an incoming SMS message. + */ + smsUrl: string; + /** + * The URL we call using the `status_callback_method` to send status information to your application. + */ + statusCallback: string; + /** + * The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + */ + statusCallbackMethod: string; + /** + * The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + */ + trunkSid: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + voiceReceiveMode: MobileVoiceReceiveMode; + /** + * The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + */ + voiceApplicationSid: string; + /** + * Whether we look up the caller\'s caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + */ + voiceCallerIdLookup: boolean; + /** + * The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + */ + voiceFallbackMethod: string; + /** + * The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + */ + voiceFallbackUrl: string; + /** + * The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + */ + voiceMethod: string; + /** + * The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + */ + voiceUrl: string; + emergencyStatus: MobileEmergencyStatus; + /** + * The SID of the emergency address configuration that we use for emergency calling from this phone number. + */ + emergencyAddressSid: string; + emergencyAddressStatus: MobileEmergencyAddressStatus; + /** + * The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + */ + bundleSid: string; + status: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + addressSid: this.addressSid, + addressRequirements: this.addressRequirements, + apiVersion: this.apiVersion, + beta: this.beta, + capabilities: this.capabilities, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + identitySid: this.identitySid, + phoneNumber: this.phoneNumber, + origin: this.origin, + sid: this.sid, + smsApplicationSid: this.smsApplicationSid, + smsFallbackMethod: this.smsFallbackMethod, + smsFallbackUrl: this.smsFallbackUrl, + smsMethod: this.smsMethod, + smsUrl: this.smsUrl, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + trunkSid: this.trunkSid, + uri: this.uri, + voiceReceiveMode: this.voiceReceiveMode, + voiceApplicationSid: this.voiceApplicationSid, + voiceCallerIdLookup: this.voiceCallerIdLookup, + voiceFallbackMethod: this.voiceFallbackMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceMethod: this.voiceMethod, + voiceUrl: this.voiceUrl, + emergencyStatus: this.emergencyStatus, + emergencyAddressSid: this.emergencyAddressSid, + emergencyAddressStatus: this.emergencyAddressStatus, + bundleSid: this.bundleSid, + status: this.status, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class MobilePage extends Page { +/** +* Initialize the MobilePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: MobileSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MobileInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MobileResource): MobileInstance { + + return new MobileInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/incomingPhoneNumber/tollFree.ts b/rest/api/v2010/account/incomingPhoneNumber/tollFree.ts new file mode 100644 index 000000000..5f8ee7f4f --- /dev/null +++ b/rest/api/v2010/account/incomingPhoneNumber/tollFree.ts @@ -0,0 +1,886 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../../interfaces"; + + +/** + * Whether the phone number requires an [Address](https://www.twilio.com/docs/usage/api/address) registered with Twilio. Can be: `none`, `any`, `local`, or `foreign`. + */ +export type TollFreeAddressRequirement = 'none'|'any'|'local'|'foreign'; + +/** + * The status of address registration with emergency services. A registered emergency address will be used during handling of emergency calls from this number. + */ +export type TollFreeEmergencyAddressStatus = 'registered'|'unregistered'|'pending-registration'|'registration-failure'|'pending-unregistration'|'unregistration-failure'; + +/** + * The parameter displays if emergency calling is enabled for this number. Active numbers may place emergency calls by dialing valid emergency numbers for the country. + */ +export type TollFreeEmergencyStatus = 'Active'|'Inactive'; + +export type TollFreeVoiceReceiveMode = 'voice'|'fax'; + + +/** + * Options to pass to create a TollFreeInstance + */ +export interface TollFreeListInstanceCreateOptions { + /** The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. */ + "phoneNumber": string; + /** The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. */ + "apiVersion"?: string; + /** A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. */ + "friendlyName"?: string; + /** The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. */ + "smsApplicationSid"?: string; + /** The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "smsFallbackMethod"?: string; + /** The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. */ + "smsFallbackUrl"?: string; + /** The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "smsMethod"?: string; + /** The URL we should call when the new phone number receives an incoming SMS message. */ + "smsUrl"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "statusCallbackMethod"?: string; + /** The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. */ + "voiceApplicationSid"?: string; + /** Whether to lookup the caller\\\'s name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. */ + "voiceCallerIdLookup"?: boolean; + /** The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. */ + "voiceMethod"?: string; + /** The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. */ + "voiceUrl"?: string; + /** The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. */ + "identitySid"?: string; + /** The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. */ + "addressSid"?: string; + /** */ + "emergencyStatus"?: TollFreeEmergencyStatus; + /** The SID of the emergency address configuration to use for emergency calling from the new phone number. */ + "emergencyAddressSid"?: string; + /** The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. */ + "trunkSid"?: string; + /** */ + "voiceReceiveMode"?: TollFreeVoiceReceiveMode; + /** The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. */ + "bundleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface TollFreeListInstanceEachOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TollFreeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TollFreeListInstanceOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TollFreeListInstancePageOptions { + /** Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. */ + "beta"?: boolean; + /** A string that identifies the resources to read. */ + "friendlyName"?: string; + /** The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "phoneNumber"?: string; + /** Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. */ + "origin"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface TollFreeSolution { + accountSid: string; +} + +export interface TollFreeListInstance { + _version: V2010; + _solution: TollFreeSolution; + _uri: string; + + + + /** + * Create a TollFreeInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollFreeInstance + */ + create(params: TollFreeListInstanceCreateOptions, callback?: (error: Error | null, item?: TollFreeInstance) => any): Promise; + + /** + * Create a TollFreeInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollFreeInstance with HTTP metadata + */ + createWithHttpInfo(params: TollFreeListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams TollFreeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TollFreeInstance, done: (err?: Error) => void) => void): void; + each(params: TollFreeListInstanceEachOptions, callback?: (item: TollFreeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TollFreeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TollFreeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TollFreeListInstanceEachOptions, callback?: (item: TollFreeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TollFreeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TollFreePage) => any): Promise; + /** + * Retrieve a single target page of TollFreeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists TollFreeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TollFreeInstance[]) => any): Promise; + list(params: TollFreeListInstanceOptions, callback?: (error: Error | null, items: TollFreeInstance[]) => any): Promise; + /** + * Lists TollFreeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: TollFreeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of TollFreeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TollFreePage) => any): Promise; + page(params: TollFreeListInstancePageOptions, callback?: (error: Error | null, items: TollFreePage) => any): Promise; + /** + * Retrieve a single page of TollFreeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollFreeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: TollFreeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TollFreeListInstance(version: V2010, accountSid: string): TollFreeListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as TollFreeListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/IncomingPhoneNumbers/TollFree.json`; + + instance.create = function create(params: TollFreeListInstanceCreateOptions, callback?: (error: Error | null, items: TollFreeInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceApplicationSid"] !== undefined) + data["VoiceApplicationSid"] = params["voiceApplicationSid"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["identitySid"] !== undefined) + data["IdentitySid"] = params["identitySid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["emergencyStatus"] !== undefined) + data["EmergencyStatus"] = params["emergencyStatus"]; + if (params["emergencyAddressSid"] !== undefined) + data["EmergencyAddressSid"] = params["emergencyAddressSid"]; + if (params["trunkSid"] !== undefined) + data["TrunkSid"] = params["trunkSid"]; + if (params["voiceReceiveMode"] !== undefined) + data["VoiceReceiveMode"] = params["voiceReceiveMode"]; + if (params["bundleSid"] !== undefined) + data["BundleSid"] = params["bundleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TollFreeInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TollFreeListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["voiceApplicationSid"] !== undefined) + data["VoiceApplicationSid"] = params["voiceApplicationSid"]; + if (params["voiceCallerIdLookup"] !== undefined) + data["VoiceCallerIdLookup"] = serialize.bool(params["voiceCallerIdLookup"]); + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["identitySid"] !== undefined) + data["IdentitySid"] = params["identitySid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["emergencyStatus"] !== undefined) + data["EmergencyStatus"] = params["emergencyStatus"]; + if (params["emergencyAddressSid"] !== undefined) + data["EmergencyAddressSid"] = params["emergencyAddressSid"]; + if (params["trunkSid"] !== undefined) + data["TrunkSid"] = params["trunkSid"]; + if (params["voiceReceiveMode"] !== undefined) + data["VoiceReceiveMode"] = params["voiceReceiveMode"]; + if (params["bundleSid"] !== undefined) + data["BundleSid"] = params["bundleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new TollFreeInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TollFreeListInstancePageOptions | ((error: Error | null, items: TollFreePage) => any), callback?: (error: Error | null, items: TollFreePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["origin"] !== undefined) + data["Origin"] = params["origin"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TollFreePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TollFreePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TollFreePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TollFreeListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["beta"] !== undefined) + data["Beta"] = serialize.bool(params["beta"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["origin"] !== undefined) + data["Origin"] = params["origin"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TollFreePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TollFreePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TollFreePayload extends TwilioResponsePayload { + incoming_phone_numbers: TollFreeResource[]; +} + +interface TollFreeResource { + account_sid: string; + address_sid: string; + address_requirements: TollFreeAddressRequirement; + api_version: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; + date_created: Date; + date_updated: Date; + friendly_name: string; + identity_sid: string; + phone_number: string; + origin: string; + sid: string; + sms_application_sid: string; + sms_fallback_method: string; + sms_fallback_url: string; + sms_method: string; + sms_url: string; + status_callback: string; + status_callback_method: string; + trunk_sid: string; + uri: string; + voice_receive_mode: TollFreeVoiceReceiveMode; + voice_application_sid: string; + voice_caller_id_lookup: boolean; + voice_fallback_method: string; + voice_fallback_url: string; + voice_method: string; + voice_url: string; + emergency_status: TollFreeEmergencyStatus; + emergency_address_sid: string; + emergency_address_status: TollFreeEmergencyAddressStatus; + bundle_sid: string; + status: string; +} + +export class TollFreeInstance { + + constructor(protected _version: V2010, payload: TollFreeResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.addressSid = (payload.address_sid); + this.addressRequirements = payload.address_requirements; + this.apiVersion = (payload.api_version); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.identitySid = (payload.identity_sid); + this.phoneNumber = (payload.phone_number); + this.origin = (payload.origin); + this.sid = (payload.sid); + this.smsApplicationSid = (payload.sms_application_sid); + this.smsFallbackMethod = (payload.sms_fallback_method); + this.smsFallbackUrl = (payload.sms_fallback_url); + this.smsMethod = (payload.sms_method); + this.smsUrl = (payload.sms_url); + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.trunkSid = (payload.trunk_sid); + this.uri = (payload.uri); + this.voiceReceiveMode = payload.voice_receive_mode; + this.voiceApplicationSid = (payload.voice_application_sid); + this.voiceCallerIdLookup = (payload.voice_caller_id_lookup); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceMethod = (payload.voice_method); + this.voiceUrl = (payload.voice_url); + this.emergencyStatus = payload.emergency_status; + this.emergencyAddressSid = (payload.emergency_address_sid); + this.emergencyAddressStatus = payload.emergency_address_status; + this.bundleSid = (payload.bundle_sid); + this.status = (payload.status); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + */ + accountSid: string; + /** + * The SID of the Address resource associated with the phone number. + */ + addressSid: string; + addressRequirements: TollFreeAddressRequirement; + /** + * The API version used to start a new TwiML session. + */ + apiVersion: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + */ + identitySid: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The phone number\'s origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + */ + origin: string; + /** + * The unique string that that we created to identify the resource. + */ + sid: string; + /** + * The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + */ + smsApplicationSid: string; + /** + * The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + */ + smsFallbackMethod: string; + /** + * The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + */ + smsFallbackUrl: string; + /** + * The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + */ + smsMethod: string; + /** + * The URL we call when the phone number receives an incoming SMS message. + */ + smsUrl: string; + /** + * The URL we call using the `status_callback_method` to send status information to your application. + */ + statusCallback: string; + /** + * The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + */ + statusCallbackMethod: string; + /** + * The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + */ + trunkSid: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + voiceReceiveMode: TollFreeVoiceReceiveMode; + /** + * The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + */ + voiceApplicationSid: string; + /** + * Whether we look up the caller\'s caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + */ + voiceCallerIdLookup: boolean; + /** + * The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + */ + voiceFallbackMethod: string; + /** + * The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + */ + voiceFallbackUrl: string; + /** + * The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + */ + voiceMethod: string; + /** + * The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + */ + voiceUrl: string; + emergencyStatus: TollFreeEmergencyStatus; + /** + * The SID of the emergency address configuration that we use for emergency calling from this phone number. + */ + emergencyAddressSid: string; + emergencyAddressStatus: TollFreeEmergencyAddressStatus; + /** + * The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + */ + bundleSid: string; + status: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + addressSid: this.addressSid, + addressRequirements: this.addressRequirements, + apiVersion: this.apiVersion, + beta: this.beta, + capabilities: this.capabilities, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + identitySid: this.identitySid, + phoneNumber: this.phoneNumber, + origin: this.origin, + sid: this.sid, + smsApplicationSid: this.smsApplicationSid, + smsFallbackMethod: this.smsFallbackMethod, + smsFallbackUrl: this.smsFallbackUrl, + smsMethod: this.smsMethod, + smsUrl: this.smsUrl, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + trunkSid: this.trunkSid, + uri: this.uri, + voiceReceiveMode: this.voiceReceiveMode, + voiceApplicationSid: this.voiceApplicationSid, + voiceCallerIdLookup: this.voiceCallerIdLookup, + voiceFallbackMethod: this.voiceFallbackMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceMethod: this.voiceMethod, + voiceUrl: this.voiceUrl, + emergencyStatus: this.emergencyStatus, + emergencyAddressSid: this.emergencyAddressSid, + emergencyAddressStatus: this.emergencyAddressStatus, + bundleSid: this.bundleSid, + status: this.status, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class TollFreePage extends Page { +/** +* Initialize the TollFreePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: TollFreeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TollFreeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TollFreeResource): TollFreeInstance { + + return new TollFreeInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/key.ts b/rest/api/v2010/account/key.ts new file mode 100644 index 000000000..631efa4c3 --- /dev/null +++ b/rest/api/v2010/account/key.ts @@ -0,0 +1,787 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a KeyInstance + */ +export interface KeyContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; +} + +/** + * Options to pass to each + */ +export interface KeyListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: KeyInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface KeyListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface KeyListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface KeyContext { + + /** + * Remove a KeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a KeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a KeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance + */ + fetch(callback?: (error: Error | null, item?: KeyInstance) => any): Promise + + /** + * Fetch a KeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a KeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance + */ + update(callback?: (error: Error | null, item?: KeyInstance) => any): Promise; + /** + * Update a KeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance + */ + update(params: KeyContextUpdateOptions, callback?: (error: Error | null, item?: KeyInstance) => any): Promise; + + /** + * Update a KeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a KeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance with HTTP metadata + */ + updateWithHttpInfo(params: KeyContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface KeyContextSolution { + "accountSid": string; + "sid": string; +} + +export class KeyContextImpl implements KeyContext { + protected _solution: KeyContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Keys/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: KeyInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new KeyInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new KeyInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: KeyContextUpdateOptions | ((error: Error | null, item?: KeyInstance) => any),callback?: (error: Error | null, item?: KeyInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new KeyInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: KeyContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new KeyInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface KeyPayload extends TwilioResponsePayload { + keys: KeyResource[]; +} + +interface KeyResource { + sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; +} + +export class KeyInstance { + protected _solution: KeyContextSolution; + protected _context?: KeyContext; + + constructor(protected _version: V2010, payload: KeyResource, accountSid: string, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The unique string that that we created to identify the Key resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + + private get _proxy(): KeyContext { + this._context = this._context || new KeyContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a KeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a KeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a KeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance + */ + fetch(callback?: (error: Error | null, item?: KeyInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a KeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a KeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance + */ + update(callback?: (error: Error | null, item?: KeyInstance) => any): Promise; + /** + * Update a KeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance + */ + update(params: KeyContextUpdateOptions, callback?: (error: Error | null, item?: KeyInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: KeyInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a KeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a KeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KeyInstance with HTTP metadata + */ + updateWithHttpInfo(params: KeyContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface KeySolution { + accountSid: string; +} + +export interface KeyListInstance { + _version: V2010; + _solution: KeySolution; + _uri: string; + + (sid: string, ): KeyContext; + get(sid: string, ): KeyContext; + + + + + + + + + + /** + * Streams KeyInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KeyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: KeyInstance, done: (err?: Error) => void) => void): void; + each(params: KeyListInstanceEachOptions, callback?: (item: KeyInstance, done: (err?: Error) => void) => void): void; + /** + * Streams KeyInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KeyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: KeyInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: KeyListInstanceEachOptions, callback?: (item: KeyInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of KeyInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: KeyPage) => any): Promise; + /** + * Retrieve a single target page of KeyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists KeyInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KeyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: KeyInstance[]) => any): Promise; + list(params: KeyListInstanceOptions, callback?: (error: Error | null, items: KeyInstance[]) => any): Promise; + /** + * Lists KeyInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KeyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: KeyListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of KeyInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KeyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: KeyPage) => any): Promise; + page(params: KeyListInstancePageOptions, callback?: (error: Error | null, items: KeyPage) => any): Promise; + /** + * Retrieve a single page of KeyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KeyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: KeyListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function KeyListInstance(version: V2010, accountSid: string): KeyListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as KeyListInstance; + + instance.get = function get(sid, ): KeyContext { + return new KeyContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Keys.json`; + + instance.page = function page(params?: KeyListInstancePageOptions | ((error: Error | null, items: KeyPage) => any), callback?: (error: Error | null, items: KeyPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new KeyPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: KeyPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new KeyPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: KeyListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new KeyPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new KeyPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class KeyPage extends Page { +/** +* Initialize the KeyPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: KeySolution) { + super(version, response, solution); + } + + /** + * Build an instance of KeyInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: KeyResource): KeyInstance { + + return new KeyInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/message.ts b/rest/api/v2010/account/message.ts new file mode 100644 index 000000000..3c89e77e5 --- /dev/null +++ b/rest/api/v2010/account/message.ts @@ -0,0 +1,1256 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { FeedbackListInstance } from "./message/feedback"; +import { MediaListInstance } from "./message/media"; + + +/** + * Determines if the address can be stored or obfuscated based on privacy settings + */ +export type MessageAddressRetention = 'retain'|'obfuscate'; + +/** + * Determines if the message content can be stored or redacted based on privacy settings + */ +export type MessageContentRetention = 'retain'|'discard'; + +/** + * The direction of the message. Can be: `inbound` for incoming messages, `outbound-api` for messages created by the REST API, `outbound-call` for messages created during a call, or `outbound-reply` for messages created in response to an incoming message. + */ +export type MessageDirection = 'inbound'|'outbound-api'|'outbound-call'|'outbound-reply'; + +/** + * Include this parameter with a value of `disable` to skip any kind of risk check on the respective message request. + */ +export type MessageRiskCheck = 'enable'|'disable'; + +/** + * For Messaging Services only: Include this parameter with a value of `fixed` in conjuction with the `send_time` parameter in order to [schedule a Message](https://www.twilio.com/docs/messaging/features/message-scheduling). + */ +export type MessageScheduleType = 'fixed'; + +/** + * The status of the Message. Possible values: `accepted`, `scheduled`, `canceled`, `queued`, `sending`, `sent`, `failed`, `delivered`, `undelivered`, `receiving`, `received`, or `read` (WhatsApp only). For more information, See [detailed descriptions](https://www.twilio.com/docs/sms/api/message-resource#message-status-values). + */ +export type MessageStatus = 'queued'|'sending'|'sent'|'failed'|'delivered'|'undelivered'|'receiving'|'received'|'accepted'|'scheduled'|'read'|'partially_delivered'|'canceled'; + +export type MessageTrafficType = 'free'; + +export type MessageUpdateStatus = 'canceled'; + + + + +/** + * Options to pass to update a MessageInstance + */ +export interface MessageContextUpdateOptions { + /** The new `body` of the Message resource. To redact the text content of a Message, this parameter\\\'s value must be an empty string */ + "body"?: string; + /** */ + "status"?: MessageUpdateStatus; +} + +/** + * Options to pass to create a MessageInstance + */ +export interface MessageListInstanceCreateOptions { + /** The recipient\\\'s phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. */ + "to": string; + /** The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). */ + "statusCallback"?: string; + /** The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App\\\'s `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. */ + "applicationSid"?: string; + /** [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. */ + "maxPrice"?: number; + /** Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. */ + "provideFeedback"?: boolean; + /** Total number of attempts made (including this request) to send the message regardless of the provider used */ + "attempt"?: number; + /** The maximum length in seconds that the Message can remain in Twilio\\\'s outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) */ + "validityPeriod"?: number; + /** Reserved */ + "forceDelivery"?: boolean; + /** */ + "contentRetention"?: MessageContentRetention; + /** */ + "addressRetention"?: MessageAddressRetention; + /** Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. */ + "smartEncoded"?: boolean; + /** Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). */ + "persistentAction"?: Array; + /** */ + "trafficType"?: MessageTrafficType; + /** For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. */ + "shortenUrls"?: boolean; + /** */ + "scheduleType"?: MessageScheduleType; + /** The time that Twilio will send the message. Must be in ISO 8601 format. */ + "sendAt"?: Date; + /** If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. */ + "sendAsMms"?: boolean; + /** For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template\\\'s default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. */ + "contentVariables"?: string; + /** */ + "riskCheck"?: MessageRiskCheck; + /** The sender\\\'s Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service\\\'s Sender Pool) or you can provide a specific sender from your Sender Pool. */ + "from"?: string; + /** A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. */ + "fallbackFrom"?: string; + /** The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service\\\'s Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. */ + "messagingServiceSid"?: string; + /** The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). */ + "body"?: string; + /** The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. */ + "mediaUrl"?: Array; + /** For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio\\\'s response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). */ + "contentSid"?: string; +} + +/** + * Options to pass to each + */ +export interface MessageListInstanceEachOptions { + /** Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. */ + "to"?: string; + /** Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. */ + "from"?: string; + /** Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). */ + "dateSent"?: Date; + /** Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). */ + "dateSentBefore"?: Date; + /** Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). */ + "dateSentAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MessageInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MessageListInstanceOptions { + /** Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. */ + "to"?: string; + /** Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. */ + "from"?: string; + /** Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). */ + "dateSent"?: Date; + /** Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). */ + "dateSentBefore"?: Date; + /** Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). */ + "dateSentAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MessageListInstancePageOptions { + /** Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. */ + "to"?: string; + /** Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. */ + "from"?: string; + /** Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). */ + "dateSent"?: Date; + /** Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). */ + "dateSentBefore"?: Date; + /** Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). */ + "dateSentAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MessageContext { + feedback: FeedbackListInstance; + media: MediaListInstance; + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MessageContextSolution { + "accountSid": string; + "sid": string; +} + +export class MessageContextImpl implements MessageContext { + protected _solution: MessageContextSolution; + protected _uri: string; + + protected _feedback?: FeedbackListInstance; + protected _media?: MediaListInstance; + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Messages/${sid}.json`; + } + + get feedback(): FeedbackListInstance { + this._feedback = this._feedback || FeedbackListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._feedback; + } + + get media(): MediaListInstance { + this._media = this._media || MediaListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._media; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MessageContextUpdateOptions | ((error: Error | null, item?: MessageInstance) => any),callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MessageContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MessagePayload extends TwilioResponsePayload { + messages: MessageResource[]; +} + +interface MessageResource { + body: string; + num_segments: string; + direction: MessageDirection; + from: string; + to: string; + date_updated: Date; + price: string; + error_message: string; + uri: string; + account_sid: string; + num_media: string; + status: MessageStatus; + messaging_service_sid: string; + sid: string; + date_sent: Date; + date_created: Date; + error_code: number; + price_unit: string; + api_version: string; + subresource_uris: Record; +} + +export class MessageInstance { + protected _solution: MessageContextSolution; + protected _context?: MessageContext; + + constructor(protected _version: V2010, payload: MessageResource, accountSid: string, sid?: string) { + + this.body = (payload.body); + this.numSegments = (payload.num_segments); + this.direction = payload.direction; + this.from = (payload.from); + this.to = (payload.to); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.price = (payload.price); + this.errorMessage = (payload.error_message); + this.uri = (payload.uri); + this.accountSid = (payload.account_sid); + this.numMedia = (payload.num_media); + this.status = payload.status; + this.messagingServiceSid = (payload.messaging_service_sid); + this.sid = (payload.sid); + this.dateSent = deserialize.rfc2822DateTime(payload.date_sent); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.errorCode = deserialize.integer(payload.error_code); + this.priceUnit = (payload.price_unit); + this.apiVersion = (payload.api_version); + this.subresourceUris = (payload.subresource_uris); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The text content of the message + */ + body: string; + /** + * The number of segments that make up the complete message. SMS message bodies that exceed the [character limit](https://www.twilio.com/docs/glossary/what-sms-character-limit) are segmented and charged as multiple messages. Note: For messages sent via a Messaging Service, `num_segments` is initially `0`, since a sender hasn\'t yet been assigned. + */ + numSegments: string; + direction: MessageDirection; + /** + * The sender\'s phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). For incoming messages, this is the number or channel address of the sender. For outgoing messages, this value is a Twilio phone number, alphanumeric sender ID, short code, or channel address from which the message is sent. + */ + from: string; + /** + * The recipient\'s phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format) or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g. `whatsapp:+15552229999`) + */ + to: string; + /** + * The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was last updated + */ + dateUpdated: Date; + /** + * The amount billed for the message in the currency specified by `price_unit`. The `price` is populated after the message has been sent/received, and may not be immediately availalble. View the [Pricing page](https://www.twilio.com/en-us/pricing) for more details. + */ + price: string; + /** + * The description of the `error_code` if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically. + */ + errorMessage: string; + /** + * The URI of the Message resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resource + */ + accountSid: string; + /** + * The number of media files associated with the Message resource. + */ + numMedia: string; + status: MessageStatus; + /** + * The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) associated with the Message resource. A unique default value is assigned if a Messaging Service is not used. + */ + messagingServiceSid: string; + /** + * The unique, Twilio-provided string that identifies the Message resource. + */ + sid: string; + /** + * The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message was sent. For an outgoing message, this is when Twilio sent the message. For an incoming message, this is when Twilio sent the HTTP request to your incoming message webhook URL. + */ + dateSent: Date; + /** + * The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was created + */ + dateCreated: Date; + /** + * The [error code](https://www.twilio.com/docs/api/errors) returned if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically. + */ + errorCode: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + */ + priceUnit: string; + /** + * The API version used to process the Message + */ + apiVersion: string; + /** + * A list of related resources identified by their URIs relative to `https://api.twilio.com` + */ + subresourceUris: Record; + + private get _proxy(): MessageContext { + this._context = this._context || new MessageContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MessageInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the feedback. + */ + feedback(): FeedbackListInstance { + return this._proxy.feedback; + } + + /** + * Access the media. + */ + media(): MediaListInstance { + return this._proxy.media; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + body: this.body, + numSegments: this.numSegments, + direction: this.direction, + from: this.from, + to: this.to, + dateUpdated: this.dateUpdated, + price: this.price, + errorMessage: this.errorMessage, + uri: this.uri, + accountSid: this.accountSid, + numMedia: this.numMedia, + status: this.status, + messagingServiceSid: this.messagingServiceSid, + sid: this.sid, + dateSent: this.dateSent, + dateCreated: this.dateCreated, + errorCode: this.errorCode, + priceUnit: this.priceUnit, + apiVersion: this.apiVersion, + subresourceUris: this.subresourceUris, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MessageSolution { + accountSid: string; +} + +export interface MessageListInstance { + _version: V2010; + _solution: MessageSolution; + _uri: string; + + (sid: string, ): MessageContext; + get(sid: string, ): MessageContext; + + + + + + + + + /** + * Create a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Create a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MessageInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + each(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MessageInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single target page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MessageInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + list(params: MessageListInstanceOptions, callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + /** + * Lists MessageInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MessageListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MessagePage) => any): Promise; + page(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessageListInstance(version: V2010, accountSid: string): MessageListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MessageListInstance; + + instance.get = function get(sid, ): MessageContext { + return new MessageContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Messages.json`; + + instance.create = function create(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, items: MessageInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["applicationSid"] !== undefined) + data["ApplicationSid"] = params["applicationSid"]; + if (params["maxPrice"] !== undefined) + data["MaxPrice"] = params["maxPrice"]; + if (params["provideFeedback"] !== undefined) + data["ProvideFeedback"] = serialize.bool(params["provideFeedback"]); + if (params["attempt"] !== undefined) + data["Attempt"] = params["attempt"]; + if (params["validityPeriod"] !== undefined) + data["ValidityPeriod"] = params["validityPeriod"]; + if (params["forceDelivery"] !== undefined) + data["ForceDelivery"] = serialize.bool(params["forceDelivery"]); + if (params["contentRetention"] !== undefined) + data["ContentRetention"] = params["contentRetention"]; + if (params["addressRetention"] !== undefined) + data["AddressRetention"] = params["addressRetention"]; + if (params["smartEncoded"] !== undefined) + data["SmartEncoded"] = serialize.bool(params["smartEncoded"]); + if (params["persistentAction"] !== undefined) + data["PersistentAction"] = serialize.map(params["persistentAction"], (e: string) => (e)); + if (params["trafficType"] !== undefined) + data["TrafficType"] = params["trafficType"]; + if (params["shortenUrls"] !== undefined) + data["ShortenUrls"] = serialize.bool(params["shortenUrls"]); + if (params["scheduleType"] !== undefined) + data["ScheduleType"] = params["scheduleType"]; + if (params["sendAt"] !== undefined) + data["SendAt"] = serialize.iso8601DateTime(params["sendAt"]); + if (params["sendAsMms"] !== undefined) + data["SendAsMms"] = serialize.bool(params["sendAsMms"]); + if (params["contentVariables"] !== undefined) + data["ContentVariables"] = params["contentVariables"]; + if (params["riskCheck"] !== undefined) + data["RiskCheck"] = params["riskCheck"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["fallbackFrom"] !== undefined) + data["FallbackFrom"] = params["fallbackFrom"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["mediaUrl"] !== undefined) + data["MediaUrl"] = serialize.map(params["mediaUrl"], (e: string) => (e)); + if (params["contentSid"] !== undefined) + data["ContentSid"] = params["contentSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["applicationSid"] !== undefined) + data["ApplicationSid"] = params["applicationSid"]; + if (params["maxPrice"] !== undefined) + data["MaxPrice"] = params["maxPrice"]; + if (params["provideFeedback"] !== undefined) + data["ProvideFeedback"] = serialize.bool(params["provideFeedback"]); + if (params["attempt"] !== undefined) + data["Attempt"] = params["attempt"]; + if (params["validityPeriod"] !== undefined) + data["ValidityPeriod"] = params["validityPeriod"]; + if (params["forceDelivery"] !== undefined) + data["ForceDelivery"] = serialize.bool(params["forceDelivery"]); + if (params["contentRetention"] !== undefined) + data["ContentRetention"] = params["contentRetention"]; + if (params["addressRetention"] !== undefined) + data["AddressRetention"] = params["addressRetention"]; + if (params["smartEncoded"] !== undefined) + data["SmartEncoded"] = serialize.bool(params["smartEncoded"]); + if (params["persistentAction"] !== undefined) + data["PersistentAction"] = serialize.map(params["persistentAction"], (e: string) => (e)); + if (params["trafficType"] !== undefined) + data["TrafficType"] = params["trafficType"]; + if (params["shortenUrls"] !== undefined) + data["ShortenUrls"] = serialize.bool(params["shortenUrls"]); + if (params["scheduleType"] !== undefined) + data["ScheduleType"] = params["scheduleType"]; + if (params["sendAt"] !== undefined) + data["SendAt"] = serialize.iso8601DateTime(params["sendAt"]); + if (params["sendAsMms"] !== undefined) + data["SendAsMms"] = serialize.bool(params["sendAsMms"]); + if (params["contentVariables"] !== undefined) + data["ContentVariables"] = params["contentVariables"]; + if (params["riskCheck"] !== undefined) + data["RiskCheck"] = params["riskCheck"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["fallbackFrom"] !== undefined) + data["FallbackFrom"] = params["fallbackFrom"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["mediaUrl"] !== undefined) + data["MediaUrl"] = serialize.map(params["mediaUrl"], (e: string) => (e)); + if (params["contentSid"] !== undefined) + data["ContentSid"] = params["contentSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MessageListInstancePageOptions | ((error: Error | null, items: MessagePage) => any), callback?: (error: Error | null, items: MessagePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["dateSent"] !== undefined) + data["DateSent"] = serialize.iso8601DateTime(params["dateSent"]); + if (params["dateSentBefore"] !== undefined) + data["DateSent<"] = serialize.iso8601DateTime(params["dateSentBefore"]); + if (params["dateSentAfter"] !== undefined) + data["DateSent>"] = serialize.iso8601DateTime(params["dateSentAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MessagePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MessagePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MessageListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["dateSent"] !== undefined) + data["DateSent"] = serialize.iso8601DateTime(params["dateSent"]); + if (params["dateSentBefore"] !== undefined) + data["DateSent<"] = serialize.iso8601DateTime(params["dateSentBefore"]); + if (params["dateSentAfter"] !== undefined) + data["DateSent>"] = serialize.iso8601DateTime(params["dateSentAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MessagePage extends Page { +/** +* Initialize the MessagePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: MessageSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MessageInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MessageResource): MessageInstance { + + return new MessageInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/message/feedback.ts b/rest/api/v2010/account/message/feedback.ts new file mode 100644 index 000000000..6d70d1e00 --- /dev/null +++ b/rest/api/v2010/account/message/feedback.ts @@ -0,0 +1,256 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * Reported outcome indicating whether there is confirmation that the Message recipient performed a tracked user action. Can be: `unconfirmed` or `confirmed`. For more details see [How to Optimize Message Deliverability with Message Feedback](https://www.twilio.com/docs/messaging/guides/send-message-feedback-to-twilio). + */ +export type FeedbackOutcome = 'confirmed'|'unconfirmed'; + + +/** + * Options to pass to create a FeedbackInstance + */ +export interface FeedbackListInstanceCreateOptions { + /** */ + "outcome"?: FeedbackOutcome; +} + + +export interface FeedbackSolution { + accountSid: string; + messageSid: string; +} + +export interface FeedbackListInstance { + _version: V2010; + _solution: FeedbackSolution; + _uri: string; + + + + /** + * Create a FeedbackInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FeedbackInstance + */ + create(callback?: (error: Error | null, item?: FeedbackInstance) => any): Promise; + /** + * Create a FeedbackInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FeedbackInstance + */ + create(params: FeedbackListInstanceCreateOptions, callback?: (error: Error | null, item?: FeedbackInstance) => any): Promise; + + /** + * Create a FeedbackInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FeedbackInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a FeedbackInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FeedbackInstance with HTTP metadata + */ + createWithHttpInfo(params: FeedbackListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FeedbackListInstance(version: V2010, accountSid: string, messageSid: string): FeedbackListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(messageSid)) { + throw new Error('Parameter \'messageSid\' is not valid.'); + } + + const instance = {} as FeedbackListInstance; + + instance._version = version; + instance._solution = { accountSid, messageSid, }; + instance._uri = `/Accounts/${accountSid}/Messages/${messageSid}/Feedback.json`; + + instance.create = function create(params?: FeedbackListInstanceCreateOptions | ((error: Error | null, items: FeedbackInstance) => any), callback?: (error: Error | null, items: FeedbackInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["outcome"] !== undefined) + data["Outcome"] = params["outcome"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FeedbackInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.messageSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: FeedbackListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["outcome"] !== undefined) + data["Outcome"] = params["outcome"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new FeedbackInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.messageSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface FeedbackPayload extends FeedbackResource {} + +interface FeedbackResource { + account_sid: string; + message_sid: string; + outcome: FeedbackOutcome; + date_created: Date; + date_updated: Date; + uri: string; +} + +export class FeedbackInstance { + + constructor(protected _version: V2010, payload: FeedbackResource, accountSid: string, messageSid: string) { + + this.accountSid = (payload.account_sid); + this.messageSid = (payload.message_sid); + this.outcome = payload.outcome; + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.uri = (payload.uri); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with this MessageFeedback resource. + */ + accountSid: string; + /** + * The SID of the Message resource associated with this MessageFeedback resource. + */ + messageSid: string; + outcome: FeedbackOutcome; + /** + * The date and time in GMT when this MessageFeedback resource was created, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when this MessageFeedback resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + messageSid: this.messageSid, + outcome: this.outcome, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/api/v2010/account/message/media.ts b/rest/api/v2010/account/message/media.ts new file mode 100644 index 000000000..e65dd91b3 --- /dev/null +++ b/rest/api/v2010/account/message/media.ts @@ -0,0 +1,688 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to each + */ +export interface MediaListInstanceEachOptions { + /** Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. */ + "dateCreated"?: Date; + /** Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. */ + "dateCreatedBefore"?: Date; + /** Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. */ + "dateCreatedAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MediaInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MediaListInstanceOptions { + /** Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. */ + "dateCreated"?: Date; + /** Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. */ + "dateCreatedBefore"?: Date; + /** Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. */ + "dateCreatedAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MediaListInstancePageOptions { + /** Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. */ + "dateCreated"?: Date; + /** Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. */ + "dateCreatedBefore"?: Date; + /** Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. */ + "dateCreatedAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MediaContext { + + /** + * Remove a MediaInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a MediaInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a MediaInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance + */ + fetch(callback?: (error: Error | null, item?: MediaInstance) => any): Promise + + /** + * Fetch a MediaInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MediaContextSolution { + "accountSid": string; + "messageSid": string; + "sid": string; +} + +export class MediaContextImpl implements MediaContext { + protected _solution: MediaContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, messageSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(messageSid)) { + throw new Error('Parameter \'messageSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, messageSid, sid, }; + this._uri = `/Accounts/${accountSid}/Messages/${messageSid}/Media/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MediaInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MediaInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.messageSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MediaInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.messageSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MediaPayload extends TwilioResponsePayload { + media_list: MediaResource[]; +} + +interface MediaResource { + account_sid: string; + content_type: string; + date_created: Date; + date_updated: Date; + parent_sid: string; + sid: string; + uri: string; +} + +export class MediaInstance { + protected _solution: MediaContextSolution; + protected _context?: MediaContext; + + constructor(protected _version: V2010, payload: MediaResource, accountSid: string, messageSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.contentType = (payload.content_type); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.parentSid = (payload.parent_sid); + this.sid = (payload.sid); + this.uri = (payload.uri); + + this._solution = { accountSid, messageSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with this Media resource. + */ + accountSid: string; + /** + * The default [MIME type](https://en.wikipedia.org/wiki/Internet_media_type) of the media, for example `image/jpeg`, `image/png`, or `image/gif`. + */ + contentType: string; + /** + * The date and time in GMT when this Media resource was created, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when this Media resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The SID of the Message resource that is associated with this Media resource. + */ + parentSid: string; + /** + * The unique string that identifies this Media resource. + */ + sid: string; + /** + * The URI of this Media resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): MediaContext { + this._context = this._context || new MediaContextImpl(this._version, this._solution.accountSid, this._solution.messageSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MediaInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a MediaInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a MediaInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance + */ + fetch(callback?: (error: Error | null, item?: MediaInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MediaInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + contentType: this.contentType, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + parentSid: this.parentSid, + sid: this.sid, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MediaSolution { + accountSid: string; + messageSid: string; +} + +export interface MediaListInstance { + _version: V2010; + _solution: MediaSolution; + _uri: string; + + (sid: string, ): MediaContext; + get(sid: string, ): MediaContext; + + + + + + + + /** + * Streams MediaInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MediaListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MediaInstance, done: (err?: Error) => void) => void): void; + each(params: MediaListInstanceEachOptions, callback?: (item: MediaInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MediaInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MediaListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MediaInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MediaListInstanceEachOptions, callback?: (item: MediaInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MediaInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MediaPage) => any): Promise; + /** + * Retrieve a single target page of MediaInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MediaInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MediaListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MediaInstance[]) => any): Promise; + list(params: MediaListInstanceOptions, callback?: (error: Error | null, items: MediaInstance[]) => any): Promise; + /** + * Lists MediaInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MediaListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MediaListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MediaInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MediaListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MediaPage) => any): Promise; + page(params: MediaListInstancePageOptions, callback?: (error: Error | null, items: MediaPage) => any): Promise; + /** + * Retrieve a single page of MediaInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MediaListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MediaListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MediaListInstance(version: V2010, accountSid: string, messageSid: string): MediaListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(messageSid)) { + throw new Error('Parameter \'messageSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MediaListInstance; + + instance.get = function get(sid, ): MediaContext { + return new MediaContextImpl(version, accountSid, messageSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, messageSid, }; + instance._uri = `/Accounts/${accountSid}/Messages/${messageSid}/Media.json`; + + instance.page = function page(params?: MediaListInstancePageOptions | ((error: Error | null, items: MediaPage) => any), callback?: (error: Error | null, items: MediaPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreated<"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreated>"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MediaPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MediaPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MediaPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MediaListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreated<"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreated>"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MediaPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MediaPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MediaPage extends Page { +/** +* Initialize the MediaPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: MediaSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MediaInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MediaResource): MediaInstance { + + return new MediaInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.messageSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/newKey.ts b/rest/api/v2010/account/newKey.ts new file mode 100644 index 000000000..b5c215eec --- /dev/null +++ b/rest/api/v2010/account/newKey.ts @@ -0,0 +1,242 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to create a NewKeyInstance + */ +export interface NewKeyListInstanceCreateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; +} + + +export interface NewKeySolution { + accountSid: string; +} + +export interface NewKeyListInstance { + _version: V2010; + _solution: NewKeySolution; + _uri: string; + + + + /** + * Create a NewKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewKeyInstance + */ + create(callback?: (error: Error | null, item?: NewKeyInstance) => any): Promise; + /** + * Create a NewKeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewKeyInstance + */ + create(params: NewKeyListInstanceCreateOptions, callback?: (error: Error | null, item?: NewKeyInstance) => any): Promise; + + /** + * Create a NewKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewKeyInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a NewKeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewKeyInstance with HTTP metadata + */ + createWithHttpInfo(params: NewKeyListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NewKeyListInstance(version: V2010, accountSid: string): NewKeyListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as NewKeyListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Keys.json`; + + instance.create = function create(params?: NewKeyListInstanceCreateOptions | ((error: Error | null, items: NewKeyInstance) => any), callback?: (error: Error | null, items: NewKeyInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NewKeyInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: NewKeyListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new NewKeyInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface NewKeyPayload extends NewKeyResource {} + +interface NewKeyResource { + sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + secret: string; +} + +export class NewKeyInstance { + + constructor(protected _version: V2010, payload: NewKeyResource, accountSid: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.secret = (payload.secret); + + } + + /** + * The unique string that that we created to identify the NewKey resource. You will use this as the basic-auth `user` when authenticating to the API. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT that the API Key was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the new API Key was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + */ + secret: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + secret: this.secret, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/api/v2010/account/newSigningKey.ts b/rest/api/v2010/account/newSigningKey.ts new file mode 100644 index 000000000..200b4bde8 --- /dev/null +++ b/rest/api/v2010/account/newSigningKey.ts @@ -0,0 +1,242 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to create a NewSigningKeyInstance + */ +export interface NewSigningKeyListInstanceCreateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; +} + + +export interface NewSigningKeySolution { + accountSid: string; +} + +export interface NewSigningKeyListInstance { + _version: V2010; + _solution: NewSigningKeySolution; + _uri: string; + + + + /** + * Create a NewSigningKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewSigningKeyInstance + */ + create(callback?: (error: Error | null, item?: NewSigningKeyInstance) => any): Promise; + /** + * Create a NewSigningKeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewSigningKeyInstance + */ + create(params: NewSigningKeyListInstanceCreateOptions, callback?: (error: Error | null, item?: NewSigningKeyInstance) => any): Promise; + + /** + * Create a NewSigningKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewSigningKeyInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a NewSigningKeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewSigningKeyInstance with HTTP metadata + */ + createWithHttpInfo(params: NewSigningKeyListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NewSigningKeyListInstance(version: V2010, accountSid: string): NewSigningKeyListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as NewSigningKeyListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/SigningKeys.json`; + + instance.create = function create(params?: NewSigningKeyListInstanceCreateOptions | ((error: Error | null, items: NewSigningKeyInstance) => any), callback?: (error: Error | null, items: NewSigningKeyInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NewSigningKeyInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: NewSigningKeyListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new NewSigningKeyInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface NewSigningKeyPayload extends NewSigningKeyResource {} + +interface NewSigningKeyResource { + sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + secret: string; +} + +export class NewSigningKeyInstance { + + constructor(protected _version: V2010, payload: NewSigningKeyResource, accountSid: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.secret = (payload.secret); + + } + + /** + * The unique string that that we created to identify the NewSigningKey resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + */ + secret: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + secret: this.secret, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/api/v2010/account/notification.ts b/rest/api/v2010/account/notification.ts new file mode 100644 index 000000000..5592968ee --- /dev/null +++ b/rest/api/v2010/account/notification.ts @@ -0,0 +1,679 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface NotificationListInstanceEachOptions { + /** Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. */ + "log"?: number; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDate"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateBefore"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: NotificationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface NotificationListInstanceOptions { + /** Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. */ + "log"?: number; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDate"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateBefore"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface NotificationListInstancePageOptions { + /** Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. */ + "log"?: number; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDate"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateBefore"?: Date; + /** Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. */ + "messageDateAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface NotificationContext { + + /** + * Fetch a NotificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + fetch(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise + + /** + * Fetch a NotificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface NotificationContextSolution { + "accountSid": string; + "sid": string; +} + +export class NotificationContextImpl implements NotificationContext { + protected _solution: NotificationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Notifications/${sid}.json`; + } + + fetch(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new NotificationInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new NotificationInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface NotificationPayload extends TwilioResponsePayload { + notifications: NotificationResource[]; +} + +interface NotificationResource { + account_sid: string; + api_version: string; + call_sid: string; + date_created: Date; + date_updated: Date; + error_code: string; + log: string; + message_date: Date; + message_text: string; + more_info: string; + request_method: string; + request_url: string; + request_variables: string; + response_body: string; + response_headers: string; + sid: string; + uri: string; +} + +export class NotificationInstance { + protected _solution: NotificationContextSolution; + protected _context?: NotificationContext; + + constructor(protected _version: V2010, payload: NotificationResource, accountSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.callSid = (payload.call_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.errorCode = (payload.error_code); + this.log = (payload.log); + this.messageDate = deserialize.rfc2822DateTime(payload.message_date); + this.messageText = (payload.message_text); + this.moreInfo = (payload.more_info); + this.requestMethod = (payload.request_method); + this.requestUrl = (payload.request_url); + this.requestVariables = (payload.request_variables); + this.responseBody = (payload.response_body); + this.responseHeaders = (payload.response_headers); + this.sid = (payload.sid); + this.uri = (payload.uri); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource. + */ + accountSid: string; + /** + * The API version used to generate the notification. Can be empty for events that don\'t have a specific API version, such as incoming phone calls. + */ + apiVersion: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Notification resource is associated with. + */ + callSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * A unique error code for the error condition that is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + */ + errorCode: string; + /** + * An integer log level that corresponds to the type of notification: `0` is ERROR, `1` is WARNING. + */ + log: string; + /** + * The date the notification was actually generated in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. Message buffering can cause this value to differ from `date_created`. + */ + messageDate: Date; + /** + * The text of the notification. + */ + messageText: string; + /** + * The URL for more information about the error condition. This value is a page in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + */ + moreInfo: string; + /** + * The HTTP method used to generate the notification. If the notification was generated during a phone call, this is the HTTP Method used to request the resource on your server. If the notification was generated by your use of our REST API, this is the HTTP method used to call the resource on our servers. + */ + requestMethod: string; + /** + * The URL of the resource that generated the notification. If the notification was generated during a phone call, this is the URL of the resource on your server that caused the notification. If the notification was generated by your use of our REST API, this is the URL of the resource you called. + */ + requestUrl: string; + /** + * The HTTP GET or POST variables we sent to your server. However, if the notification was generated by our REST API, this contains the HTTP POST or PUT variables you sent to our API. + */ + requestVariables: string; + /** + * The HTTP body returned by your server. + */ + responseBody: string; + /** + * The HTTP headers returned by your server. + */ + responseHeaders: string; + /** + * The unique string that that we created to identify the Notification resource. + */ + sid: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): NotificationContext { + this._context = this._context || new NotificationContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a NotificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + fetch(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a NotificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + callSid: this.callSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + errorCode: this.errorCode, + log: this.log, + messageDate: this.messageDate, + messageText: this.messageText, + moreInfo: this.moreInfo, + requestMethod: this.requestMethod, + requestUrl: this.requestUrl, + requestVariables: this.requestVariables, + responseBody: this.responseBody, + responseHeaders: this.responseHeaders, + sid: this.sid, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface NotificationSolution { + accountSid: string; +} + +export interface NotificationListInstance { + _version: V2010; + _solution: NotificationSolution; + _uri: string; + + (sid: string, ): NotificationContext; + get(sid: string, ): NotificationContext; + + + + + + /** + * Streams NotificationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: NotificationInstance, done: (err?: Error) => void) => void): void; + each(params: NotificationListInstanceEachOptions, callback?: (item: NotificationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams NotificationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: NotificationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: NotificationListInstanceEachOptions, callback?: (item: NotificationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of NotificationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: NotificationPage) => any): Promise; + /** + * Retrieve a single target page of NotificationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists NotificationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: NotificationInstance[]) => any): Promise; + list(params: NotificationListInstanceOptions, callback?: (error: Error | null, items: NotificationInstance[]) => any): Promise; + /** + * Lists NotificationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: NotificationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of NotificationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: NotificationPage) => any): Promise; + page(params: NotificationListInstancePageOptions, callback?: (error: Error | null, items: NotificationPage) => any): Promise; + /** + * Retrieve a single page of NotificationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NotificationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: NotificationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NotificationListInstance(version: V2010, accountSid: string): NotificationListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as NotificationListInstance; + + instance.get = function get(sid, ): NotificationContext { + return new NotificationContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Notifications.json`; + + instance.page = function page(params?: NotificationListInstancePageOptions | ((error: Error | null, items: NotificationPage) => any), callback?: (error: Error | null, items: NotificationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["log"] !== undefined) + data["Log"] = params["log"]; + if (params["messageDate"] !== undefined) + data["MessageDate"] = serialize.iso8601Date(params["messageDate"]); + if (params["messageDateBefore"] !== undefined) + data["MessageDate<"] = serialize.iso8601Date(params["messageDateBefore"]); + if (params["messageDateAfter"] !== undefined) + data["MessageDate>"] = serialize.iso8601Date(params["messageDateAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new NotificationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: NotificationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new NotificationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: NotificationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["log"] !== undefined) + data["Log"] = params["log"]; + if (params["messageDate"] !== undefined) + data["MessageDate"] = serialize.iso8601Date(params["messageDate"]); + if (params["messageDateBefore"] !== undefined) + data["MessageDate<"] = serialize.iso8601Date(params["messageDateBefore"]); + if (params["messageDateAfter"] !== undefined) + data["MessageDate>"] = serialize.iso8601Date(params["messageDateAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NotificationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NotificationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class NotificationPage extends Page { +/** +* Initialize the NotificationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: NotificationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of NotificationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: NotificationResource): NotificationInstance { + + return new NotificationInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/outgoingCallerId.ts b/rest/api/v2010/account/outgoingCallerId.ts new file mode 100644 index 000000000..4e80cf716 --- /dev/null +++ b/rest/api/v2010/account/outgoingCallerId.ts @@ -0,0 +1,828 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a OutgoingCallerIdInstance + */ +export interface OutgoingCallerIdContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; +} + +/** + * Options to pass to each + */ +export interface OutgoingCallerIdListInstanceEachOptions { + /** The phone number of the OutgoingCallerId resources to read. */ + "phoneNumber"?: string; + /** The string that identifies the OutgoingCallerId resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: OutgoingCallerIdInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface OutgoingCallerIdListInstanceOptions { + /** The phone number of the OutgoingCallerId resources to read. */ + "phoneNumber"?: string; + /** The string that identifies the OutgoingCallerId resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface OutgoingCallerIdListInstancePageOptions { + /** The phone number of the OutgoingCallerId resources to read. */ + "phoneNumber"?: string; + /** The string that identifies the OutgoingCallerId resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface OutgoingCallerIdContext { + + /** + * Remove a OutgoingCallerIdInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a OutgoingCallerIdInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a OutgoingCallerIdInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance + */ + fetch(callback?: (error: Error | null, item?: OutgoingCallerIdInstance) => any): Promise + + /** + * Fetch a OutgoingCallerIdInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a OutgoingCallerIdInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance + */ + update(callback?: (error: Error | null, item?: OutgoingCallerIdInstance) => any): Promise; + /** + * Update a OutgoingCallerIdInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance + */ + update(params: OutgoingCallerIdContextUpdateOptions, callback?: (error: Error | null, item?: OutgoingCallerIdInstance) => any): Promise; + + /** + * Update a OutgoingCallerIdInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a OutgoingCallerIdInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance with HTTP metadata + */ + updateWithHttpInfo(params: OutgoingCallerIdContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OutgoingCallerIdContextSolution { + "accountSid": string; + "sid": string; +} + +export class OutgoingCallerIdContextImpl implements OutgoingCallerIdContext { + protected _solution: OutgoingCallerIdContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/OutgoingCallerIds/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: OutgoingCallerIdInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OutgoingCallerIdInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new OutgoingCallerIdInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: OutgoingCallerIdContextUpdateOptions | ((error: Error | null, item?: OutgoingCallerIdInstance) => any),callback?: (error: Error | null, item?: OutgoingCallerIdInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new OutgoingCallerIdInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: OutgoingCallerIdContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new OutgoingCallerIdInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface OutgoingCallerIdPayload extends TwilioResponsePayload { + outgoing_caller_ids: OutgoingCallerIdResource[]; +} + +interface OutgoingCallerIdResource { + sid: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + account_sid: string; + phone_number: string; + uri: string; +} + +export class OutgoingCallerIdInstance { + protected _solution: OutgoingCallerIdContextSolution; + protected _context?: OutgoingCallerIdContext; + + constructor(protected _version: V2010, payload: OutgoingCallerIdResource, accountSid: string, sid?: string) { + + this.sid = (payload.sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.accountSid = (payload.account_sid); + this.phoneNumber = (payload.phone_number); + this.uri = (payload.uri); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The unique string that that we created to identify the OutgoingCallerId resource. + */ + sid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OutgoingCallerId resource. + */ + accountSid: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): OutgoingCallerIdContext { + this._context = this._context || new OutgoingCallerIdContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a OutgoingCallerIdInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a OutgoingCallerIdInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a OutgoingCallerIdInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance + */ + fetch(callback?: (error: Error | null, item?: OutgoingCallerIdInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a OutgoingCallerIdInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a OutgoingCallerIdInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance + */ + update(callback?: (error: Error | null, item?: OutgoingCallerIdInstance) => any): Promise; + /** + * Update a OutgoingCallerIdInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance + */ + update(params: OutgoingCallerIdContextUpdateOptions, callback?: (error: Error | null, item?: OutgoingCallerIdInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: OutgoingCallerIdInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a OutgoingCallerIdInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a OutgoingCallerIdInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutgoingCallerIdInstance with HTTP metadata + */ + updateWithHttpInfo(params: OutgoingCallerIdContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + accountSid: this.accountSid, + phoneNumber: this.phoneNumber, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OutgoingCallerIdSolution { + accountSid: string; +} + +export interface OutgoingCallerIdListInstance { + _version: V2010; + _solution: OutgoingCallerIdSolution; + _uri: string; + + (sid: string, ): OutgoingCallerIdContext; + get(sid: string, ): OutgoingCallerIdContext; + + + + + + + + + + /** + * Streams OutgoingCallerIdInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutgoingCallerIdListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: OutgoingCallerIdInstance, done: (err?: Error) => void) => void): void; + each(params: OutgoingCallerIdListInstanceEachOptions, callback?: (item: OutgoingCallerIdInstance, done: (err?: Error) => void) => void): void; + /** + * Streams OutgoingCallerIdInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutgoingCallerIdListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: OutgoingCallerIdInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: OutgoingCallerIdListInstanceEachOptions, callback?: (item: OutgoingCallerIdInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of OutgoingCallerIdInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: OutgoingCallerIdPage) => any): Promise; + /** + * Retrieve a single target page of OutgoingCallerIdInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists OutgoingCallerIdInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutgoingCallerIdListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: OutgoingCallerIdInstance[]) => any): Promise; + list(params: OutgoingCallerIdListInstanceOptions, callback?: (error: Error | null, items: OutgoingCallerIdInstance[]) => any): Promise; + /** + * Lists OutgoingCallerIdInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutgoingCallerIdListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: OutgoingCallerIdListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of OutgoingCallerIdInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutgoingCallerIdListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: OutgoingCallerIdPage) => any): Promise; + page(params: OutgoingCallerIdListInstancePageOptions, callback?: (error: Error | null, items: OutgoingCallerIdPage) => any): Promise; + /** + * Retrieve a single page of OutgoingCallerIdInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutgoingCallerIdListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: OutgoingCallerIdListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OutgoingCallerIdListInstance(version: V2010, accountSid: string): OutgoingCallerIdListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as OutgoingCallerIdListInstance; + + instance.get = function get(sid, ): OutgoingCallerIdContext { + return new OutgoingCallerIdContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/OutgoingCallerIds.json`; + + instance.page = function page(params?: OutgoingCallerIdListInstancePageOptions | ((error: Error | null, items: OutgoingCallerIdPage) => any), callback?: (error: Error | null, items: OutgoingCallerIdPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new OutgoingCallerIdPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: OutgoingCallerIdPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new OutgoingCallerIdPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: OutgoingCallerIdListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OutgoingCallerIdPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OutgoingCallerIdPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class OutgoingCallerIdPage extends Page { +/** +* Initialize the OutgoingCallerIdPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: OutgoingCallerIdSolution) { + super(version, response, solution); + } + + /** + * Build an instance of OutgoingCallerIdInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: OutgoingCallerIdResource): OutgoingCallerIdInstance { + + return new OutgoingCallerIdInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/queue.ts b/rest/api/v2010/account/queue.ts new file mode 100644 index 000000000..d276534b6 --- /dev/null +++ b/rest/api/v2010/account/queue.ts @@ -0,0 +1,948 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { MemberListInstance } from "./queue/member"; + + + + + +/** + * Options to pass to update a QueueInstance + */ +export interface QueueContextUpdateOptions { + /** A descriptive string that you created to describe this resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. */ + "maxSize"?: number; +} + +/** + * Options to pass to create a QueueInstance + */ +export interface QueueListInstanceCreateOptions { + /** A descriptive string that you created to describe this resource. It can be up to 64 characters long. */ + "friendlyName": string; + /** The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. */ + "maxSize"?: number; +} + +/** + * Options to pass to each + */ +export interface QueueListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: QueueInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface QueueListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface QueueListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface QueueContext { + members: MemberListInstance; + + /** + * Remove a QueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a QueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a QueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance + */ + fetch(callback?: (error: Error | null, item?: QueueInstance) => any): Promise + + /** + * Fetch a QueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a QueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance + */ + update(callback?: (error: Error | null, item?: QueueInstance) => any): Promise; + /** + * Update a QueueInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance + */ + update(params: QueueContextUpdateOptions, callback?: (error: Error | null, item?: QueueInstance) => any): Promise; + + /** + * Update a QueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a QueueInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance with HTTP metadata + */ + updateWithHttpInfo(params: QueueContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface QueueContextSolution { + "accountSid": string; + "sid": string; +} + +export class QueueContextImpl implements QueueContext { + protected _solution: QueueContextSolution; + protected _uri: string; + + protected _members?: MemberListInstance; + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Queues/${sid}.json`; + } + + get members(): MemberListInstance { + this._members = this._members || MemberListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._members; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: QueueInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new QueueInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new QueueInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: QueueContextUpdateOptions | ((error: Error | null, item?: QueueInstance) => any),callback?: (error: Error | null, item?: QueueInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["maxSize"] !== undefined) + data["MaxSize"] = params["maxSize"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new QueueInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: QueueContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["maxSize"] !== undefined) + data["MaxSize"] = params["maxSize"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new QueueInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface QueuePayload extends TwilioResponsePayload { + queues: QueueResource[]; +} + +interface QueueResource { + date_updated: Date; + current_size: number; + friendly_name: string; + uri: string; + account_sid: string; + average_wait_time: number; + sid: string; + date_created: Date; + max_size: number; +} + +export class QueueInstance { + protected _solution: QueueContextSolution; + protected _context?: QueueContext; + + constructor(protected _version: V2010, payload: QueueResource, accountSid: string, sid?: string) { + + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.currentSize = deserialize.integer(payload.current_size); + this.friendlyName = (payload.friendly_name); + this.uri = (payload.uri); + this.accountSid = (payload.account_sid); + this.averageWaitTime = deserialize.integer(payload.average_wait_time); + this.sid = (payload.sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.maxSize = deserialize.integer(payload.max_size); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The number of calls currently in the queue. + */ + currentSize: number; + /** + * A string that you assigned to describe this resource. + */ + friendlyName: string; + /** + * The URI of this resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Queue resource. + */ + accountSid: string; + /** + * The average wait time in seconds of the members in this queue. This is calculated at the time of the request. + */ + averageWaitTime: number; + /** + * The unique string that that we created to identify this Queue resource. + */ + sid: string; + /** + * The date and time in GMT that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The maximum number of calls that can be in the queue. The default is 1000 and the maximum is 5000. + */ + maxSize: number; + + private get _proxy(): QueueContext { + this._context = this._context || new QueueContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a QueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a QueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a QueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance + */ + fetch(callback?: (error: Error | null, item?: QueueInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a QueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a QueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance + */ + update(callback?: (error: Error | null, item?: QueueInstance) => any): Promise; + /** + * Update a QueueInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance + */ + update(params: QueueContextUpdateOptions, callback?: (error: Error | null, item?: QueueInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: QueueInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a QueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a QueueInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance with HTTP metadata + */ + updateWithHttpInfo(params: QueueContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the members. + */ + members(): MemberListInstance { + return this._proxy.members; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + dateUpdated: this.dateUpdated, + currentSize: this.currentSize, + friendlyName: this.friendlyName, + uri: this.uri, + accountSid: this.accountSid, + averageWaitTime: this.averageWaitTime, + sid: this.sid, + dateCreated: this.dateCreated, + maxSize: this.maxSize, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface QueueSolution { + accountSid: string; +} + +export interface QueueListInstance { + _version: V2010; + _solution: QueueSolution; + _uri: string; + + (sid: string, ): QueueContext; + get(sid: string, ): QueueContext; + + + + + + + + + /** + * Create a QueueInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance + */ + create(params: QueueListInstanceCreateOptions, callback?: (error: Error | null, item?: QueueInstance) => any): Promise; + + /** + * Create a QueueInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueueInstance with HTTP metadata + */ + createWithHttpInfo(params: QueueListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams QueueInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueueListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: QueueInstance, done: (err?: Error) => void) => void): void; + each(params: QueueListInstanceEachOptions, callback?: (item: QueueInstance, done: (err?: Error) => void) => void): void; + /** + * Streams QueueInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueueListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: QueueInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: QueueListInstanceEachOptions, callback?: (item: QueueInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of QueueInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: QueuePage) => any): Promise; + /** + * Retrieve a single target page of QueueInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists QueueInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueueListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: QueueInstance[]) => any): Promise; + list(params: QueueListInstanceOptions, callback?: (error: Error | null, items: QueueInstance[]) => any): Promise; + /** + * Lists QueueInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueueListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: QueueListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of QueueInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueueListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: QueuePage) => any): Promise; + page(params: QueueListInstancePageOptions, callback?: (error: Error | null, items: QueuePage) => any): Promise; + /** + * Retrieve a single page of QueueInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueueListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: QueueListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function QueueListInstance(version: V2010, accountSid: string): QueueListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as QueueListInstance; + + instance.get = function get(sid, ): QueueContext { + return new QueueContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Queues.json`; + + instance.create = function create(params: QueueListInstanceCreateOptions, callback?: (error: Error | null, items: QueueInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["maxSize"] !== undefined) + data["MaxSize"] = params["maxSize"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new QueueInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: QueueListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["maxSize"] !== undefined) + data["MaxSize"] = params["maxSize"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new QueueInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: QueueListInstancePageOptions | ((error: Error | null, items: QueuePage) => any), callback?: (error: Error | null, items: QueuePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new QueuePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: QueuePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new QueuePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: QueueListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new QueuePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new QueuePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class QueuePage extends Page { +/** +* Initialize the QueuePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: QueueSolution) { + super(version, response, solution); + } + + /** + * Build an instance of QueueInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: QueueResource): QueueInstance { + + return new QueueInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/queue/member.ts b/rest/api/v2010/account/queue/member.ts new file mode 100644 index 000000000..de7b2221e --- /dev/null +++ b/rest/api/v2010/account/queue/member.ts @@ -0,0 +1,710 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a MemberInstance + */ +export interface MemberContextUpdateOptions { + /** The absolute URL of the Queue resource. */ + "url": string; + /** How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. */ + "method"?: string; +} + +/** + * Options to pass to each + */ +export interface MemberListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MemberInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MemberListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MemberListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MemberContext { + + /** + * Fetch a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise + + /** + * Fetch a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + /** + * Update a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MemberContextSolution { + "accountSid": string; + "queueSid": string; + "callSid": string; +} + +export class MemberContextImpl implements MemberContext { + protected _solution: MemberContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, queueSid: string, callSid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(queueSid)) { + throw new Error('Parameter \'queueSid\' is not valid.'); + } + + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + this._solution = { accountSid, queueSid, callSid, }; + this._uri = `/Accounts/${accountSid}/Queues/${queueSid}/Members/${callSid}.json`; + } + + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.queueSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.queueSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: MemberContextUpdateOptions,callback?: (error: Error | null, item?: MemberInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["url"] === null || params["url"] === undefined) { + throw new Error('Required parameter "params[\'url\']" missing.'); + } + + let data: any = {}; + + + + data["Url"] = params["url"]; + if (params["method"] !== undefined) + data["Method"] = params["method"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.queueSid, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: MemberContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["url"] === null || params["url"] === undefined) { + throw new Error('Required parameter "params[\'url\']" missing.'); + } + + let data: any = {}; + + + + data["Url"] = params["url"]; + if (params["method"] !== undefined) + data["Method"] = params["method"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.queueSid, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MemberPayload extends TwilioResponsePayload { + queue_members: MemberResource[]; +} + +interface MemberResource { + call_sid: string; + date_enqueued: Date; + position: number; + uri: string; + wait_time: number; + queue_sid: string; +} + +export class MemberInstance { + protected _solution: MemberContextSolution; + protected _context?: MemberContext; + + constructor(protected _version: V2010, payload: MemberResource, accountSid: string, queueSid: string, callSid?: string) { + + this.callSid = (payload.call_sid); + this.dateEnqueued = deserialize.rfc2822DateTime(payload.date_enqueued); + this.position = deserialize.integer(payload.position); + this.uri = (payload.uri); + this.waitTime = deserialize.integer(payload.wait_time); + this.queueSid = (payload.queue_sid); + + this._solution = { accountSid, queueSid, callSid: callSid, }; + } + + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Member resource is associated with. + */ + callSid: string; + /** + * The date that the member was enqueued, given in RFC 2822 format. + */ + dateEnqueued: Date; + /** + * This member\'s current position in the queue. + */ + position: number; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The number of seconds the member has been in the queue. + */ + waitTime: number; + /** + * The SID of the Queue the member is in. + */ + queueSid: string; + + private get _proxy(): MemberContext { + this._context = this._context || new MemberContextImpl(this._version, this._solution.accountSid, this._solution.queueSid, this._solution.callSid); + return this._context; + } + + /** + * Fetch a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MemberInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + callSid: this.callSid, + dateEnqueued: this.dateEnqueued, + position: this.position, + uri: this.uri, + waitTime: this.waitTime, + queueSid: this.queueSid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MemberSolution { + accountSid: string; + queueSid: string; +} + +export interface MemberListInstance { + _version: V2010; + _solution: MemberSolution; + _uri: string; + + (callSid: string, ): MemberContext; + get(callSid: string, ): MemberContext; + + + + + + + + /** + * Streams MemberInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + each(params: MemberListInstanceEachOptions, callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MemberInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MemberListInstanceEachOptions, callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MemberInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MemberPage) => any): Promise; + /** + * Retrieve a single target page of MemberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MemberInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MemberInstance[]) => any): Promise; + list(params: MemberListInstanceOptions, callback?: (error: Error | null, items: MemberInstance[]) => any): Promise; + /** + * Lists MemberInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MemberListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MemberInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MemberPage) => any): Promise; + page(params: MemberListInstancePageOptions, callback?: (error: Error | null, items: MemberPage) => any): Promise; + /** + * Retrieve a single page of MemberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MemberListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MemberListInstance(version: V2010, accountSid: string, queueSid: string): MemberListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(queueSid)) { + throw new Error('Parameter \'queueSid\' is not valid.'); + } + + const instance = ((callSid, ) => instance.get(callSid, )) as MemberListInstance; + + instance.get = function get(callSid, ): MemberContext { + return new MemberContextImpl(version, accountSid, queueSid, callSid); + } + + instance._version = version; + instance._solution = { accountSid, queueSid, }; + instance._uri = `/Accounts/${accountSid}/Queues/${queueSid}/Members.json`; + + instance.page = function page(params?: MemberListInstancePageOptions | ((error: Error | null, items: MemberPage) => any), callback?: (error: Error | null, items: MemberPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MemberPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MemberPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MemberPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MemberListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MemberPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MemberPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MemberPage extends Page { +/** +* Initialize the MemberPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: MemberSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MemberInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MemberResource): MemberInstance { + + return new MemberInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.queueSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/recording.ts b/rest/api/v2010/account/recording.ts new file mode 100644 index 000000000..fba8d18a2 --- /dev/null +++ b/rest/api/v2010/account/recording.ts @@ -0,0 +1,902 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { AddOnResultListInstance } from "./recording/addOnResult"; +import { TranscriptionListInstance } from "./recording/transcription"; + + +/** + * How the recording was created. Can be: `DialVerb`, `Conference`, `OutboundAPI`, `Trunking`, `RecordVerb`, `StartCallRecordingAPI`, and `StartConferenceRecordingAPI`. + */ +export type RecordingSource = 'DialVerb'|'Conference'|'OutboundAPI'|'Trunking'|'RecordVerb'|'StartCallRecordingAPI'|'StartConferenceRecordingAPI'; + +/** + * The status of the recording. Can be: `processing`, `completed`, `absent` or `deleted`. For information about more detailed statuses on in-progress recordings, check out how to [Update a Recording Resource](https://www.twilio.com/docs/voice/api/recording#update-a-recording-resource). + */ +export type RecordingStatus = 'in-progress'|'paused'|'stopped'|'processing'|'completed'|'absent'|'deleted'; + + + +/** + * Options to pass to fetch a RecordingInstance + */ +export interface RecordingContextFetchOptions { + /** A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. */ + "includeSoftDeleted"?: boolean; +} + +/** + * Options to pass to each + */ +export interface RecordingListInstanceEachOptions { + /** Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. */ + "dateCreated"?: Date; + /** Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. */ + "dateCreatedBefore"?: Date; + /** Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. */ + "dateCreatedAfter"?: Date; + /** The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. */ + "callSid"?: string; + /** The Conference SID that identifies the conference associated with the recording to read. */ + "conferenceSid"?: string; + /** A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. */ + "includeSoftDeleted"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RecordingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RecordingListInstanceOptions { + /** Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. */ + "dateCreated"?: Date; + /** Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. */ + "dateCreatedBefore"?: Date; + /** Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. */ + "dateCreatedAfter"?: Date; + /** The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. */ + "callSid"?: string; + /** The Conference SID that identifies the conference associated with the recording to read. */ + "conferenceSid"?: string; + /** A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. */ + "includeSoftDeleted"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RecordingListInstancePageOptions { + /** Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. */ + "dateCreated"?: Date; + /** Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. */ + "dateCreatedBefore"?: Date; + /** Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. */ + "dateCreatedAfter"?: Date; + /** The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. */ + "callSid"?: string; + /** The Conference SID that identifies the conference associated with the recording to read. */ + "conferenceSid"?: string; + /** A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. */ + "includeSoftDeleted"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RecordingContext { + addOnResults: AddOnResultListInstance; + transcriptions: TranscriptionListInstance; + + /** + * Remove a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise; + /** + * Fetch a RecordingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(params: RecordingContextFetchOptions, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise; + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(params: RecordingContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RecordingContextSolution { + "accountSid": string; + "sid": string; +} + +export class RecordingContextImpl implements RecordingContext { + protected _solution: RecordingContextSolution; + protected _uri: string; + + protected _addOnResults?: AddOnResultListInstance; + protected _transcriptions?: TranscriptionListInstance; + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Recordings/${sid}.json`; + } + + get addOnResults(): AddOnResultListInstance { + this._addOnResults = this._addOnResults || AddOnResultListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._addOnResults; + } + + get transcriptions(): TranscriptionListInstance { + this._transcriptions = this._transcriptions || TranscriptionListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._transcriptions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(params?: RecordingContextFetchOptions | ((error: Error | null, item?: RecordingInstance) => any),callback?: (error: Error | null, item?: RecordingInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["includeSoftDeleted"] !== undefined) + data["IncludeSoftDeleted"] = serialize.bool(params["includeSoftDeleted"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: RecordingContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["includeSoftDeleted"] !== undefined) + data["IncludeSoftDeleted"] = serialize.bool(params["includeSoftDeleted"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RecordingPayload extends TwilioResponsePayload { + recordings: RecordingResource[]; +} + +interface RecordingResource { + account_sid: string; + api_version: string; + call_sid: string; + conference_sid: string; + date_created: Date; + date_updated: Date; + start_time: Date; + duration: string; + sid: string; + price: string; + price_unit: string; + status: RecordingStatus; + channels: number; + source: RecordingSource; + error_code: number; + uri: string; + encryption_details: any; + subresource_uris: Record; + media_url: string; +} + +export class RecordingInstance { + protected _solution: RecordingContextSolution; + protected _context?: RecordingContext; + + constructor(protected _version: V2010, payload: RecordingResource, accountSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.callSid = (payload.call_sid); + this.conferenceSid = (payload.conference_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.startTime = deserialize.rfc2822DateTime(payload.start_time); + this.duration = (payload.duration); + this.sid = (payload.sid); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.status = payload.status; + this.channels = deserialize.integer(payload.channels); + this.source = payload.source; + this.errorCode = deserialize.integer(payload.error_code); + this.uri = (payload.uri); + this.encryptionDetails = (payload.encryption_details); + this.subresourceUris = (payload.subresource_uris); + this.mediaUrl = (payload.media_url); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource. + */ + accountSid: string; + /** + * The API version used during the recording. + */ + apiVersion: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Recording resource is associated with. This will always refer to the parent leg of a two-leg call. + */ + callSid: string; + /** + * The Conference SID that identifies the conference associated with the recording, if a conference recording. + */ + conferenceSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + startTime: Date; + /** + * The length of the recording in seconds. + */ + duration: string; + /** + * The unique string that that we created to identify the Recording resource. + */ + sid: string; + /** + * The one-time cost of creating the recording in the `price_unit` currency. + */ + price: string; + /** + * The currency used in the `price` property. Example: `USD`. + */ + priceUnit: string; + status: RecordingStatus; + /** + * The number of channels in the recording resource. For information on specifying the number of channels in the downloaded recording file, check out [Fetch a Recording’s media file](https://www.twilio.com/docs/voice/api/recording#download-dual-channel-media-file). + */ + channels: number; + source: RecordingSource; + /** + * The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + */ + errorCode: number; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + */ + encryptionDetails: any; + /** + * A list of related resources identified by their relative URIs. + */ + subresourceUris: Record; + /** + * The URL of the media file associated with this recording resource. When stored externally, this is the full URL location of the media file. + */ + mediaUrl: string; + + private get _proxy(): RecordingContext { + this._context = this._context || new RecordingContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise; + /** + * Fetch a RecordingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(params: RecordingContextFetchOptions, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(params: RecordingContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Access the addOnResults. + */ + addOnResults(): AddOnResultListInstance { + return this._proxy.addOnResults; + } + + /** + * Access the transcriptions. + */ + transcriptions(): TranscriptionListInstance { + return this._proxy.transcriptions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + callSid: this.callSid, + conferenceSid: this.conferenceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + startTime: this.startTime, + duration: this.duration, + sid: this.sid, + price: this.price, + priceUnit: this.priceUnit, + status: this.status, + channels: this.channels, + source: this.source, + errorCode: this.errorCode, + uri: this.uri, + encryptionDetails: this.encryptionDetails, + subresourceUris: this.subresourceUris, + mediaUrl: this.mediaUrl, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RecordingSolution { + accountSid: string; +} + +export interface RecordingListInstance { + _version: V2010; + _solution: RecordingSolution; + _uri: string; + + (sid: string, ): RecordingContext; + get(sid: string, ): RecordingContext; + + + + + + + + /** + * Streams RecordingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + each(params: RecordingListInstanceEachOptions, callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RecordingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RecordingListInstanceEachOptions, callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RecordingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RecordingPage) => any): Promise; + /** + * Retrieve a single target page of RecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RecordingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RecordingInstance[]) => any): Promise; + list(params: RecordingListInstanceOptions, callback?: (error: Error | null, items: RecordingInstance[]) => any): Promise; + /** + * Lists RecordingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RecordingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RecordingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RecordingPage) => any): Promise; + page(params: RecordingListInstancePageOptions, callback?: (error: Error | null, items: RecordingPage) => any): Promise; + /** + * Retrieve a single page of RecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RecordingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RecordingListInstance(version: V2010, accountSid: string): RecordingListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RecordingListInstance; + + instance.get = function get(sid, ): RecordingContext { + return new RecordingContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Recordings.json`; + + instance.page = function page(params?: RecordingListInstancePageOptions | ((error: Error | null, items: RecordingPage) => any), callback?: (error: Error | null, items: RecordingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreated<"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreated>"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["callSid"] !== undefined) + data["CallSid"] = params["callSid"]; + if (params["conferenceSid"] !== undefined) + data["ConferenceSid"] = params["conferenceSid"]; + if (params["includeSoftDeleted"] !== undefined) + data["IncludeSoftDeleted"] = serialize.bool(params["includeSoftDeleted"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RecordingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RecordingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RecordingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RecordingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreated<"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreated>"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["callSid"] !== undefined) + data["CallSid"] = params["callSid"]; + if (params["conferenceSid"] !== undefined) + data["ConferenceSid"] = params["conferenceSid"]; + if (params["includeSoftDeleted"] !== undefined) + data["IncludeSoftDeleted"] = serialize.bool(params["includeSoftDeleted"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RecordingPage extends Page { +/** +* Initialize the RecordingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: RecordingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RecordingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RecordingResource): RecordingInstance { + + return new RecordingInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/recording/addOnResult.ts b/rest/api/v2010/account/recording/addOnResult.ts new file mode 100644 index 000000000..44dd234c6 --- /dev/null +++ b/rest/api/v2010/account/recording/addOnResult.ts @@ -0,0 +1,696 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { PayloadListInstance } from "./addOnResult/payload"; + + +/** + * The status of the result. Can be: `canceled`, `completed`, `deleted`, `failed`, `in-progress`, `init`, `processing`, `queued`. + */ +export type AddOnResultStatus = 'canceled'|'completed'|'deleted'|'failed'|'in-progress'|'init'|'processing'|'queued'; + + + + +/** + * Options to pass to each + */ +export interface AddOnResultListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AddOnResultInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AddOnResultListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AddOnResultListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AddOnResultContext { + payloads: PayloadListInstance; + + /** + * Remove a AddOnResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AddOnResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a AddOnResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddOnResultInstance + */ + fetch(callback?: (error: Error | null, item?: AddOnResultInstance) => any): Promise + + /** + * Fetch a AddOnResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddOnResultInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AddOnResultContextSolution { + "accountSid": string; + "referenceSid": string; + "sid": string; +} + +export class AddOnResultContextImpl implements AddOnResultContext { + protected _solution: AddOnResultContextSolution; + protected _uri: string; + + protected _payloads?: PayloadListInstance; + + constructor(protected _version: V2010, accountSid: string, referenceSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(referenceSid)) { + throw new Error('Parameter \'referenceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, referenceSid, sid, }; + this._uri = `/Accounts/${accountSid}/Recordings/${referenceSid}/AddOnResults/${sid}.json`; + } + + get payloads(): PayloadListInstance { + this._payloads = this._payloads || PayloadListInstance(this._version, this._solution.accountSid, this._solution.referenceSid, this._solution.sid); + return this._payloads; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AddOnResultInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AddOnResultInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.referenceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AddOnResultInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.referenceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AddOnResultPayload extends TwilioResponsePayload { + add_on_results: AddOnResultResource[]; +} + +interface AddOnResultResource { + sid: string; + account_sid: string; + status: AddOnResultStatus; + add_on_sid: string; + add_on_configuration_sid: string; + date_created: Date; + date_updated: Date; + date_completed: Date; + reference_sid: string; + subresource_uris: Record; +} + +export class AddOnResultInstance { + protected _solution: AddOnResultContextSolution; + protected _context?: AddOnResultContext; + + constructor(protected _version: V2010, payload: AddOnResultResource, accountSid: string, referenceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.status = payload.status; + this.addOnSid = (payload.add_on_sid); + this.addOnConfigurationSid = (payload.add_on_configuration_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.dateCompleted = deserialize.rfc2822DateTime(payload.date_completed); + this.referenceSid = (payload.reference_sid); + this.subresourceUris = (payload.subresource_uris); + + this._solution = { accountSid, referenceSid, sid: sid, }; + } + + /** + * The unique string that that we created to identify the Recording AddOnResult resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult resource. + */ + accountSid: string; + status: AddOnResultStatus; + /** + * The SID of the Add-on to which the result belongs. + */ + addOnSid: string; + /** + * The SID of the Add-on configuration. + */ + addOnConfigurationSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The date and time in GMT that the result was completed specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCompleted: Date; + /** + * The SID of the recording to which the AddOnResult resource belongs. + */ + referenceSid: string; + /** + * A list of related resources identified by their relative URIs. + */ + subresourceUris: Record; + + private get _proxy(): AddOnResultContext { + this._context = this._context || new AddOnResultContextImpl(this._version, this._solution.accountSid, this._solution.referenceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a AddOnResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AddOnResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AddOnResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddOnResultInstance + */ + fetch(callback?: (error: Error | null, item?: AddOnResultInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AddOnResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddOnResultInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the payloads. + */ + payloads(): PayloadListInstance { + return this._proxy.payloads; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + status: this.status, + addOnSid: this.addOnSid, + addOnConfigurationSid: this.addOnConfigurationSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + dateCompleted: this.dateCompleted, + referenceSid: this.referenceSid, + subresourceUris: this.subresourceUris, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AddOnResultSolution { + accountSid: string; + referenceSid: string; +} + +export interface AddOnResultListInstance { + _version: V2010; + _solution: AddOnResultSolution; + _uri: string; + + (sid: string, ): AddOnResultContext; + get(sid: string, ): AddOnResultContext; + + + + + + + + /** + * Streams AddOnResultInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddOnResultListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AddOnResultInstance, done: (err?: Error) => void) => void): void; + each(params: AddOnResultListInstanceEachOptions, callback?: (item: AddOnResultInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AddOnResultInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddOnResultListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AddOnResultInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AddOnResultListInstanceEachOptions, callback?: (item: AddOnResultInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AddOnResultInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AddOnResultPage) => any): Promise; + /** + * Retrieve a single target page of AddOnResultInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AddOnResultInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddOnResultListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AddOnResultInstance[]) => any): Promise; + list(params: AddOnResultListInstanceOptions, callback?: (error: Error | null, items: AddOnResultInstance[]) => any): Promise; + /** + * Lists AddOnResultInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddOnResultListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AddOnResultListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AddOnResultInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddOnResultListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AddOnResultPage) => any): Promise; + page(params: AddOnResultListInstancePageOptions, callback?: (error: Error | null, items: AddOnResultPage) => any): Promise; + /** + * Retrieve a single page of AddOnResultInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddOnResultListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AddOnResultListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AddOnResultListInstance(version: V2010, accountSid: string, referenceSid: string): AddOnResultListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(referenceSid)) { + throw new Error('Parameter \'referenceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as AddOnResultListInstance; + + instance.get = function get(sid, ): AddOnResultContext { + return new AddOnResultContextImpl(version, accountSid, referenceSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, referenceSid, }; + instance._uri = `/Accounts/${accountSid}/Recordings/${referenceSid}/AddOnResults.json`; + + instance.page = function page(params?: AddOnResultListInstancePageOptions | ((error: Error | null, items: AddOnResultPage) => any), callback?: (error: Error | null, items: AddOnResultPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AddOnResultPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AddOnResultPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AddOnResultPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AddOnResultListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AddOnResultPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AddOnResultPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AddOnResultPage extends Page { +/** +* Initialize the AddOnResultPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AddOnResultSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AddOnResultInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AddOnResultResource): AddOnResultInstance { + + return new AddOnResultInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.referenceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/recording/addOnResult/payload.ts b/rest/api/v2010/account/recording/addOnResult/payload.ts new file mode 100644 index 000000000..db692657b --- /dev/null +++ b/rest/api/v2010/account/recording/addOnResult/payload.ts @@ -0,0 +1,712 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../../base/Page"; +import Response from "../../../../../../http/response"; +import V2010 from "../../../../V2010"; +const deserialize = require("../../../../../../base/deserialize"); +const serialize = require("../../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../../base/utility"; +import { ApiResponse } from "../../../../../../base/ApiResponse"; +import { DataListInstance } from "./payload/data"; + + + + + +/** + * Options to pass to each + */ +export interface PayloadListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PayloadInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PayloadListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PayloadListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PayloadContext { + data: DataListInstance; + + /** + * Remove a PayloadInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a PayloadInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a PayloadInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PayloadInstance + */ + fetch(callback?: (error: Error | null, item?: PayloadInstance) => any): Promise + + /** + * Fetch a PayloadInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PayloadInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PayloadContextSolution { + "accountSid": string; + "referenceSid": string; + "addOnResultSid": string; + "sid": string; +} + +export class PayloadContextImpl implements PayloadContext { + protected _solution: PayloadContextSolution; + protected _uri: string; + + protected _data?: DataListInstance; + + constructor(protected _version: V2010, accountSid: string, referenceSid: string, addOnResultSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(referenceSid)) { + throw new Error('Parameter \'referenceSid\' is not valid.'); + } + + if (!isValidPathParam(addOnResultSid)) { + throw new Error('Parameter \'addOnResultSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, referenceSid, addOnResultSid, sid, }; + this._uri = `/Accounts/${accountSid}/Recordings/${referenceSid}/AddOnResults/${addOnResultSid}/Payloads/${sid}.json`; + } + + get data(): DataListInstance { + this._data = this._data || DataListInstance(this._version, this._solution.accountSid, this._solution.referenceSid, this._solution.addOnResultSid, this._solution.sid); + return this._data; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: PayloadInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PayloadInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.referenceSid, instance._solution.addOnResultSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new PayloadInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.referenceSid, instance._solution.addOnResultSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PayloadPayload extends TwilioResponsePayload { + payloads: PayloadResource[]; +} + +interface PayloadResource { + sid: string; + add_on_result_sid: string; + account_sid: string; + label: string; + add_on_sid: string; + add_on_configuration_sid: string; + content_type: string; + date_created: Date; + date_updated: Date; + reference_sid: string; + subresource_uris: Record; +} + +export class PayloadInstance { + protected _solution: PayloadContextSolution; + protected _context?: PayloadContext; + + constructor(protected _version: V2010, payload: PayloadResource, accountSid: string, referenceSid: string, addOnResultSid: string, sid?: string) { + + this.sid = (payload.sid); + this.addOnResultSid = (payload.add_on_result_sid); + this.accountSid = (payload.account_sid); + this.label = (payload.label); + this.addOnSid = (payload.add_on_sid); + this.addOnConfigurationSid = (payload.add_on_configuration_sid); + this.contentType = (payload.content_type); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.referenceSid = (payload.reference_sid); + this.subresourceUris = (payload.subresource_uris); + + this._solution = { accountSid, referenceSid, addOnResultSid, sid: sid, }; + } + + /** + * The unique string that that we created to identify the Recording AddOnResult Payload resource. + */ + sid: string; + /** + * The SID of the AddOnResult to which the payload belongs. + */ + addOnResultSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resource. + */ + accountSid: string; + /** + * The string provided by the vendor that describes the payload. + */ + label: string; + /** + * The SID of the Add-on to which the result belongs. + */ + addOnSid: string; + /** + * The SID of the Add-on configuration. + */ + addOnConfigurationSid: string; + /** + * The MIME type of the payload. + */ + contentType: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The SID of the recording to which the AddOnResult resource that contains the payload belongs. + */ + referenceSid: string; + /** + * A list of related resources identified by their relative URIs. + */ + subresourceUris: Record; + + private get _proxy(): PayloadContext { + this._context = this._context || new PayloadContextImpl(this._version, this._solution.accountSid, this._solution.referenceSid, this._solution.addOnResultSid, this._solution.sid); + return this._context; + } + + /** + * Remove a PayloadInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a PayloadInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a PayloadInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PayloadInstance + */ + fetch(callback?: (error: Error | null, item?: PayloadInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PayloadInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PayloadInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the data. + */ + data(): DataListInstance { + return this._proxy.data; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + addOnResultSid: this.addOnResultSid, + accountSid: this.accountSid, + label: this.label, + addOnSid: this.addOnSid, + addOnConfigurationSid: this.addOnConfigurationSid, + contentType: this.contentType, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + referenceSid: this.referenceSid, + subresourceUris: this.subresourceUris, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PayloadSolution { + accountSid: string; + referenceSid: string; + addOnResultSid: string; +} + +export interface PayloadListInstance { + _version: V2010; + _solution: PayloadSolution; + _uri: string; + + (sid: string, ): PayloadContext; + get(sid: string, ): PayloadContext; + + + + + + + + /** + * Streams PayloadInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PayloadListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PayloadInstance, done: (err?: Error) => void) => void): void; + each(params: PayloadListInstanceEachOptions, callback?: (item: PayloadInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PayloadInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PayloadListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PayloadInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PayloadListInstanceEachOptions, callback?: (item: PayloadInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PayloadInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PayloadPage) => any): Promise; + /** + * Retrieve a single target page of PayloadInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists PayloadInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PayloadListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PayloadInstance[]) => any): Promise; + list(params: PayloadListInstanceOptions, callback?: (error: Error | null, items: PayloadInstance[]) => any): Promise; + /** + * Lists PayloadInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PayloadListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: PayloadListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of PayloadInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PayloadListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PayloadPage) => any): Promise; + page(params: PayloadListInstancePageOptions, callback?: (error: Error | null, items: PayloadPage) => any): Promise; + /** + * Retrieve a single page of PayloadInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PayloadListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: PayloadListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PayloadListInstance(version: V2010, accountSid: string, referenceSid: string, addOnResultSid: string): PayloadListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(referenceSid)) { + throw new Error('Parameter \'referenceSid\' is not valid.'); + } + + if (!isValidPathParam(addOnResultSid)) { + throw new Error('Parameter \'addOnResultSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as PayloadListInstance; + + instance.get = function get(sid, ): PayloadContext { + return new PayloadContextImpl(version, accountSid, referenceSid, addOnResultSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, referenceSid, addOnResultSid, }; + instance._uri = `/Accounts/${accountSid}/Recordings/${referenceSid}/AddOnResults/${addOnResultSid}/Payloads.json`; + + instance.page = function page(params?: PayloadListInstancePageOptions | ((error: Error | null, items: PayloadPage) => any), callback?: (error: Error | null, items: PayloadPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PayloadPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PayloadPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PayloadPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PayloadListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PayloadPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PayloadPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PayloadPage extends Page { +/** +* Initialize the PayloadPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: PayloadSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PayloadInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PayloadResource): PayloadInstance { + + return new PayloadInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.referenceSid, + this._solution.addOnResultSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/recording/addOnResult/payload/data.ts b/rest/api/v2010/account/recording/addOnResult/payload/data.ts new file mode 100644 index 000000000..d2acff18e --- /dev/null +++ b/rest/api/v2010/account/recording/addOnResult/payload/data.ts @@ -0,0 +1,269 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../../../../V2010"; +const deserialize = require("../../../../../../../base/deserialize"); +const serialize = require("../../../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../../../base/utility"; +import { ApiResponse } from "../../../../../../../base/ApiResponse"; + + + + +export interface DataContext { + + /** + * Fetch a DataInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataInstance + */ + fetch(callback?: (error: Error | null, item?: DataInstance) => any): Promise + + /** + * Fetch a DataInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DataContextSolution { + "accountSid": string; + "referenceSid": string; + "addOnResultSid": string; + "payloadSid": string; +} + +export class DataContextImpl implements DataContext { + protected _solution: DataContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, referenceSid: string, addOnResultSid: string, payloadSid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(referenceSid)) { + throw new Error('Parameter \'referenceSid\' is not valid.'); + } + + if (!isValidPathParam(addOnResultSid)) { + throw new Error('Parameter \'addOnResultSid\' is not valid.'); + } + + if (!isValidPathParam(payloadSid)) { + throw new Error('Parameter \'payloadSid\' is not valid.'); + } + + this._solution = { accountSid, referenceSid, addOnResultSid, payloadSid, }; + this._uri = `/Accounts/${accountSid}/Recordings/${referenceSid}/AddOnResults/${addOnResultSid}/Payloads/${payloadSid}/Data.json`; + } + + fetch(callback?: (error: Error | null, item?: DataInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DataInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.referenceSid, instance._solution.addOnResultSid, instance._solution.payloadSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new DataInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.referenceSid, instance._solution.addOnResultSid, instance._solution.payloadSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DataPayload extends DataResource {} + +interface DataResource { + redirect_to: string; +} + +export class DataInstance { + protected _solution: DataContextSolution; + protected _context?: DataContext; + + constructor(protected _version: V2010, payload: DataResource, accountSid: string, referenceSid: string, addOnResultSid: string, payloadSid: string) { + + this.redirectTo = (payload.redirect_to); + + this._solution = { accountSid, referenceSid, addOnResultSid, payloadSid, }; + } + + /** + * The URL to redirect to to get the data returned by the AddOn that was previously stored. + */ + redirectTo: string; + + private get _proxy(): DataContext { + this._context = this._context || new DataContextImpl(this._version, this._solution.accountSid, this._solution.referenceSid, this._solution.addOnResultSid, this._solution.payloadSid); + return this._context; + } + + /** + * Fetch a DataInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataInstance + */ + fetch(callback?: (error: Error | null, item?: DataInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DataInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + redirectTo: this.redirectTo, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DataSolution { + accountSid: string; + referenceSid: string; + addOnResultSid: string; + payloadSid: string; +} + +export interface DataListInstance { + _version: V2010; + _solution: DataSolution; + _uri: string; + + (): DataContext; + get(): DataContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DataListInstance(version: V2010, accountSid: string, referenceSid: string, addOnResultSid: string, payloadSid: string): DataListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(referenceSid)) { + throw new Error('Parameter \'referenceSid\' is not valid.'); + } + + if (!isValidPathParam(addOnResultSid)) { + throw new Error('Parameter \'addOnResultSid\' is not valid.'); + } + + if (!isValidPathParam(payloadSid)) { + throw new Error('Parameter \'payloadSid\' is not valid.'); + } + + const instance = (() => instance.get()) as DataListInstance; + + instance.get = function get(): DataContext { + return new DataContextImpl(version, accountSid, referenceSid, addOnResultSid, payloadSid); + } + + instance._version = version; + instance._solution = { accountSid, referenceSid, addOnResultSid, payloadSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/api/v2010/account/recording/transcription.ts b/rest/api/v2010/account/recording/transcription.ts new file mode 100644 index 000000000..d7592a678 --- /dev/null +++ b/rest/api/v2010/account/recording/transcription.ts @@ -0,0 +1,702 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2010 from "../../../V2010"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The status of the transcription. Can be: `in-progress`, `completed`, `failed`. + */ +export type TranscriptionStatus = 'in-progress'|'completed'|'failed'; + + + + +/** + * Options to pass to each + */ +export interface TranscriptionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TranscriptionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TranscriptionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TranscriptionContext { + + /** + * Remove a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise + + /** + * Fetch a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TranscriptionContextSolution { + "accountSid": string; + "recordingSid": string; + "sid": string; +} + +export class TranscriptionContextImpl implements TranscriptionContext { + protected _solution: TranscriptionContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, recordingSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(recordingSid)) { + throw new Error('Parameter \'recordingSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, recordingSid, sid, }; + this._uri = `/Accounts/${accountSid}/Recordings/${recordingSid}/Transcriptions/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.recordingSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new TranscriptionInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.recordingSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TranscriptionPayload extends TwilioResponsePayload { + transcriptions: TranscriptionResource[]; +} + +interface TranscriptionResource { + account_sid: string; + api_version: string; + date_created: Date; + date_updated: Date; + duration: string; + price: number; + price_unit: string; + recording_sid: string; + sid: string; + status: TranscriptionStatus; + transcription_text: string; + type: string; + uri: string; +} + +export class TranscriptionInstance { + protected _solution: TranscriptionContextSolution; + protected _context?: TranscriptionContext; + + constructor(protected _version: V2010, payload: TranscriptionResource, accountSid: string, recordingSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.duration = (payload.duration); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.recordingSid = (payload.recording_sid); + this.sid = (payload.sid); + this.status = payload.status; + this.transcriptionText = (payload.transcription_text); + this.type = (payload.type); + this.uri = (payload.uri); + + this._solution = { accountSid, recordingSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource. + */ + accountSid: string; + /** + * The API version used to create the transcription. + */ + apiVersion: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The duration of the transcribed audio in seconds. + */ + duration: string; + /** + * The charge for the transcript in the currency associated with the account. This value is populated after the transcript is complete so it may not be available immediately. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + */ + priceUnit: string; + /** + * The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) from which the transcription was created. + */ + recordingSid: string; + /** + * The unique string that that we created to identify the Transcription resource. + */ + sid: string; + status: TranscriptionStatus; + /** + * The text content of the transcription. + */ + transcriptionText: string; + /** + * The transcription type. + */ + type: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): TranscriptionContext { + this._context = this._context || new TranscriptionContextImpl(this._version, this._solution.accountSid, this._solution.recordingSid, this._solution.sid); + return this._context; + } + + /** + * Remove a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + duration: this.duration, + price: this.price, + priceUnit: this.priceUnit, + recordingSid: this.recordingSid, + sid: this.sid, + status: this.status, + transcriptionText: this.transcriptionText, + type: this.type, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TranscriptionSolution { + accountSid: string; + recordingSid: string; +} + +export interface TranscriptionListInstance { + _version: V2010; + _solution: TranscriptionSolution; + _uri: string; + + (sid: string, ): TranscriptionContext; + get(sid: string, ): TranscriptionContext; + + + + + + + + /** + * Streams TranscriptionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + each(params: TranscriptionListInstanceEachOptions, callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TranscriptionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TranscriptionListInstanceEachOptions, callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TranscriptionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TranscriptionPage) => any): Promise; + /** + * Retrieve a single target page of TranscriptionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists TranscriptionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TranscriptionInstance[]) => any): Promise; + list(params: TranscriptionListInstanceOptions, callback?: (error: Error | null, items: TranscriptionInstance[]) => any): Promise; + /** + * Lists TranscriptionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: TranscriptionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of TranscriptionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TranscriptionPage) => any): Promise; + page(params: TranscriptionListInstancePageOptions, callback?: (error: Error | null, items: TranscriptionPage) => any): Promise; + /** + * Retrieve a single page of TranscriptionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: TranscriptionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TranscriptionListInstance(version: V2010, accountSid: string, recordingSid: string): TranscriptionListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(recordingSid)) { + throw new Error('Parameter \'recordingSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as TranscriptionListInstance; + + instance.get = function get(sid, ): TranscriptionContext { + return new TranscriptionContextImpl(version, accountSid, recordingSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, recordingSid, }; + instance._uri = `/Accounts/${accountSid}/Recordings/${recordingSid}/Transcriptions.json`; + + instance.page = function page(params?: TranscriptionListInstancePageOptions | ((error: Error | null, items: TranscriptionPage) => any), callback?: (error: Error | null, items: TranscriptionPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TranscriptionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TranscriptionPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TranscriptionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TranscriptionListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TranscriptionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TranscriptionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TranscriptionPage extends Page { +/** +* Initialize the TranscriptionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: TranscriptionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TranscriptionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TranscriptionResource): TranscriptionInstance { + + return new TranscriptionInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.recordingSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/shortCode.ts b/rest/api/v2010/account/shortCode.ts new file mode 100644 index 000000000..8c42ba300 --- /dev/null +++ b/rest/api/v2010/account/shortCode.ts @@ -0,0 +1,815 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a ShortCodeInstance + */ +export interface ShortCodeContextUpdateOptions { + /** A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. */ + "friendlyName"?: string; + /** The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. */ + "apiVersion"?: string; + /** The URL we should call when receiving an incoming SMS message to this short code. */ + "smsUrl"?: string; + /** The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. */ + "smsMethod"?: string; + /** The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. */ + "smsFallbackUrl"?: string; + /** The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. */ + "smsFallbackMethod"?: string; +} + +/** + * Options to pass to each + */ +export interface ShortCodeListInstanceEachOptions { + /** The string that identifies the ShortCode resources to read. */ + "friendlyName"?: string; + /** Only show the ShortCode resources that match this pattern. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "shortCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ShortCodeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ShortCodeListInstanceOptions { + /** The string that identifies the ShortCode resources to read. */ + "friendlyName"?: string; + /** Only show the ShortCode resources that match this pattern. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "shortCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ShortCodeListInstancePageOptions { + /** The string that identifies the ShortCode resources to read. */ + "friendlyName"?: string; + /** Only show the ShortCode resources that match this pattern. You can specify partial numbers and use \'*\' as a wildcard for any digit. */ + "shortCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ShortCodeContext { + + /** + * Fetch a ShortCodeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance + */ + fetch(callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise + + /** + * Fetch a ShortCodeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ShortCodeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance + */ + update(callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise; + /** + * Update a ShortCodeInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance + */ + update(params: ShortCodeContextUpdateOptions, callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise; + + /** + * Update a ShortCodeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ShortCodeInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance with HTTP metadata + */ + updateWithHttpInfo(params: ShortCodeContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ShortCodeContextSolution { + "accountSid": string; + "sid": string; +} + +export class ShortCodeContextImpl implements ShortCodeContext { + protected _solution: ShortCodeContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/SMS/ShortCodes/${sid}.json`; + } + + fetch(callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ShortCodeInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ShortCodeInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ShortCodeContextUpdateOptions | ((error: Error | null, item?: ShortCodeInstance) => any),callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ShortCodeInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ShortCodeContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["apiVersion"] !== undefined) + data["ApiVersion"] = params["apiVersion"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ShortCodeInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ShortCodePayload extends TwilioResponsePayload { + short_codes: ShortCodeResource[]; +} + +interface ShortCodeResource { + account_sid: string; + api_version: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + short_code: string; + sid: string; + sms_fallback_method: string; + sms_fallback_url: string; + sms_method: string; + sms_url: string; + uri: string; +} + +export class ShortCodeInstance { + protected _solution: ShortCodeContextSolution; + protected _context?: ShortCodeContext; + + constructor(protected _version: V2010, payload: ShortCodeResource, accountSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.shortCode = (payload.short_code); + this.sid = (payload.sid); + this.smsFallbackMethod = (payload.sms_fallback_method); + this.smsFallbackUrl = (payload.sms_fallback_url); + this.smsMethod = (payload.sms_method); + this.smsUrl = (payload.sms_url); + this.uri = (payload.uri); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this ShortCode resource. + */ + accountSid: string; + /** + * The API version used to start a new TwiML session when an SMS message is sent to this short code. + */ + apiVersion: string; + /** + * The date and time in GMT that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * A string that you assigned to describe this resource. By default, the `FriendlyName` is the short code. + */ + friendlyName: string; + /** + * The short code. e.g., 894546. + */ + shortCode: string; + /** + * The unique string that that we created to identify this ShortCode resource. + */ + sid: string; + /** + * The HTTP method we use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + */ + smsFallbackMethod: string; + /** + * The URL that we call if an error occurs while retrieving or executing the TwiML from `sms_url`. + */ + smsFallbackUrl: string; + /** + * The HTTP method we use to call the `sms_url`. Can be: `GET` or `POST`. + */ + smsMethod: string; + /** + * The URL we call when receiving an incoming SMS message to this short code. + */ + smsUrl: string; + /** + * The URI of this resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): ShortCodeContext { + this._context = this._context || new ShortCodeContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a ShortCodeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance + */ + fetch(callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ShortCodeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ShortCodeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance + */ + update(callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise; + /** + * Update a ShortCodeInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance + */ + update(params: ShortCodeContextUpdateOptions, callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ShortCodeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ShortCodeInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance with HTTP metadata + */ + updateWithHttpInfo(params: ShortCodeContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + shortCode: this.shortCode, + sid: this.sid, + smsFallbackMethod: this.smsFallbackMethod, + smsFallbackUrl: this.smsFallbackUrl, + smsMethod: this.smsMethod, + smsUrl: this.smsUrl, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ShortCodeSolution { + accountSid: string; +} + +export interface ShortCodeListInstance { + _version: V2010; + _solution: ShortCodeSolution; + _uri: string; + + (sid: string, ): ShortCodeContext; + get(sid: string, ): ShortCodeContext; + + + + + + + + /** + * Streams ShortCodeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ShortCodeInstance, done: (err?: Error) => void) => void): void; + each(params: ShortCodeListInstanceEachOptions, callback?: (item: ShortCodeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ShortCodeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ShortCodeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ShortCodeListInstanceEachOptions, callback?: (item: ShortCodeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ShortCodeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ShortCodePage) => any): Promise; + /** + * Retrieve a single target page of ShortCodeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ShortCodeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ShortCodeInstance[]) => any): Promise; + list(params: ShortCodeListInstanceOptions, callback?: (error: Error | null, items: ShortCodeInstance[]) => any): Promise; + /** + * Lists ShortCodeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ShortCodeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ShortCodeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ShortCodePage) => any): Promise; + page(params: ShortCodeListInstancePageOptions, callback?: (error: Error | null, items: ShortCodePage) => any): Promise; + /** + * Retrieve a single page of ShortCodeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ShortCodeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ShortCodeListInstance(version: V2010, accountSid: string): ShortCodeListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ShortCodeListInstance; + + instance.get = function get(sid, ): ShortCodeContext { + return new ShortCodeContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/SMS/ShortCodes.json`; + + instance.page = function page(params?: ShortCodeListInstancePageOptions | ((error: Error | null, items: ShortCodePage) => any), callback?: (error: Error | null, items: ShortCodePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["shortCode"] !== undefined) + data["ShortCode"] = params["shortCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ShortCodePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ShortCodePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ShortCodePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ShortCodeListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["shortCode"] !== undefined) + data["ShortCode"] = params["shortCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ShortCodePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ShortCodePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ShortCodePage extends Page { +/** +* Initialize the ShortCodePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: ShortCodeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ShortCodeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ShortCodeResource): ShortCodeInstance { + + return new ShortCodeInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/signingKey.ts b/rest/api/v2010/account/signingKey.ts new file mode 100644 index 000000000..ce64eddb1 --- /dev/null +++ b/rest/api/v2010/account/signingKey.ts @@ -0,0 +1,775 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a SigningKeyInstance + */ +export interface SigningKeyContextUpdateOptions { + /** */ + "friendlyName"?: string; +} + +/** + * Options to pass to each + */ +export interface SigningKeyListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SigningKeyInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SigningKeyListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SigningKeyListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SigningKeyContext { + + /** + * Remove a SigningKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a SigningKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a SigningKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance + */ + fetch(callback?: (error: Error | null, item?: SigningKeyInstance) => any): Promise + + /** + * Fetch a SigningKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a SigningKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance + */ + update(callback?: (error: Error | null, item?: SigningKeyInstance) => any): Promise; + /** + * Update a SigningKeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance + */ + update(params: SigningKeyContextUpdateOptions, callback?: (error: Error | null, item?: SigningKeyInstance) => any): Promise; + + /** + * Update a SigningKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a SigningKeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance with HTTP metadata + */ + updateWithHttpInfo(params: SigningKeyContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SigningKeyContextSolution { + "accountSid": string; + "sid": string; +} + +export class SigningKeyContextImpl implements SigningKeyContext { + protected _solution: SigningKeyContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/SigningKeys/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SigningKeyInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SigningKeyInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new SigningKeyInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SigningKeyContextUpdateOptions | ((error: Error | null, item?: SigningKeyInstance) => any),callback?: (error: Error | null, item?: SigningKeyInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SigningKeyInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SigningKeyContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SigningKeyInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SigningKeyPayload extends TwilioResponsePayload { + signing_keys: SigningKeyResource[]; +} + +interface SigningKeyResource { + sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; +} + +export class SigningKeyInstance { + protected _solution: SigningKeyContextSolution; + protected _context?: SigningKeyContext; + + constructor(protected _version: V2010, payload: SigningKeyResource, accountSid: string, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + + this._solution = { accountSid, sid: sid, }; + } + + sid: string; + friendlyName: string; + dateCreated: Date; + dateUpdated: Date; + + private get _proxy(): SigningKeyContext { + this._context = this._context || new SigningKeyContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a SigningKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SigningKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SigningKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance + */ + fetch(callback?: (error: Error | null, item?: SigningKeyInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SigningKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SigningKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance + */ + update(callback?: (error: Error | null, item?: SigningKeyInstance) => any): Promise; + /** + * Update a SigningKeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance + */ + update(params: SigningKeyContextUpdateOptions, callback?: (error: Error | null, item?: SigningKeyInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: SigningKeyInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a SigningKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a SigningKeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningKeyInstance with HTTP metadata + */ + updateWithHttpInfo(params: SigningKeyContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SigningKeySolution { + accountSid: string; +} + +export interface SigningKeyListInstance { + _version: V2010; + _solution: SigningKeySolution; + _uri: string; + + (sid: string, ): SigningKeyContext; + get(sid: string, ): SigningKeyContext; + + + + + + + + + + /** + * Streams SigningKeyInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningKeyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SigningKeyInstance, done: (err?: Error) => void) => void): void; + each(params: SigningKeyListInstanceEachOptions, callback?: (item: SigningKeyInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SigningKeyInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningKeyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SigningKeyInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SigningKeyListInstanceEachOptions, callback?: (item: SigningKeyInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SigningKeyInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SigningKeyPage) => any): Promise; + /** + * Retrieve a single target page of SigningKeyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists SigningKeyInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningKeyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SigningKeyInstance[]) => any): Promise; + list(params: SigningKeyListInstanceOptions, callback?: (error: Error | null, items: SigningKeyInstance[]) => any): Promise; + /** + * Lists SigningKeyInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningKeyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: SigningKeyListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of SigningKeyInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningKeyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SigningKeyPage) => any): Promise; + page(params: SigningKeyListInstancePageOptions, callback?: (error: Error | null, items: SigningKeyPage) => any): Promise; + /** + * Retrieve a single page of SigningKeyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningKeyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: SigningKeyListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SigningKeyListInstance(version: V2010, accountSid: string): SigningKeyListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as SigningKeyListInstance; + + instance.get = function get(sid, ): SigningKeyContext { + return new SigningKeyContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/SigningKeys.json`; + + instance.page = function page(params?: SigningKeyListInstancePageOptions | ((error: Error | null, items: SigningKeyPage) => any), callback?: (error: Error | null, items: SigningKeyPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SigningKeyPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SigningKeyPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SigningKeyPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SigningKeyListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SigningKeyPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SigningKeyPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SigningKeyPage extends Page { +/** +* Initialize the SigningKeyPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: SigningKeySolution) { + super(version, response, solution); + } + + /** + * Build an instance of SigningKeyInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SigningKeyResource): SigningKeyInstance { + + return new SigningKeyInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/token.ts b/rest/api/v2010/account/token.ts new file mode 100644 index 000000000..ba26f81d6 --- /dev/null +++ b/rest/api/v2010/account/token.ts @@ -0,0 +1,273 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class ApiV2010AccountTokenIceServers { + "credential"?: string; + "username"?: string; + "url"?: string; + "urls"?: string; + + constructor(payload) { + this.credential = payload["credential"]; + this.username = payload["username"]; + this.url = payload["url"]; + this.urls = payload["urls"]; + } +} + + + +/** + * Options to pass to create a TokenInstance + */ +export interface TokenListInstanceCreateOptions { + /** The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). */ + "ttl"?: number; +} + + +export interface TokenSolution { + accountSid: string; +} + +export interface TokenListInstance { + _version: V2010; + _solution: TokenSolution; + _uri: string; + + + + /** + * Create a TokenInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance + */ + create(callback?: (error: Error | null, item?: TokenInstance) => any): Promise; + /** + * Create a TokenInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance + */ + create(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, item?: TokenInstance) => any): Promise; + + /** + * Create a TokenInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a TokenInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance with HTTP metadata + */ + createWithHttpInfo(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TokenListInstance(version: V2010, accountSid: string): TokenListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as TokenListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Tokens.json`; + + instance.create = function create(params?: TokenListInstanceCreateOptions | ((error: Error | null, items: TokenInstance) => any), callback?: (error: Error | null, items: TokenInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TokenInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: TokenListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new TokenInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TokenPayload extends TokenResource {} + +interface TokenResource { + account_sid: string; + date_created: Date; + date_updated: Date; + ice_servers: Array; + password: string; + ttl: string; + username: string; +} + +export class TokenInstance { + + constructor(protected _version: V2010, payload: TokenResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.iceServers = payload.ice_servers !== null && payload.ice_servers !== undefined ? payload.ice_servers.map( + (payload: any) => new ApiV2010AccountTokenIceServers(payload) + ) : null; + this.password = (payload.password); + this.ttl = (payload.ttl); + this.username = (payload.username); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Token resource. + */ + accountSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * An array representing the ephemeral credentials and the STUN and TURN server URIs. + */ + iceServers: Array; + /** + * The temporary password that the username will use when authenticating with Twilio. + */ + password: string; + /** + * The duration in seconds for which the username and password are valid. + */ + ttl: string; + /** + * The temporary username that uniquely identifies a Token. + */ + username: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + iceServers: this.iceServers, + password: this.password, + ttl: this.ttl, + username: this.username, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/api/v2010/account/transcription.ts b/rest/api/v2010/account/transcription.ts new file mode 100644 index 000000000..4b80968aa --- /dev/null +++ b/rest/api/v2010/account/transcription.ts @@ -0,0 +1,691 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The status of the transcription. Can be: `in-progress`, `completed`, `failed`. + */ +export type TranscriptionStatus = 'in-progress'|'completed'|'failed'; + + + + +/** + * Options to pass to each + */ +export interface TranscriptionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TranscriptionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TranscriptionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TranscriptionContext { + + /** + * Remove a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise + + /** + * Fetch a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TranscriptionContextSolution { + "accountSid": string; + "sid": string; +} + +export class TranscriptionContextImpl implements TranscriptionContext { + protected _solution: TranscriptionContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Transcriptions/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new TranscriptionInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TranscriptionPayload extends TwilioResponsePayload { + transcriptions: TranscriptionResource[]; +} + +interface TranscriptionResource { + account_sid: string; + api_version: string; + date_created: Date; + date_updated: Date; + duration: string; + price: number; + price_unit: string; + recording_sid: string; + sid: string; + status: TranscriptionStatus; + transcription_text: string; + type: string; + uri: string; +} + +export class TranscriptionInstance { + protected _solution: TranscriptionContextSolution; + protected _context?: TranscriptionContext; + + constructor(protected _version: V2010, payload: TranscriptionResource, accountSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.duration = (payload.duration); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.recordingSid = (payload.recording_sid); + this.sid = (payload.sid); + this.status = payload.status; + this.transcriptionText = (payload.transcription_text); + this.type = (payload.type); + this.uri = (payload.uri); + + this._solution = { accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource. + */ + accountSid: string; + /** + * The API version used to create the transcription. + */ + apiVersion: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The duration of the transcribed audio in seconds. + */ + duration: string; + /** + * The charge for the transcript in the currency associated with the account. This value is populated after the transcript is complete so it may not be available immediately. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + */ + priceUnit: string; + /** + * The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) from which the transcription was created. + */ + recordingSid: string; + /** + * The unique string that that we created to identify the Transcription resource. + */ + sid: string; + status: TranscriptionStatus; + /** + * The text content of the transcription. + */ + transcriptionText: string; + /** + * The transcription type. Can only be: `fast`. + */ + type: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): TranscriptionContext { + this._context = this._context || new TranscriptionContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + duration: this.duration, + price: this.price, + priceUnit: this.priceUnit, + recordingSid: this.recordingSid, + sid: this.sid, + status: this.status, + transcriptionText: this.transcriptionText, + type: this.type, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TranscriptionSolution { + accountSid: string; +} + +export interface TranscriptionListInstance { + _version: V2010; + _solution: TranscriptionSolution; + _uri: string; + + (sid: string, ): TranscriptionContext; + get(sid: string, ): TranscriptionContext; + + + + + + + + /** + * Streams TranscriptionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + each(params: TranscriptionListInstanceEachOptions, callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TranscriptionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TranscriptionListInstanceEachOptions, callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TranscriptionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TranscriptionPage) => any): Promise; + /** + * Retrieve a single target page of TranscriptionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists TranscriptionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TranscriptionInstance[]) => any): Promise; + list(params: TranscriptionListInstanceOptions, callback?: (error: Error | null, items: TranscriptionInstance[]) => any): Promise; + /** + * Lists TranscriptionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: TranscriptionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of TranscriptionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TranscriptionPage) => any): Promise; + page(params: TranscriptionListInstancePageOptions, callback?: (error: Error | null, items: TranscriptionPage) => any): Promise; + /** + * Retrieve a single page of TranscriptionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: TranscriptionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TranscriptionListInstance(version: V2010, accountSid: string): TranscriptionListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as TranscriptionListInstance; + + instance.get = function get(sid, ): TranscriptionContext { + return new TranscriptionContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Transcriptions.json`; + + instance.page = function page(params?: TranscriptionListInstancePageOptions | ((error: Error | null, items: TranscriptionPage) => any), callback?: (error: Error | null, items: TranscriptionPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TranscriptionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TranscriptionPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TranscriptionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TranscriptionListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TranscriptionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TranscriptionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TranscriptionPage extends Page { +/** +* Initialize the TranscriptionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: TranscriptionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TranscriptionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TranscriptionResource): TranscriptionInstance { + + return new TranscriptionInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/account/validationRequest.ts b/rest/api/v2010/account/validationRequest.ts new file mode 100644 index 000000000..a5aa21767 --- /dev/null +++ b/rest/api/v2010/account/validationRequest.ts @@ -0,0 +1,258 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to create a ValidationRequestInstance + */ +export interface ValidationRequestListInstanceCreateOptions { + /** The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. */ + "phoneNumber": string; + /** A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. */ + "friendlyName"?: string; + /** The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. */ + "callDelay"?: number; + /** The digits to dial after connecting the verification call. */ + "extension"?: string; + /** The URL we should call using the `status_callback_method` to send status information about the verification process to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. */ + "statusCallbackMethod"?: string; +} + + +export interface ValidationRequestSolution { + accountSid: string; +} + +export interface ValidationRequestListInstance { + _version: V2010; + _solution: ValidationRequestSolution; + _uri: string; + + + + /** + * Create a ValidationRequestInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ValidationRequestInstance + */ + create(params: ValidationRequestListInstanceCreateOptions, callback?: (error: Error | null, item?: ValidationRequestInstance) => any): Promise; + + /** + * Create a ValidationRequestInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ValidationRequestInstance with HTTP metadata + */ + createWithHttpInfo(params: ValidationRequestListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ValidationRequestListInstance(version: V2010, accountSid: string): ValidationRequestListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as ValidationRequestListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/OutgoingCallerIds.json`; + + instance.create = function create(params: ValidationRequestListInstanceCreateOptions, callback?: (error: Error | null, items: ValidationRequestInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["callDelay"] !== undefined) + data["CallDelay"] = params["callDelay"]; + if (params["extension"] !== undefined) + data["Extension"] = params["extension"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ValidationRequestInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ValidationRequestListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["callDelay"] !== undefined) + data["CallDelay"] = params["callDelay"]; + if (params["extension"] !== undefined) + data["Extension"] = params["extension"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ValidationRequestInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ValidationRequestPayload extends ValidationRequestResource {} + +interface ValidationRequestResource { + account_sid: string; + call_sid: string; + friendly_name: string; + phone_number: string; + validation_code: string; +} + +export class ValidationRequestInstance { + + constructor(protected _version: V2010, payload: ValidationRequestResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.callSid = (payload.call_sid); + this.friendlyName = (payload.friendly_name); + this.phoneNumber = (payload.phone_number); + this.validationCode = (payload.validation_code); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for the Caller ID. + */ + accountSid: string; + /** + * The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Caller ID is associated with. + */ + callSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The 6 digit validation code that someone must enter to validate the Caller ID when `phone_number` is called. + */ + validationCode: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + callSid: this.callSid, + friendlyName: this.friendlyName, + phoneNumber: this.phoneNumber, + validationCode: this.validationCode, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/api/v2010/authCallsCredentialListMapping.ts b/rest/api/v2010/authCallsCredentialListMapping.ts new file mode 100644 index 000000000..d2e9d489e --- /dev/null +++ b/rest/api/v2010/authCallsCredentialListMapping.ts @@ -0,0 +1,743 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2010 from "../V2010"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a AuthCallsCredentialListMappingInstance + */ +export interface AuthCallsCredentialListMappingListInstanceCreateOptions { + /** The SID of the CredentialList resource to map to the SIP domain. */ + "credentialListSid": string; +} + +/** + * Options to pass to each + */ +export interface AuthCallsCredentialListMappingListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AuthCallsCredentialListMappingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AuthCallsCredentialListMappingListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AuthCallsCredentialListMappingListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AuthCallsCredentialListMappingContext { + + /** + * Remove a AuthCallsCredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AuthCallsCredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a AuthCallsCredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsCredentialListMappingInstance + */ + fetch(callback?: (error: Error | null, item?: AuthCallsCredentialListMappingInstance) => any): Promise + + /** + * Fetch a AuthCallsCredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsCredentialListMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AuthCallsCredentialListMappingContextSolution { + "accountSid": string; + "domainSid": string; + "sid": string; +} + +export class AuthCallsCredentialListMappingContextImpl implements AuthCallsCredentialListMappingContext { + protected _solution: AuthCallsCredentialListMappingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, domainSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, domainSid, sid, }; + this._uri = `/Accounts/${accountSid}/SIP/Domains/${domainSid}/Auth/Calls/CredentialListMappings/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AuthCallsCredentialListMappingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AuthCallsCredentialListMappingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.domainSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AuthCallsCredentialListMappingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.domainSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AuthCallsCredentialListMappingPayload extends TwilioResponsePayload { + contents: AuthCallsCredentialListMappingResource[]; +} + +interface AuthCallsCredentialListMappingResource { + account_sid: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + sid: string; +} + +export class AuthCallsCredentialListMappingInstance { + protected _solution: AuthCallsCredentialListMappingContextSolution; + protected _context?: AuthCallsCredentialListMappingContext; + + constructor(protected _version: V2010, payload: AuthCallsCredentialListMappingResource, accountSid?: string, domainSid?: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + + this._solution = { accountSid: accountSid, domainSid: domainSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource. + */ + accountSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The unique string that that we created to identify the CredentialListMapping resource. + */ + sid: string; + + private get _proxy(): AuthCallsCredentialListMappingContext { + this._context = this._context || new AuthCallsCredentialListMappingContextImpl(this._version, this._solution.accountSid, this._solution.domainSid, this._solution.sid); + return this._context; + } + + /** + * Remove a AuthCallsCredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AuthCallsCredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AuthCallsCredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsCredentialListMappingInstance + */ + fetch(callback?: (error: Error | null, item?: AuthCallsCredentialListMappingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AuthCallsCredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsCredentialListMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + sid: this.sid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AuthCallsCredentialListMappingSolution { + accountSid: string; + domainSid: string; +} + +export interface AuthCallsCredentialListMappingListInstance { + _version: V2010; + _solution: AuthCallsCredentialListMappingSolution; + _uri: string; + + (accountSid: string, domainSid: string, sid: string, ): AuthCallsCredentialListMappingContext; + get(accountSid: string, domainSid: string, sid: string, ): AuthCallsCredentialListMappingContext; + + + + + + + /** + * Create a AuthCallsCredentialListMappingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsCredentialListMappingInstance + */ + create(params: AuthCallsCredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: AuthCallsCredentialListMappingInstance) => any): Promise; + + /** + * Create a AuthCallsCredentialListMappingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsCredentialListMappingInstance with HTTP metadata + */ + createWithHttpInfo(params: AuthCallsCredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams AuthCallsCredentialListMappingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsCredentialListMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AuthCallsCredentialListMappingInstance, done: (err?: Error) => void) => void): void; + each(params: AuthCallsCredentialListMappingListInstanceEachOptions, callback?: (item: AuthCallsCredentialListMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AuthCallsCredentialListMappingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsCredentialListMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AuthCallsCredentialListMappingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AuthCallsCredentialListMappingListInstanceEachOptions, callback?: (item: AuthCallsCredentialListMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AuthCallsCredentialListMappingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AuthCallsCredentialListMappingPage) => any): Promise; + /** + * Retrieve a single target page of AuthCallsCredentialListMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AuthCallsCredentialListMappingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsCredentialListMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AuthCallsCredentialListMappingInstance[]) => any): Promise; + list(params: AuthCallsCredentialListMappingListInstanceOptions, callback?: (error: Error | null, items: AuthCallsCredentialListMappingInstance[]) => any): Promise; + /** + * Lists AuthCallsCredentialListMappingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsCredentialListMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AuthCallsCredentialListMappingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AuthCallsCredentialListMappingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsCredentialListMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AuthCallsCredentialListMappingPage) => any): Promise; + page(params: AuthCallsCredentialListMappingListInstancePageOptions, callback?: (error: Error | null, items: AuthCallsCredentialListMappingPage) => any): Promise; + /** + * Retrieve a single page of AuthCallsCredentialListMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsCredentialListMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AuthCallsCredentialListMappingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AuthCallsCredentialListMappingListInstance(version: V2010, accountSid: string, domainSid: string): AuthCallsCredentialListMappingListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + const instance = ((accountSid, domainSid, sid, ) => instance.get(accountSid, domainSid, sid, )) as AuthCallsCredentialListMappingListInstance; + + instance.get = function get(accountSid, domainSid, sid, ): AuthCallsCredentialListMappingContext { + return new AuthCallsCredentialListMappingContextImpl(version, accountSid, domainSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, domainSid, }; + instance._uri = `/Accounts/${accountSid}/SIP/Domains/${domainSid}/Auth/Calls/CredentialListMappings.json`; + + instance.create = function create(params: AuthCallsCredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, items: AuthCallsCredentialListMappingInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["credentialListSid"] === null || params["credentialListSid"] === undefined) { + throw new Error('Required parameter "params[\'credentialListSid\']" missing.'); + } + + let data: any = {}; + + + + data["CredentialListSid"] = params["credentialListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AuthCallsCredentialListMappingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AuthCallsCredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["credentialListSid"] === null || params["credentialListSid"] === undefined) { + throw new Error('Required parameter "params[\'credentialListSid\']" missing.'); + } + + let data: any = {}; + + + + data["CredentialListSid"] = params["credentialListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AuthCallsCredentialListMappingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AuthCallsCredentialListMappingListInstancePageOptions | ((error: Error | null, items: AuthCallsCredentialListMappingPage) => any), callback?: (error: Error | null, items: AuthCallsCredentialListMappingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AuthCallsCredentialListMappingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AuthCallsCredentialListMappingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AuthCallsCredentialListMappingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AuthCallsCredentialListMappingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthCallsCredentialListMappingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthCallsCredentialListMappingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AuthCallsCredentialListMappingPage extends Page { +/** +* Initialize the AuthCallsCredentialListMappingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AuthCallsCredentialListMappingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AuthCallsCredentialListMappingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AuthCallsCredentialListMappingResource): AuthCallsCredentialListMappingInstance { + + return new AuthCallsCredentialListMappingInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.domainSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/authCallsIpAccessControlListMapping.ts b/rest/api/v2010/authCallsIpAccessControlListMapping.ts new file mode 100644 index 000000000..3c20af500 --- /dev/null +++ b/rest/api/v2010/authCallsIpAccessControlListMapping.ts @@ -0,0 +1,743 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2010 from "../V2010"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a AuthCallsIpAccessControlListMappingInstance + */ +export interface AuthCallsIpAccessControlListMappingListInstanceCreateOptions { + /** The SID of the IpAccessControlList resource to map to the SIP domain. */ + "ipAccessControlListSid": string; +} + +/** + * Options to pass to each + */ +export interface AuthCallsIpAccessControlListMappingListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AuthCallsIpAccessControlListMappingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AuthCallsIpAccessControlListMappingListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AuthCallsIpAccessControlListMappingListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AuthCallsIpAccessControlListMappingContext { + + /** + * Remove a AuthCallsIpAccessControlListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AuthCallsIpAccessControlListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a AuthCallsIpAccessControlListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsIpAccessControlListMappingInstance + */ + fetch(callback?: (error: Error | null, item?: AuthCallsIpAccessControlListMappingInstance) => any): Promise + + /** + * Fetch a AuthCallsIpAccessControlListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsIpAccessControlListMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AuthCallsIpAccessControlListMappingContextSolution { + "accountSid": string; + "domainSid": string; + "sid": string; +} + +export class AuthCallsIpAccessControlListMappingContextImpl implements AuthCallsIpAccessControlListMappingContext { + protected _solution: AuthCallsIpAccessControlListMappingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, domainSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, domainSid, sid, }; + this._uri = `/Accounts/${accountSid}/SIP/Domains/${domainSid}/Auth/Calls/IpAccessControlListMappings/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AuthCallsIpAccessControlListMappingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AuthCallsIpAccessControlListMappingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.domainSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AuthCallsIpAccessControlListMappingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.domainSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AuthCallsIpAccessControlListMappingPayload extends TwilioResponsePayload { + contents: AuthCallsIpAccessControlListMappingResource[]; +} + +interface AuthCallsIpAccessControlListMappingResource { + account_sid: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + sid: string; +} + +export class AuthCallsIpAccessControlListMappingInstance { + protected _solution: AuthCallsIpAccessControlListMappingContextSolution; + protected _context?: AuthCallsIpAccessControlListMappingContext; + + constructor(protected _version: V2010, payload: AuthCallsIpAccessControlListMappingResource, accountSid?: string, domainSid?: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + + this._solution = { accountSid: accountSid, domainSid: domainSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlListMapping resource. + */ + accountSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The unique string that that we created to identify the IpAccessControlListMapping resource. + */ + sid: string; + + private get _proxy(): AuthCallsIpAccessControlListMappingContext { + this._context = this._context || new AuthCallsIpAccessControlListMappingContextImpl(this._version, this._solution.accountSid, this._solution.domainSid, this._solution.sid); + return this._context; + } + + /** + * Remove a AuthCallsIpAccessControlListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AuthCallsIpAccessControlListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AuthCallsIpAccessControlListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsIpAccessControlListMappingInstance + */ + fetch(callback?: (error: Error | null, item?: AuthCallsIpAccessControlListMappingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AuthCallsIpAccessControlListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsIpAccessControlListMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + sid: this.sid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AuthCallsIpAccessControlListMappingSolution { + accountSid: string; + domainSid: string; +} + +export interface AuthCallsIpAccessControlListMappingListInstance { + _version: V2010; + _solution: AuthCallsIpAccessControlListMappingSolution; + _uri: string; + + (accountSid: string, domainSid: string, sid: string, ): AuthCallsIpAccessControlListMappingContext; + get(accountSid: string, domainSid: string, sid: string, ): AuthCallsIpAccessControlListMappingContext; + + + + + + + /** + * Create a AuthCallsIpAccessControlListMappingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsIpAccessControlListMappingInstance + */ + create(params: AuthCallsIpAccessControlListMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: AuthCallsIpAccessControlListMappingInstance) => any): Promise; + + /** + * Create a AuthCallsIpAccessControlListMappingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthCallsIpAccessControlListMappingInstance with HTTP metadata + */ + createWithHttpInfo(params: AuthCallsIpAccessControlListMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams AuthCallsIpAccessControlListMappingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsIpAccessControlListMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AuthCallsIpAccessControlListMappingInstance, done: (err?: Error) => void) => void): void; + each(params: AuthCallsIpAccessControlListMappingListInstanceEachOptions, callback?: (item: AuthCallsIpAccessControlListMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AuthCallsIpAccessControlListMappingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsIpAccessControlListMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AuthCallsIpAccessControlListMappingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AuthCallsIpAccessControlListMappingListInstanceEachOptions, callback?: (item: AuthCallsIpAccessControlListMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AuthCallsIpAccessControlListMappingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AuthCallsIpAccessControlListMappingPage) => any): Promise; + /** + * Retrieve a single target page of AuthCallsIpAccessControlListMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AuthCallsIpAccessControlListMappingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsIpAccessControlListMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AuthCallsIpAccessControlListMappingInstance[]) => any): Promise; + list(params: AuthCallsIpAccessControlListMappingListInstanceOptions, callback?: (error: Error | null, items: AuthCallsIpAccessControlListMappingInstance[]) => any): Promise; + /** + * Lists AuthCallsIpAccessControlListMappingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsIpAccessControlListMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AuthCallsIpAccessControlListMappingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AuthCallsIpAccessControlListMappingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsIpAccessControlListMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AuthCallsIpAccessControlListMappingPage) => any): Promise; + page(params: AuthCallsIpAccessControlListMappingListInstancePageOptions, callback?: (error: Error | null, items: AuthCallsIpAccessControlListMappingPage) => any): Promise; + /** + * Retrieve a single page of AuthCallsIpAccessControlListMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthCallsIpAccessControlListMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AuthCallsIpAccessControlListMappingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AuthCallsIpAccessControlListMappingListInstance(version: V2010, accountSid: string, domainSid: string): AuthCallsIpAccessControlListMappingListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + const instance = ((accountSid, domainSid, sid, ) => instance.get(accountSid, domainSid, sid, )) as AuthCallsIpAccessControlListMappingListInstance; + + instance.get = function get(accountSid, domainSid, sid, ): AuthCallsIpAccessControlListMappingContext { + return new AuthCallsIpAccessControlListMappingContextImpl(version, accountSid, domainSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, domainSid, }; + instance._uri = `/Accounts/${accountSid}/SIP/Domains/${domainSid}/Auth/Calls/IpAccessControlListMappings.json`; + + instance.create = function create(params: AuthCallsIpAccessControlListMappingListInstanceCreateOptions, callback?: (error: Error | null, items: AuthCallsIpAccessControlListMappingInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["ipAccessControlListSid"] === null || params["ipAccessControlListSid"] === undefined) { + throw new Error('Required parameter "params[\'ipAccessControlListSid\']" missing.'); + } + + let data: any = {}; + + + + data["IpAccessControlListSid"] = params["ipAccessControlListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AuthCallsIpAccessControlListMappingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AuthCallsIpAccessControlListMappingListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["ipAccessControlListSid"] === null || params["ipAccessControlListSid"] === undefined) { + throw new Error('Required parameter "params[\'ipAccessControlListSid\']" missing.'); + } + + let data: any = {}; + + + + data["IpAccessControlListSid"] = params["ipAccessControlListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AuthCallsIpAccessControlListMappingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AuthCallsIpAccessControlListMappingListInstancePageOptions | ((error: Error | null, items: AuthCallsIpAccessControlListMappingPage) => any), callback?: (error: Error | null, items: AuthCallsIpAccessControlListMappingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AuthCallsIpAccessControlListMappingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AuthCallsIpAccessControlListMappingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AuthCallsIpAccessControlListMappingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AuthCallsIpAccessControlListMappingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthCallsIpAccessControlListMappingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthCallsIpAccessControlListMappingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AuthCallsIpAccessControlListMappingPage extends Page { +/** +* Initialize the AuthCallsIpAccessControlListMappingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AuthCallsIpAccessControlListMappingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AuthCallsIpAccessControlListMappingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AuthCallsIpAccessControlListMappingResource): AuthCallsIpAccessControlListMappingInstance { + + return new AuthCallsIpAccessControlListMappingInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.domainSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/authRegistrationsCredentialListMapping.ts b/rest/api/v2010/authRegistrationsCredentialListMapping.ts new file mode 100644 index 000000000..ab50bdf4e --- /dev/null +++ b/rest/api/v2010/authRegistrationsCredentialListMapping.ts @@ -0,0 +1,743 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2010 from "../V2010"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a AuthRegistrationsCredentialListMappingInstance + */ +export interface AuthRegistrationsCredentialListMappingListInstanceCreateOptions { + /** The SID of the CredentialList resource to map to the SIP domain. */ + "credentialListSid": string; +} + +/** + * Options to pass to each + */ +export interface AuthRegistrationsCredentialListMappingListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AuthRegistrationsCredentialListMappingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AuthRegistrationsCredentialListMappingListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AuthRegistrationsCredentialListMappingListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AuthRegistrationsCredentialListMappingContext { + + /** + * Remove a AuthRegistrationsCredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AuthRegistrationsCredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a AuthRegistrationsCredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthRegistrationsCredentialListMappingInstance + */ + fetch(callback?: (error: Error | null, item?: AuthRegistrationsCredentialListMappingInstance) => any): Promise + + /** + * Fetch a AuthRegistrationsCredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthRegistrationsCredentialListMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AuthRegistrationsCredentialListMappingContextSolution { + "accountSid": string; + "domainSid": string; + "sid": string; +} + +export class AuthRegistrationsCredentialListMappingContextImpl implements AuthRegistrationsCredentialListMappingContext { + protected _solution: AuthRegistrationsCredentialListMappingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, domainSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, domainSid, sid, }; + this._uri = `/Accounts/${accountSid}/SIP/Domains/${domainSid}/Auth/Registrations/CredentialListMappings/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AuthRegistrationsCredentialListMappingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AuthRegistrationsCredentialListMappingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.domainSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AuthRegistrationsCredentialListMappingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.domainSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AuthRegistrationsCredentialListMappingPayload extends TwilioResponsePayload { + contents: AuthRegistrationsCredentialListMappingResource[]; +} + +interface AuthRegistrationsCredentialListMappingResource { + account_sid: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + sid: string; +} + +export class AuthRegistrationsCredentialListMappingInstance { + protected _solution: AuthRegistrationsCredentialListMappingContextSolution; + protected _context?: AuthRegistrationsCredentialListMappingContext; + + constructor(protected _version: V2010, payload: AuthRegistrationsCredentialListMappingResource, accountSid?: string, domainSid?: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + + this._solution = { accountSid: accountSid, domainSid: domainSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource. + */ + accountSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The unique string that that we created to identify the CredentialListMapping resource. + */ + sid: string; + + private get _proxy(): AuthRegistrationsCredentialListMappingContext { + this._context = this._context || new AuthRegistrationsCredentialListMappingContextImpl(this._version, this._solution.accountSid, this._solution.domainSid, this._solution.sid); + return this._context; + } + + /** + * Remove a AuthRegistrationsCredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AuthRegistrationsCredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AuthRegistrationsCredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthRegistrationsCredentialListMappingInstance + */ + fetch(callback?: (error: Error | null, item?: AuthRegistrationsCredentialListMappingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AuthRegistrationsCredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthRegistrationsCredentialListMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + sid: this.sid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AuthRegistrationsCredentialListMappingSolution { + accountSid: string; + domainSid: string; +} + +export interface AuthRegistrationsCredentialListMappingListInstance { + _version: V2010; + _solution: AuthRegistrationsCredentialListMappingSolution; + _uri: string; + + (accountSid: string, domainSid: string, sid: string, ): AuthRegistrationsCredentialListMappingContext; + get(accountSid: string, domainSid: string, sid: string, ): AuthRegistrationsCredentialListMappingContext; + + + + + + + /** + * Create a AuthRegistrationsCredentialListMappingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthRegistrationsCredentialListMappingInstance + */ + create(params: AuthRegistrationsCredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: AuthRegistrationsCredentialListMappingInstance) => any): Promise; + + /** + * Create a AuthRegistrationsCredentialListMappingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthRegistrationsCredentialListMappingInstance with HTTP metadata + */ + createWithHttpInfo(params: AuthRegistrationsCredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams AuthRegistrationsCredentialListMappingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthRegistrationsCredentialListMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AuthRegistrationsCredentialListMappingInstance, done: (err?: Error) => void) => void): void; + each(params: AuthRegistrationsCredentialListMappingListInstanceEachOptions, callback?: (item: AuthRegistrationsCredentialListMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AuthRegistrationsCredentialListMappingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthRegistrationsCredentialListMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AuthRegistrationsCredentialListMappingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AuthRegistrationsCredentialListMappingListInstanceEachOptions, callback?: (item: AuthRegistrationsCredentialListMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AuthRegistrationsCredentialListMappingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AuthRegistrationsCredentialListMappingPage) => any): Promise; + /** + * Retrieve a single target page of AuthRegistrationsCredentialListMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AuthRegistrationsCredentialListMappingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthRegistrationsCredentialListMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AuthRegistrationsCredentialListMappingInstance[]) => any): Promise; + list(params: AuthRegistrationsCredentialListMappingListInstanceOptions, callback?: (error: Error | null, items: AuthRegistrationsCredentialListMappingInstance[]) => any): Promise; + /** + * Lists AuthRegistrationsCredentialListMappingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthRegistrationsCredentialListMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AuthRegistrationsCredentialListMappingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AuthRegistrationsCredentialListMappingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthRegistrationsCredentialListMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AuthRegistrationsCredentialListMappingPage) => any): Promise; + page(params: AuthRegistrationsCredentialListMappingListInstancePageOptions, callback?: (error: Error | null, items: AuthRegistrationsCredentialListMappingPage) => any): Promise; + /** + * Retrieve a single page of AuthRegistrationsCredentialListMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthRegistrationsCredentialListMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AuthRegistrationsCredentialListMappingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AuthRegistrationsCredentialListMappingListInstance(version: V2010, accountSid: string, domainSid: string): AuthRegistrationsCredentialListMappingListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + const instance = ((accountSid, domainSid, sid, ) => instance.get(accountSid, domainSid, sid, )) as AuthRegistrationsCredentialListMappingListInstance; + + instance.get = function get(accountSid, domainSid, sid, ): AuthRegistrationsCredentialListMappingContext { + return new AuthRegistrationsCredentialListMappingContextImpl(version, accountSid, domainSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, domainSid, }; + instance._uri = `/Accounts/${accountSid}/SIP/Domains/${domainSid}/Auth/Registrations/CredentialListMappings.json`; + + instance.create = function create(params: AuthRegistrationsCredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, items: AuthRegistrationsCredentialListMappingInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["credentialListSid"] === null || params["credentialListSid"] === undefined) { + throw new Error('Required parameter "params[\'credentialListSid\']" missing.'); + } + + let data: any = {}; + + + + data["CredentialListSid"] = params["credentialListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AuthRegistrationsCredentialListMappingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AuthRegistrationsCredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["credentialListSid"] === null || params["credentialListSid"] === undefined) { + throw new Error('Required parameter "params[\'credentialListSid\']" missing.'); + } + + let data: any = {}; + + + + data["CredentialListSid"] = params["credentialListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AuthRegistrationsCredentialListMappingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AuthRegistrationsCredentialListMappingListInstancePageOptions | ((error: Error | null, items: AuthRegistrationsCredentialListMappingPage) => any), callback?: (error: Error | null, items: AuthRegistrationsCredentialListMappingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AuthRegistrationsCredentialListMappingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AuthRegistrationsCredentialListMappingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AuthRegistrationsCredentialListMappingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AuthRegistrationsCredentialListMappingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthRegistrationsCredentialListMappingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthRegistrationsCredentialListMappingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AuthRegistrationsCredentialListMappingPage extends Page { +/** +* Initialize the AuthRegistrationsCredentialListMappingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AuthRegistrationsCredentialListMappingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AuthRegistrationsCredentialListMappingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AuthRegistrationsCredentialListMappingResource): AuthRegistrationsCredentialListMappingInstance { + + return new AuthRegistrationsCredentialListMappingInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.domainSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/credentialList.ts b/rest/api/v2010/credentialList.ts new file mode 100644 index 000000000..cc10018d2 --- /dev/null +++ b/rest/api/v2010/credentialList.ts @@ -0,0 +1,892 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2010 from "../V2010"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { CredentialListInstance as CredentialListInstanceImport } from "./credentialList/credential"; + + + + + +/** + * Options to pass to update a CredentialListInstance + */ +export interface CredentialListContextUpdateOptions { + /** A human readable descriptive text for a CredentialList, up to 64 characters long. */ + "friendlyName": string; +} + +/** + * Options to pass to create a CredentialListInstance + */ +export interface CredentialListListInstanceCreateOptions { + /** A human readable descriptive text that describes the CredentialList, up to 64 characters long. */ + "friendlyName": string; +} + +/** + * Options to pass to each + */ +export interface CredentialListListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CredentialListInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CredentialListListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CredentialListListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CredentialListContext { + credentials: CredentialListInstanceImport; + + /** + * Remove a CredentialListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a CredentialListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a CredentialListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise + + /** + * Fetch a CredentialListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a CredentialListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance + */ + update(params: CredentialListContextUpdateOptions, callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise; + + /** + * Update a CredentialListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialListContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CredentialListContextSolution { + "accountSid": string; + "sid": string; +} + +export class CredentialListContextImpl implements CredentialListContext { + protected _solution: CredentialListContextSolution; + protected _uri: string; + + protected _credentials?: CredentialListInstanceImport; + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/SIP/CredentialLists/${sid}.json`; + } + + get credentials(): CredentialListInstanceImport { + this._credentials = this._credentials || CredentialListInstanceImport(this._version, this._solution.accountSid, this._solution.sid); + return this._credentials; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CredentialListInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialListInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: CredentialListContextUpdateOptions,callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialListInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: CredentialListContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialListInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CredentialListPayload extends TwilioResponsePayload { + credential_lists: CredentialListResource[]; +} + +interface CredentialListResource { + account_sid: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + sid: string; + subresource_uris: Record; + uri: string; +} + +export class CredentialListInstance { + protected _solution: CredentialListContextSolution; + protected _context?: CredentialListContext; + + constructor(protected _version: V2010, payload: CredentialListResource, accountSid?: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + + this._solution = { accountSid: accountSid, sid: sid, }; + } + + /** + * The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) that owns this resource. + */ + accountSid: string; + /** + * The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateCreated: Date; + /** + * The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateUpdated: Date; + /** + * A human readable descriptive text that describes the CredentialList, up to 64 characters long. + */ + friendlyName: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * A list of credentials associated with this credential list. + */ + subresourceUris: Record; + /** + * The URI for this resource, relative to `https://api.twilio.com`. + */ + uri: string; + + private get _proxy(): CredentialListContext { + this._context = this._context || new CredentialListContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a CredentialListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CredentialListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CredentialListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CredentialListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CredentialListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance + */ + update(params: CredentialListContextUpdateOptions, callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a CredentialListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialListContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the credentials. + */ + credentials(): CredentialListInstanceImport { + return this._proxy.credentials; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + sid: this.sid, + subresourceUris: this.subresourceUris, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CredentialListSolution { + accountSid: string; +} + +export interface CredentialListListInstance { + _version: V2010; + _solution: CredentialListSolution; + _uri: string; + + (accountSid: string, sid: string, ): CredentialListContext; + get(accountSid: string, sid: string, ): CredentialListContext; + + + + + + + + + /** + * Create a CredentialListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance + */ + create(params: CredentialListListInstanceCreateOptions, callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise; + + /** + * Create a CredentialListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance with HTTP metadata + */ + createWithHttpInfo(params: CredentialListListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CredentialListInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CredentialListInstance, done: (err?: Error) => void) => void): void; + each(params: CredentialListListInstanceEachOptions, callback?: (item: CredentialListInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CredentialListInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CredentialListInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CredentialListListInstanceEachOptions, callback?: (item: CredentialListInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CredentialListInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialListPage) => any): Promise; + /** + * Retrieve a single target page of CredentialListInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CredentialListInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CredentialListInstance[]) => any): Promise; + list(params: CredentialListListInstanceOptions, callback?: (error: Error | null, items: CredentialListInstance[]) => any): Promise; + /** + * Lists CredentialListInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CredentialListListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CredentialListInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CredentialListPage) => any): Promise; + page(params: CredentialListListInstancePageOptions, callback?: (error: Error | null, items: CredentialListPage) => any): Promise; + /** + * Retrieve a single page of CredentialListInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CredentialListListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CredentialListListInstance(version: V2010, accountSid: string): CredentialListListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((accountSid, sid, ) => instance.get(accountSid, sid, )) as CredentialListListInstance; + + instance.get = function get(accountSid, sid, ): CredentialListContext { + return new CredentialListContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/SIP/CredentialLists.json`; + + instance.create = function create(params: CredentialListListInstanceCreateOptions, callback?: (error: Error | null, items: CredentialListInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialListInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CredentialListListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialListInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CredentialListListInstancePageOptions | ((error: Error | null, items: CredentialListPage) => any), callback?: (error: Error | null, items: CredentialListPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CredentialListPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialListPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CredentialListPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CredentialListListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialListPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialListPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CredentialListPage extends Page { +/** +* Initialize the CredentialListPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: CredentialListSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CredentialListInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CredentialListResource): CredentialListInstance { + + return new CredentialListInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/credentialList/credential.ts b/rest/api/v2010/credentialList/credential.ts new file mode 100644 index 000000000..1702f2317 --- /dev/null +++ b/rest/api/v2010/credentialList/credential.ts @@ -0,0 +1,932 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a CredentialInstance + */ +export interface CredentialContextUpdateOptions { + /** The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) */ + "password"?: string; +} + +/** + * Options to pass to create a CredentialInstance + */ +export interface CredentialListInstanceCreateOptions { + /** The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio\\\'s challenge of the initial INVITE. It can be up to 32 characters long. */ + "username": string; + /** The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) */ + "password": string; +} + +/** + * Options to pass to each + */ +export interface CredentialListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CredentialInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CredentialListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CredentialListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CredentialContext { + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CredentialContextSolution { + "accountSid": string; + "credentialListSid": string; + "sid": string; +} + +export class CredentialContextImpl implements CredentialContext { + protected _solution: CredentialContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, credentialListSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(credentialListSid)) { + throw new Error('Parameter \'credentialListSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, credentialListSid, sid, }; + this._uri = `/Accounts/${accountSid}/SIP/CredentialLists/${credentialListSid}/Credentials/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.credentialListSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.credentialListSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: CredentialInstance) => any),callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["password"] !== undefined) + data["Password"] = params["password"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.credentialListSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["password"] !== undefined) + data["Password"] = params["password"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.credentialListSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CredentialPayload extends TwilioResponsePayload { + credentials: CredentialResource[]; +} + +interface CredentialResource { + sid: string; + account_sid: string; + credential_list_sid: string; + username: string; + date_created: Date; + date_updated: Date; + uri: string; +} + +export class CredentialInstance { + protected _solution: CredentialContextSolution; + protected _context?: CredentialContext; + + constructor(protected _version: V2010, payload: CredentialResource, accountSid: string, credentialListSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.credentialListSid = (payload.credential_list_sid); + this.username = (payload.username); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.uri = (payload.uri); + + this._solution = { accountSid, credentialListSid, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The unique id of the Account that is responsible for this resource. + */ + accountSid: string; + /** + * The unique id that identifies the credential list that includes this credential. + */ + credentialListSid: string; + /** + * The username for this credential. + */ + username: string; + /** + * The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateCreated: Date; + /** + * The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateUpdated: Date; + /** + * The URI for this resource, relative to `https://api.twilio.com` + */ + uri: string; + + private get _proxy(): CredentialContext { + this._context = this._context || new CredentialContextImpl(this._version, this._solution.accountSid, this._solution.credentialListSid, this._solution.sid); + return this._context; + } + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + credentialListSid: this.credentialListSid, + username: this.username, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CredentialSolution { + accountSid: string; + credentialListSid: string; +} + +export interface CredentialListInstance { + _version: V2010; + _solution: CredentialSolution; + _uri: string; + + (sid: string, ): CredentialContext; + get(sid: string, ): CredentialContext; + + + + + + + + + /** + * Create a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Create a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CredentialInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + each(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CredentialInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single target page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CredentialInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + list(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + /** + * Lists CredentialInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CredentialPage) => any): Promise; + page(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CredentialListInstance(version: V2010, accountSid: string, credentialListSid: string): CredentialListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(credentialListSid)) { + throw new Error('Parameter \'credentialListSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as CredentialListInstance; + + instance.get = function get(sid, ): CredentialContext { + return new CredentialContextImpl(version, accountSid, credentialListSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, credentialListSid, }; + instance._uri = `/Accounts/${accountSid}/SIP/CredentialLists/${credentialListSid}/Credentials.json`; + + instance.create = function create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: CredentialInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["username"] === null || params["username"] === undefined) { + throw new Error('Required parameter "params[\'username\']" missing.'); + } + + if (params["password"] === null || params["password"] === undefined) { + throw new Error('Required parameter "params[\'password\']" missing.'); + } + + let data: any = {}; + + + + data["Username"] = params["username"]; + + data["Password"] = params["password"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.credentialListSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["username"] === null || params["username"] === undefined) { + throw new Error('Required parameter "params[\'username\']" missing.'); + } + + if (params["password"] === null || params["password"] === undefined) { + throw new Error('Required parameter "params[\'password\']" missing.'); + } + + let data: any = {}; + + + + data["Username"] = params["username"]; + + data["Password"] = params["password"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.credentialListSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CredentialListInstancePageOptions | ((error: Error | null, items: CredentialPage) => any), callback?: (error: Error | null, items: CredentialPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CredentialPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CredentialPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CredentialListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CredentialPage extends Page { +/** +* Initialize the CredentialPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: CredentialSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CredentialInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CredentialResource): CredentialInstance { + + return new CredentialInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.credentialListSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/domain.ts b/rest/api/v2010/domain.ts new file mode 100644 index 000000000..a986d516b --- /dev/null +++ b/rest/api/v2010/domain.ts @@ -0,0 +1,1179 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2010 from "../V2010"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { CredentialListMappingListInstance } from "./domain/credentialListMapping"; +import { IpAccessControlListMappingListInstance } from "./domain/ipAccessControlListMapping"; + + + + + +/** + * Options to pass to update a DomainInstance + */ +export interface DomainContextUpdateOptions { + /** A descriptive string that you created to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method we should use to call `voice_url` */ + "voiceMethod"?: string; + /** The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. */ + "voiceStatusCallbackMethod"?: string; + /** The URL that we should call to pass status parameters (such as call ended) to your application. */ + "voiceStatusCallbackUrl"?: string; + /** The URL we should call when the domain receives a call. */ + "voiceUrl"?: string; + /** Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. */ + "sipRegistration"?: boolean; + /** The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. */ + "domainName"?: string; + /** Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. */ + "emergencyCallingEnabled"?: boolean; + /** Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. */ + "secure"?: boolean; + /** The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. */ + "byocTrunkSid"?: string; + /** Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. */ + "emergencyCallerSid"?: string; +} + +/** + * Options to pass to create a DomainInstance + */ +export interface DomainListInstanceCreateOptions { + /** The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. */ + "domainName": string; + /** A descriptive string that you created to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The URL we should when the domain receives a call. */ + "voiceUrl"?: string; + /** The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. */ + "voiceMethod"?: string; + /** The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL that we should call to pass status parameters (such as call ended) to your application. */ + "voiceStatusCallbackUrl"?: string; + /** The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. */ + "voiceStatusCallbackMethod"?: string; + /** Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. */ + "sipRegistration"?: boolean; + /** Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. */ + "emergencyCallingEnabled"?: boolean; + /** Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. */ + "secure"?: boolean; + /** The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. */ + "byocTrunkSid"?: string; + /** Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. */ + "emergencyCallerSid"?: string; +} + +/** + * Options to pass to each + */ +export interface DomainListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DomainInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DomainListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DomainListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface DomainContext { + credentialListMappings: CredentialListMappingListInstance; + ipAccessControlListMappings: IpAccessControlListMappingListInstance; + + /** + * Remove a DomainInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a DomainInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a DomainInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance + */ + fetch(callback?: (error: Error | null, item?: DomainInstance) => any): Promise + + /** + * Fetch a DomainInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a DomainInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance + */ + update(callback?: (error: Error | null, item?: DomainInstance) => any): Promise; + /** + * Update a DomainInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance + */ + update(params: DomainContextUpdateOptions, callback?: (error: Error | null, item?: DomainInstance) => any): Promise; + + /** + * Update a DomainInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a DomainInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance with HTTP metadata + */ + updateWithHttpInfo(params: DomainContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DomainContextSolution { + "accountSid": string; + "sid": string; +} + +export class DomainContextImpl implements DomainContext { + protected _solution: DomainContextSolution; + protected _uri: string; + + protected _credentialListMappings?: CredentialListMappingListInstance; + protected _ipAccessControlListMappings?: IpAccessControlListMappingListInstance; + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/SIP/Domains/${sid}.json`; + } + + get credentialListMappings(): CredentialListMappingListInstance { + this._credentialListMappings = this._credentialListMappings || CredentialListMappingListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._credentialListMappings; + } + + get ipAccessControlListMappings(): IpAccessControlListMappingListInstance { + this._ipAccessControlListMappings = this._ipAccessControlListMappings || IpAccessControlListMappingListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._ipAccessControlListMappings; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: DomainInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DomainInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new DomainInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: DomainContextUpdateOptions | ((error: Error | null, item?: DomainInstance) => any),callback?: (error: Error | null, item?: DomainInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceStatusCallbackMethod"] !== undefined) + data["VoiceStatusCallbackMethod"] = params["voiceStatusCallbackMethod"]; + if (params["voiceStatusCallbackUrl"] !== undefined) + data["VoiceStatusCallbackUrl"] = params["voiceStatusCallbackUrl"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["sipRegistration"] !== undefined) + data["SipRegistration"] = serialize.bool(params["sipRegistration"]); + if (params["domainName"] !== undefined) + data["DomainName"] = params["domainName"]; + if (params["emergencyCallingEnabled"] !== undefined) + data["EmergencyCallingEnabled"] = serialize.bool(params["emergencyCallingEnabled"]); + if (params["secure"] !== undefined) + data["Secure"] = serialize.bool(params["secure"]); + if (params["byocTrunkSid"] !== undefined) + data["ByocTrunkSid"] = params["byocTrunkSid"]; + if (params["emergencyCallerSid"] !== undefined) + data["EmergencyCallerSid"] = params["emergencyCallerSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DomainInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: DomainContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceStatusCallbackMethod"] !== undefined) + data["VoiceStatusCallbackMethod"] = params["voiceStatusCallbackMethod"]; + if (params["voiceStatusCallbackUrl"] !== undefined) + data["VoiceStatusCallbackUrl"] = params["voiceStatusCallbackUrl"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["sipRegistration"] !== undefined) + data["SipRegistration"] = serialize.bool(params["sipRegistration"]); + if (params["domainName"] !== undefined) + data["DomainName"] = params["domainName"]; + if (params["emergencyCallingEnabled"] !== undefined) + data["EmergencyCallingEnabled"] = serialize.bool(params["emergencyCallingEnabled"]); + if (params["secure"] !== undefined) + data["Secure"] = serialize.bool(params["secure"]); + if (params["byocTrunkSid"] !== undefined) + data["ByocTrunkSid"] = params["byocTrunkSid"]; + if (params["emergencyCallerSid"] !== undefined) + data["EmergencyCallerSid"] = params["emergencyCallerSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new DomainInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DomainPayload extends TwilioResponsePayload { + domains: DomainResource[]; +} + +interface DomainResource { + account_sid: string; + api_version: string; + auth_type: string; + date_created: Date; + date_updated: Date; + domain_name: string; + friendly_name: string; + sid: string; + uri: string; + voice_fallback_method: string; + voice_fallback_url: string; + voice_method: string; + voice_status_callback_method: string; + voice_status_callback_url: string; + voice_url: string; + subresource_uris: Record; + sip_registration: boolean; + emergency_calling_enabled: boolean; + secure: boolean; + byoc_trunk_sid: string; + emergency_caller_sid: string; +} + +export class DomainInstance { + protected _solution: DomainContextSolution; + protected _context?: DomainContext; + + constructor(protected _version: V2010, payload: DomainResource, accountSid?: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.authType = (payload.auth_type); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.domainName = (payload.domain_name); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + this.uri = (payload.uri); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceMethod = (payload.voice_method); + this.voiceStatusCallbackMethod = (payload.voice_status_callback_method); + this.voiceStatusCallbackUrl = (payload.voice_status_callback_url); + this.voiceUrl = (payload.voice_url); + this.subresourceUris = (payload.subresource_uris); + this.sipRegistration = (payload.sip_registration); + this.emergencyCallingEnabled = (payload.emergency_calling_enabled); + this.secure = (payload.secure); + this.byocTrunkSid = (payload.byoc_trunk_sid); + this.emergencyCallerSid = (payload.emergency_caller_sid); + + this._solution = { accountSid: accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resource. + */ + accountSid: string; + /** + * The API version used to process the call. + */ + apiVersion: string; + /** + * The types of authentication you have mapped to your domain. Can be: `IP_ACL` and `CREDENTIAL_LIST`. If you have both defined for your domain, both will be returned in a comma delimited string. If `auth_type` is not defined, the domain will not be able to receive any traffic. + */ + authType: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \"-\" and must end with `sip.twilio.com`. + */ + domainName: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The unique string that that we created to identify the SipDomain resource. + */ + sid: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + */ + voiceFallbackMethod: string; + /** + * The URL that we call when an error occurs while retrieving or executing the TwiML requested from `voice_url`. + */ + voiceFallbackUrl: string; + /** + * The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + */ + voiceMethod: string; + /** + * The HTTP method we use to call `voice_status_callback_url`. Either `GET` or `POST`. + */ + voiceStatusCallbackMethod: string; + /** + * The URL that we call to pass status parameters (such as call ended) to your application. + */ + voiceStatusCallbackUrl: string; + /** + * The URL we call using the `voice_method` when the domain receives a call. + */ + voiceUrl: string; + /** + * A list of mapping resources associated with the SIP Domain resource identified by their relative URIs. + */ + subresourceUris: Record; + /** + * Whether to allow SIP Endpoints to register with the domain to receive calls. + */ + sipRegistration: boolean; + /** + * Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + */ + emergencyCallingEnabled: boolean; + /** + * Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + */ + secure: boolean; + /** + * The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + */ + byocTrunkSid: string; + /** + * Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + */ + emergencyCallerSid: string; + + private get _proxy(): DomainContext { + this._context = this._context || new DomainContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a DomainInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a DomainInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a DomainInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance + */ + fetch(callback?: (error: Error | null, item?: DomainInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DomainInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a DomainInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance + */ + update(callback?: (error: Error | null, item?: DomainInstance) => any): Promise; + /** + * Update a DomainInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance + */ + update(params: DomainContextUpdateOptions, callback?: (error: Error | null, item?: DomainInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: DomainInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a DomainInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a DomainInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance with HTTP metadata + */ + updateWithHttpInfo(params: DomainContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the credentialListMappings. + */ + credentialListMappings(): CredentialListMappingListInstance { + return this._proxy.credentialListMappings; + } + + /** + * Access the ipAccessControlListMappings. + */ + ipAccessControlListMappings(): IpAccessControlListMappingListInstance { + return this._proxy.ipAccessControlListMappings; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + authType: this.authType, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + domainName: this.domainName, + friendlyName: this.friendlyName, + sid: this.sid, + uri: this.uri, + voiceFallbackMethod: this.voiceFallbackMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceMethod: this.voiceMethod, + voiceStatusCallbackMethod: this.voiceStatusCallbackMethod, + voiceStatusCallbackUrl: this.voiceStatusCallbackUrl, + voiceUrl: this.voiceUrl, + subresourceUris: this.subresourceUris, + sipRegistration: this.sipRegistration, + emergencyCallingEnabled: this.emergencyCallingEnabled, + secure: this.secure, + byocTrunkSid: this.byocTrunkSid, + emergencyCallerSid: this.emergencyCallerSid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DomainSolution { + accountSid: string; +} + +export interface DomainListInstance { + _version: V2010; + _solution: DomainSolution; + _uri: string; + + (accountSid: string, sid: string, ): DomainContext; + get(accountSid: string, sid: string, ): DomainContext; + + + + + + + + + /** + * Create a DomainInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance + */ + create(params: DomainListInstanceCreateOptions, callback?: (error: Error | null, item?: DomainInstance) => any): Promise; + + /** + * Create a DomainInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainInstance with HTTP metadata + */ + createWithHttpInfo(params: DomainListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams DomainInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DomainListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DomainInstance, done: (err?: Error) => void) => void): void; + each(params: DomainListInstanceEachOptions, callback?: (item: DomainInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DomainInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DomainListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DomainInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DomainListInstanceEachOptions, callback?: (item: DomainInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DomainInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DomainPage) => any): Promise; + /** + * Retrieve a single target page of DomainInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists DomainInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DomainListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DomainInstance[]) => any): Promise; + list(params: DomainListInstanceOptions, callback?: (error: Error | null, items: DomainInstance[]) => any): Promise; + /** + * Lists DomainInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DomainListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: DomainListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of DomainInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DomainListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DomainPage) => any): Promise; + page(params: DomainListInstancePageOptions, callback?: (error: Error | null, items: DomainPage) => any): Promise; + /** + * Retrieve a single page of DomainInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DomainListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: DomainListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DomainListInstance(version: V2010, accountSid: string): DomainListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((accountSid, sid, ) => instance.get(accountSid, sid, )) as DomainListInstance; + + instance.get = function get(accountSid, sid, ): DomainContext { + return new DomainContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/SIP/Domains.json`; + + instance.create = function create(params: DomainListInstanceCreateOptions, callback?: (error: Error | null, items: DomainInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["domainName"] === null || params["domainName"] === undefined) { + throw new Error('Required parameter "params[\'domainName\']" missing.'); + } + + let data: any = {}; + + + + data["DomainName"] = params["domainName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceStatusCallbackUrl"] !== undefined) + data["VoiceStatusCallbackUrl"] = params["voiceStatusCallbackUrl"]; + if (params["voiceStatusCallbackMethod"] !== undefined) + data["VoiceStatusCallbackMethod"] = params["voiceStatusCallbackMethod"]; + if (params["sipRegistration"] !== undefined) + data["SipRegistration"] = serialize.bool(params["sipRegistration"]); + if (params["emergencyCallingEnabled"] !== undefined) + data["EmergencyCallingEnabled"] = serialize.bool(params["emergencyCallingEnabled"]); + if (params["secure"] !== undefined) + data["Secure"] = serialize.bool(params["secure"]); + if (params["byocTrunkSid"] !== undefined) + data["ByocTrunkSid"] = params["byocTrunkSid"]; + if (params["emergencyCallerSid"] !== undefined) + data["EmergencyCallerSid"] = params["emergencyCallerSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DomainInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: DomainListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["domainName"] === null || params["domainName"] === undefined) { + throw new Error('Required parameter "params[\'domainName\']" missing.'); + } + + let data: any = {}; + + + + data["DomainName"] = params["domainName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceStatusCallbackUrl"] !== undefined) + data["VoiceStatusCallbackUrl"] = params["voiceStatusCallbackUrl"]; + if (params["voiceStatusCallbackMethod"] !== undefined) + data["VoiceStatusCallbackMethod"] = params["voiceStatusCallbackMethod"]; + if (params["sipRegistration"] !== undefined) + data["SipRegistration"] = serialize.bool(params["sipRegistration"]); + if (params["emergencyCallingEnabled"] !== undefined) + data["EmergencyCallingEnabled"] = serialize.bool(params["emergencyCallingEnabled"]); + if (params["secure"] !== undefined) + data["Secure"] = serialize.bool(params["secure"]); + if (params["byocTrunkSid"] !== undefined) + data["ByocTrunkSid"] = params["byocTrunkSid"]; + if (params["emergencyCallerSid"] !== undefined) + data["EmergencyCallerSid"] = params["emergencyCallerSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new DomainInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: DomainListInstancePageOptions | ((error: Error | null, items: DomainPage) => any), callback?: (error: Error | null, items: DomainPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DomainPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DomainPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DomainPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DomainListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DomainPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DomainPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class DomainPage extends Page { +/** +* Initialize the DomainPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: DomainSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DomainInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DomainResource): DomainInstance { + + return new DomainInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/domain/credentialListMapping.ts b/rest/api/v2010/domain/credentialListMapping.ts new file mode 100644 index 000000000..7773cc167 --- /dev/null +++ b/rest/api/v2010/domain/credentialListMapping.ts @@ -0,0 +1,757 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a CredentialListMappingInstance + */ +export interface CredentialListMappingListInstanceCreateOptions { + /** A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. */ + "credentialListSid": string; +} + +/** + * Options to pass to each + */ +export interface CredentialListMappingListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CredentialListMappingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CredentialListMappingListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CredentialListMappingListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CredentialListMappingContext { + + /** + * Remove a CredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a CredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a CredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListMappingInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialListMappingInstance) => any): Promise + + /** + * Fetch a CredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CredentialListMappingContextSolution { + "accountSid": string; + "domainSid": string; + "sid": string; +} + +export class CredentialListMappingContextImpl implements CredentialListMappingContext { + protected _solution: CredentialListMappingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, domainSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, domainSid, sid, }; + this._uri = `/Accounts/${accountSid}/SIP/Domains/${domainSid}/CredentialListMappings/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CredentialListMappingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CredentialListMappingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.domainSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialListMappingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.domainSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CredentialListMappingPayload extends TwilioResponsePayload { + credential_list_mappings: CredentialListMappingResource[]; +} + +interface CredentialListMappingResource { + account_sid: string; + date_created: Date; + date_updated: Date; + domain_sid: string; + friendly_name: string; + sid: string; + uri: string; +} + +export class CredentialListMappingInstance { + protected _solution: CredentialListMappingContextSolution; + protected _context?: CredentialListMappingContext; + + constructor(protected _version: V2010, payload: CredentialListMappingResource, accountSid: string, domainSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.domainSid = (payload.domain_sid); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + this.uri = (payload.uri); + + this._solution = { accountSid, domainSid, sid: sid, }; + } + + /** + * The unique id of the Account that is responsible for this resource. + */ + accountSid: string; + /** + * The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateCreated: Date; + /** + * The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateUpdated: Date; + /** + * The unique string that is created to identify the SipDomain resource. + */ + domainSid: string; + /** + * A human readable descriptive text for this resource, up to 64 characters long. + */ + friendlyName: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The URI for this resource, relative to `https://api.twilio.com` + */ + uri: string; + + private get _proxy(): CredentialListMappingContext { + this._context = this._context || new CredentialListMappingContextImpl(this._version, this._solution.accountSid, this._solution.domainSid, this._solution.sid); + return this._context; + } + + /** + * Remove a CredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CredentialListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListMappingInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialListMappingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CredentialListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + domainSid: this.domainSid, + friendlyName: this.friendlyName, + sid: this.sid, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CredentialListMappingSolution { + accountSid: string; + domainSid: string; +} + +export interface CredentialListMappingListInstance { + _version: V2010; + _solution: CredentialListMappingSolution; + _uri: string; + + (sid: string, ): CredentialListMappingContext; + get(sid: string, ): CredentialListMappingContext; + + + + + + + /** + * Create a CredentialListMappingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListMappingInstance + */ + create(params: CredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: CredentialListMappingInstance) => any): Promise; + + /** + * Create a CredentialListMappingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListMappingInstance with HTTP metadata + */ + createWithHttpInfo(params: CredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CredentialListMappingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CredentialListMappingInstance, done: (err?: Error) => void) => void): void; + each(params: CredentialListMappingListInstanceEachOptions, callback?: (item: CredentialListMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CredentialListMappingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CredentialListMappingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CredentialListMappingListInstanceEachOptions, callback?: (item: CredentialListMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CredentialListMappingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialListMappingPage) => any): Promise; + /** + * Retrieve a single target page of CredentialListMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CredentialListMappingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CredentialListMappingInstance[]) => any): Promise; + list(params: CredentialListMappingListInstanceOptions, callback?: (error: Error | null, items: CredentialListMappingInstance[]) => any): Promise; + /** + * Lists CredentialListMappingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CredentialListMappingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CredentialListMappingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CredentialListMappingPage) => any): Promise; + page(params: CredentialListMappingListInstancePageOptions, callback?: (error: Error | null, items: CredentialListMappingPage) => any): Promise; + /** + * Retrieve a single page of CredentialListMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CredentialListMappingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CredentialListMappingListInstance(version: V2010, accountSid: string, domainSid: string): CredentialListMappingListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as CredentialListMappingListInstance; + + instance.get = function get(sid, ): CredentialListMappingContext { + return new CredentialListMappingContextImpl(version, accountSid, domainSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, domainSid, }; + instance._uri = `/Accounts/${accountSid}/SIP/Domains/${domainSid}/CredentialListMappings.json`; + + instance.create = function create(params: CredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, items: CredentialListMappingInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["credentialListSid"] === null || params["credentialListSid"] === undefined) { + throw new Error('Required parameter "params[\'credentialListSid\']" missing.'); + } + + let data: any = {}; + + + + data["CredentialListSid"] = params["credentialListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialListMappingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CredentialListMappingListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["credentialListSid"] === null || params["credentialListSid"] === undefined) { + throw new Error('Required parameter "params[\'credentialListSid\']" missing.'); + } + + let data: any = {}; + + + + data["CredentialListSid"] = params["credentialListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialListMappingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CredentialListMappingListInstancePageOptions | ((error: Error | null, items: CredentialListMappingPage) => any), callback?: (error: Error | null, items: CredentialListMappingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CredentialListMappingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialListMappingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CredentialListMappingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CredentialListMappingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialListMappingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialListMappingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CredentialListMappingPage extends Page { +/** +* Initialize the CredentialListMappingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: CredentialListMappingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CredentialListMappingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CredentialListMappingResource): CredentialListMappingInstance { + + return new CredentialListMappingInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.domainSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/domain/ipAccessControlListMapping.ts b/rest/api/v2010/domain/ipAccessControlListMapping.ts new file mode 100644 index 000000000..4b5451fc0 --- /dev/null +++ b/rest/api/v2010/domain/ipAccessControlListMapping.ts @@ -0,0 +1,757 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a IpAccessControlListMappingInstance + */ +export interface IpAccessControlListMappingListInstanceCreateOptions { + /** The unique id of the IP access control list to map to the SIP domain. */ + "ipAccessControlListSid": string; +} + +/** + * Options to pass to each + */ +export interface IpAccessControlListMappingListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: IpAccessControlListMappingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface IpAccessControlListMappingListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface IpAccessControlListMappingListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface IpAccessControlListMappingContext { + + /** + * Remove a IpAccessControlListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a IpAccessControlListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a IpAccessControlListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListMappingInstance + */ + fetch(callback?: (error: Error | null, item?: IpAccessControlListMappingInstance) => any): Promise + + /** + * Fetch a IpAccessControlListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface IpAccessControlListMappingContextSolution { + "accountSid": string; + "domainSid": string; + "sid": string; +} + +export class IpAccessControlListMappingContextImpl implements IpAccessControlListMappingContext { + protected _solution: IpAccessControlListMappingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, domainSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, domainSid, sid, }; + this._uri = `/Accounts/${accountSid}/SIP/Domains/${domainSid}/IpAccessControlListMappings/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: IpAccessControlListMappingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new IpAccessControlListMappingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.domainSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new IpAccessControlListMappingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.domainSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface IpAccessControlListMappingPayload extends TwilioResponsePayload { + ip_access_control_list_mappings: IpAccessControlListMappingResource[]; +} + +interface IpAccessControlListMappingResource { + account_sid: string; + date_created: Date; + date_updated: Date; + domain_sid: string; + friendly_name: string; + sid: string; + uri: string; +} + +export class IpAccessControlListMappingInstance { + protected _solution: IpAccessControlListMappingContextSolution; + protected _context?: IpAccessControlListMappingContext; + + constructor(protected _version: V2010, payload: IpAccessControlListMappingResource, accountSid: string, domainSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.domainSid = (payload.domain_sid); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + this.uri = (payload.uri); + + this._solution = { accountSid, domainSid, sid: sid, }; + } + + /** + * The unique id of the Account that is responsible for this resource. + */ + accountSid: string; + /** + * The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateCreated: Date; + /** + * The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateUpdated: Date; + /** + * The unique string that is created to identify the SipDomain resource. + */ + domainSid: string; + /** + * A human readable descriptive text for this resource, up to 64 characters long. + */ + friendlyName: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The URI for this resource, relative to `https://api.twilio.com` + */ + uri: string; + + private get _proxy(): IpAccessControlListMappingContext { + this._context = this._context || new IpAccessControlListMappingContextImpl(this._version, this._solution.accountSid, this._solution.domainSid, this._solution.sid); + return this._context; + } + + /** + * Remove a IpAccessControlListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a IpAccessControlListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a IpAccessControlListMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListMappingInstance + */ + fetch(callback?: (error: Error | null, item?: IpAccessControlListMappingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a IpAccessControlListMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + domainSid: this.domainSid, + friendlyName: this.friendlyName, + sid: this.sid, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface IpAccessControlListMappingSolution { + accountSid: string; + domainSid: string; +} + +export interface IpAccessControlListMappingListInstance { + _version: V2010; + _solution: IpAccessControlListMappingSolution; + _uri: string; + + (sid: string, ): IpAccessControlListMappingContext; + get(sid: string, ): IpAccessControlListMappingContext; + + + + + + + /** + * Create a IpAccessControlListMappingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListMappingInstance + */ + create(params: IpAccessControlListMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: IpAccessControlListMappingInstance) => any): Promise; + + /** + * Create a IpAccessControlListMappingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListMappingInstance with HTTP metadata + */ + createWithHttpInfo(params: IpAccessControlListMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams IpAccessControlListMappingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: IpAccessControlListMappingInstance, done: (err?: Error) => void) => void): void; + each(params: IpAccessControlListMappingListInstanceEachOptions, callback?: (item: IpAccessControlListMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams IpAccessControlListMappingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: IpAccessControlListMappingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: IpAccessControlListMappingListInstanceEachOptions, callback?: (item: IpAccessControlListMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of IpAccessControlListMappingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: IpAccessControlListMappingPage) => any): Promise; + /** + * Retrieve a single target page of IpAccessControlListMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists IpAccessControlListMappingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: IpAccessControlListMappingInstance[]) => any): Promise; + list(params: IpAccessControlListMappingListInstanceOptions, callback?: (error: Error | null, items: IpAccessControlListMappingInstance[]) => any): Promise; + /** + * Lists IpAccessControlListMappingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: IpAccessControlListMappingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of IpAccessControlListMappingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: IpAccessControlListMappingPage) => any): Promise; + page(params: IpAccessControlListMappingListInstancePageOptions, callback?: (error: Error | null, items: IpAccessControlListMappingPage) => any): Promise; + /** + * Retrieve a single page of IpAccessControlListMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: IpAccessControlListMappingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function IpAccessControlListMappingListInstance(version: V2010, accountSid: string, domainSid: string): IpAccessControlListMappingListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as IpAccessControlListMappingListInstance; + + instance.get = function get(sid, ): IpAccessControlListMappingContext { + return new IpAccessControlListMappingContextImpl(version, accountSid, domainSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, domainSid, }; + instance._uri = `/Accounts/${accountSid}/SIP/Domains/${domainSid}/IpAccessControlListMappings.json`; + + instance.create = function create(params: IpAccessControlListMappingListInstanceCreateOptions, callback?: (error: Error | null, items: IpAccessControlListMappingInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["ipAccessControlListSid"] === null || params["ipAccessControlListSid"] === undefined) { + throw new Error('Required parameter "params[\'ipAccessControlListSid\']" missing.'); + } + + let data: any = {}; + + + + data["IpAccessControlListSid"] = params["ipAccessControlListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IpAccessControlListMappingInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: IpAccessControlListMappingListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["ipAccessControlListSid"] === null || params["ipAccessControlListSid"] === undefined) { + throw new Error('Required parameter "params[\'ipAccessControlListSid\']" missing.'); + } + + let data: any = {}; + + + + data["IpAccessControlListSid"] = params["ipAccessControlListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new IpAccessControlListMappingInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: IpAccessControlListMappingListInstancePageOptions | ((error: Error | null, items: IpAccessControlListMappingPage) => any), callback?: (error: Error | null, items: IpAccessControlListMappingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new IpAccessControlListMappingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: IpAccessControlListMappingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new IpAccessControlListMappingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: IpAccessControlListMappingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpAccessControlListMappingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpAccessControlListMappingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class IpAccessControlListMappingPage extends Page { +/** +* Initialize the IpAccessControlListMappingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: IpAccessControlListMappingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of IpAccessControlListMappingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: IpAccessControlListMappingResource): IpAccessControlListMappingInstance { + + return new IpAccessControlListMappingInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.domainSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/ipAccessControlList.ts b/rest/api/v2010/ipAccessControlList.ts new file mode 100644 index 000000000..bd3e1c459 --- /dev/null +++ b/rest/api/v2010/ipAccessControlList.ts @@ -0,0 +1,892 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2010 from "../V2010"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { IpAddressListInstance } from "./ipAccessControlList/ipAddress"; + + + + + +/** + * Options to pass to update a IpAccessControlListInstance + */ +export interface IpAccessControlListContextUpdateOptions { + /** A human readable descriptive text, up to 255 characters long. */ + "friendlyName": string; +} + +/** + * Options to pass to create a IpAccessControlListInstance + */ +export interface IpAccessControlListListInstanceCreateOptions { + /** A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. */ + "friendlyName": string; +} + +/** + * Options to pass to each + */ +export interface IpAccessControlListListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: IpAccessControlListInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface IpAccessControlListListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface IpAccessControlListListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface IpAccessControlListContext { + ipAddresses: IpAddressListInstance; + + /** + * Remove a IpAccessControlListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a IpAccessControlListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a IpAccessControlListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance + */ + fetch(callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise + + /** + * Fetch a IpAccessControlListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a IpAccessControlListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance + */ + update(params: IpAccessControlListContextUpdateOptions, callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise; + + /** + * Update a IpAccessControlListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance with HTTP metadata + */ + updateWithHttpInfo(params: IpAccessControlListContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface IpAccessControlListContextSolution { + "accountSid": string; + "sid": string; +} + +export class IpAccessControlListContextImpl implements IpAccessControlListContext { + protected _solution: IpAccessControlListContextSolution; + protected _uri: string; + + protected _ipAddresses?: IpAddressListInstance; + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/SIP/IpAccessControlLists/${sid}.json`; + } + + get ipAddresses(): IpAddressListInstance { + this._ipAddresses = this._ipAddresses || IpAddressListInstance(this._version, this._solution.accountSid, this._solution.sid); + return this._ipAddresses; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new IpAccessControlListInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new IpAccessControlListInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: IpAccessControlListContextUpdateOptions,callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IpAccessControlListInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: IpAccessControlListContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new IpAccessControlListInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface IpAccessControlListPayload extends TwilioResponsePayload { + ip_access_control_lists: IpAccessControlListResource[]; +} + +interface IpAccessControlListResource { + sid: string; + account_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + subresource_uris: Record; + uri: string; +} + +export class IpAccessControlListInstance { + protected _solution: IpAccessControlListContextSolution; + protected _context?: IpAccessControlListContext; + + constructor(protected _version: V2010, payload: IpAccessControlListResource, accountSid?: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + + this._solution = { accountSid: accountSid, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) that owns this resource. + */ + accountSid: string; + /** + * A human readable descriptive text, up to 255 characters long. + */ + friendlyName: string; + /** + * The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateCreated: Date; + /** + * The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateUpdated: Date; + /** + * A list of the IpAddress resources associated with this IP access control list resource. + */ + subresourceUris: Record; + /** + * The URI for this resource, relative to `https://api.twilio.com` + */ + uri: string; + + private get _proxy(): IpAccessControlListContext { + this._context = this._context || new IpAccessControlListContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a IpAccessControlListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a IpAccessControlListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a IpAccessControlListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance + */ + fetch(callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a IpAccessControlListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a IpAccessControlListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance + */ + update(params: IpAccessControlListContextUpdateOptions, callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a IpAccessControlListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance with HTTP metadata + */ + updateWithHttpInfo(params: IpAccessControlListContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the ipAddresses. + */ + ipAddresses(): IpAddressListInstance { + return this._proxy.ipAddresses; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + subresourceUris: this.subresourceUris, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface IpAccessControlListSolution { + accountSid: string; +} + +export interface IpAccessControlListListInstance { + _version: V2010; + _solution: IpAccessControlListSolution; + _uri: string; + + (accountSid: string, sid: string, ): IpAccessControlListContext; + get(accountSid: string, sid: string, ): IpAccessControlListContext; + + + + + + + + + /** + * Create a IpAccessControlListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance + */ + create(params: IpAccessControlListListInstanceCreateOptions, callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise; + + /** + * Create a IpAccessControlListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance with HTTP metadata + */ + createWithHttpInfo(params: IpAccessControlListListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams IpAccessControlListInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: IpAccessControlListInstance, done: (err?: Error) => void) => void): void; + each(params: IpAccessControlListListInstanceEachOptions, callback?: (item: IpAccessControlListInstance, done: (err?: Error) => void) => void): void; + /** + * Streams IpAccessControlListInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: IpAccessControlListInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: IpAccessControlListListInstanceEachOptions, callback?: (item: IpAccessControlListInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of IpAccessControlListInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: IpAccessControlListPage) => any): Promise; + /** + * Retrieve a single target page of IpAccessControlListInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists IpAccessControlListInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: IpAccessControlListInstance[]) => any): Promise; + list(params: IpAccessControlListListInstanceOptions, callback?: (error: Error | null, items: IpAccessControlListInstance[]) => any): Promise; + /** + * Lists IpAccessControlListInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: IpAccessControlListListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of IpAccessControlListInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: IpAccessControlListPage) => any): Promise; + page(params: IpAccessControlListListInstancePageOptions, callback?: (error: Error | null, items: IpAccessControlListPage) => any): Promise; + /** + * Retrieve a single page of IpAccessControlListInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: IpAccessControlListListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function IpAccessControlListListInstance(version: V2010, accountSid: string): IpAccessControlListListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((accountSid, sid, ) => instance.get(accountSid, sid, )) as IpAccessControlListListInstance; + + instance.get = function get(accountSid, sid, ): IpAccessControlListContext { + return new IpAccessControlListContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/SIP/IpAccessControlLists.json`; + + instance.create = function create(params: IpAccessControlListListInstanceCreateOptions, callback?: (error: Error | null, items: IpAccessControlListInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IpAccessControlListInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: IpAccessControlListListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new IpAccessControlListInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: IpAccessControlListListInstancePageOptions | ((error: Error | null, items: IpAccessControlListPage) => any), callback?: (error: Error | null, items: IpAccessControlListPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new IpAccessControlListPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: IpAccessControlListPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new IpAccessControlListPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: IpAccessControlListListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpAccessControlListPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpAccessControlListPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class IpAccessControlListPage extends Page { +/** +* Initialize the IpAccessControlListPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: IpAccessControlListSolution) { + super(version, response, solution); + } + + /** + * Build an instance of IpAccessControlListInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: IpAccessControlListResource): IpAccessControlListInstance { + + return new IpAccessControlListInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/ipAccessControlList/ipAddress.ts b/rest/api/v2010/ipAccessControlList/ipAddress.ts new file mode 100644 index 000000000..e6ceb3f15 --- /dev/null +++ b/rest/api/v2010/ipAccessControlList/ipAddress.ts @@ -0,0 +1,964 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a IpAddressInstance + */ +export interface IpAddressContextUpdateOptions { + /** An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. */ + "ipAddress"?: string; + /** A human readable descriptive text for this resource, up to 255 characters long. */ + "friendlyName"?: string; + /** An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. */ + "cidrPrefixLength"?: number; +} + +/** + * Options to pass to create a IpAddressInstance + */ +export interface IpAddressListInstanceCreateOptions { + /** A human readable descriptive text for this resource, up to 255 characters long. */ + "friendlyName": string; + /** An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. */ + "ipAddress": string; + /** An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. */ + "cidrPrefixLength"?: number; +} + +/** + * Options to pass to each + */ +export interface IpAddressListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: IpAddressInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface IpAddressListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface IpAddressListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface IpAddressContext { + + /** + * Remove a IpAddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a IpAddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a IpAddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance + */ + fetch(callback?: (error: Error | null, item?: IpAddressInstance) => any): Promise + + /** + * Fetch a IpAddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a IpAddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance + */ + update(callback?: (error: Error | null, item?: IpAddressInstance) => any): Promise; + /** + * Update a IpAddressInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance + */ + update(params: IpAddressContextUpdateOptions, callback?: (error: Error | null, item?: IpAddressInstance) => any): Promise; + + /** + * Update a IpAddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a IpAddressInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance with HTTP metadata + */ + updateWithHttpInfo(params: IpAddressContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface IpAddressContextSolution { + "accountSid": string; + "ipAccessControlListSid": string; + "sid": string; +} + +export class IpAddressContextImpl implements IpAddressContext { + protected _solution: IpAddressContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, ipAccessControlListSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(ipAccessControlListSid)) { + throw new Error('Parameter \'ipAccessControlListSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, ipAccessControlListSid, sid, }; + this._uri = `/Accounts/${accountSid}/SIP/IpAccessControlLists/${ipAccessControlListSid}/IpAddresses/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: IpAddressInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new IpAddressInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.ipAccessControlListSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new IpAddressInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.ipAccessControlListSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: IpAddressContextUpdateOptions | ((error: Error | null, item?: IpAddressInstance) => any),callback?: (error: Error | null, item?: IpAddressInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ipAddress"] !== undefined) + data["IpAddress"] = params["ipAddress"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["cidrPrefixLength"] !== undefined) + data["CidrPrefixLength"] = params["cidrPrefixLength"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IpAddressInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.ipAccessControlListSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: IpAddressContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ipAddress"] !== undefined) + data["IpAddress"] = params["ipAddress"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["cidrPrefixLength"] !== undefined) + data["CidrPrefixLength"] = params["cidrPrefixLength"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new IpAddressInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.ipAccessControlListSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface IpAddressPayload extends TwilioResponsePayload { + ip_addresses: IpAddressResource[]; +} + +interface IpAddressResource { + sid: string; + account_sid: string; + friendly_name: string; + ip_address: string; + cidr_prefix_length: number; + ip_access_control_list_sid: string; + date_created: Date; + date_updated: Date; + uri: string; +} + +export class IpAddressInstance { + protected _solution: IpAddressContextSolution; + protected _context?: IpAddressContext; + + constructor(protected _version: V2010, payload: IpAddressResource, accountSid: string, ipAccessControlListSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.ipAddress = (payload.ip_address); + this.cidrPrefixLength = deserialize.integer(payload.cidr_prefix_length); + this.ipAccessControlListSid = (payload.ip_access_control_list_sid); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.uri = (payload.uri); + + this._solution = { accountSid, ipAccessControlListSid, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The unique id of the Account that is responsible for this resource. + */ + accountSid: string; + /** + * A human readable descriptive text for this resource, up to 255 characters long. + */ + friendlyName: string; + /** + * An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + */ + ipAddress: string; + /** + * An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + */ + cidrPrefixLength: number; + /** + * The unique id of the IpAccessControlList resource that includes this resource. + */ + ipAccessControlListSid: string; + /** + * The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateCreated: Date; + /** + * The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + */ + dateUpdated: Date; + /** + * The URI for this resource, relative to `https://api.twilio.com` + */ + uri: string; + + private get _proxy(): IpAddressContext { + this._context = this._context || new IpAddressContextImpl(this._version, this._solution.accountSid, this._solution.ipAccessControlListSid, this._solution.sid); + return this._context; + } + + /** + * Remove a IpAddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a IpAddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a IpAddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance + */ + fetch(callback?: (error: Error | null, item?: IpAddressInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a IpAddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a IpAddressInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance + */ + update(callback?: (error: Error | null, item?: IpAddressInstance) => any): Promise; + /** + * Update a IpAddressInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance + */ + update(params: IpAddressContextUpdateOptions, callback?: (error: Error | null, item?: IpAddressInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: IpAddressInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a IpAddressInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a IpAddressInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance with HTTP metadata + */ + updateWithHttpInfo(params: IpAddressContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + ipAddress: this.ipAddress, + cidrPrefixLength: this.cidrPrefixLength, + ipAccessControlListSid: this.ipAccessControlListSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + uri: this.uri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface IpAddressSolution { + accountSid: string; + ipAccessControlListSid: string; +} + +export interface IpAddressListInstance { + _version: V2010; + _solution: IpAddressSolution; + _uri: string; + + (sid: string, ): IpAddressContext; + get(sid: string, ): IpAddressContext; + + + + + + + + + /** + * Create a IpAddressInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance + */ + create(params: IpAddressListInstanceCreateOptions, callback?: (error: Error | null, item?: IpAddressInstance) => any): Promise; + + /** + * Create a IpAddressInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAddressInstance with HTTP metadata + */ + createWithHttpInfo(params: IpAddressListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams IpAddressInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAddressListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: IpAddressInstance, done: (err?: Error) => void) => void): void; + each(params: IpAddressListInstanceEachOptions, callback?: (item: IpAddressInstance, done: (err?: Error) => void) => void): void; + /** + * Streams IpAddressInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAddressListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: IpAddressInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: IpAddressListInstanceEachOptions, callback?: (item: IpAddressInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of IpAddressInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: IpAddressPage) => any): Promise; + /** + * Retrieve a single target page of IpAddressInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists IpAddressInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAddressListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: IpAddressInstance[]) => any): Promise; + list(params: IpAddressListInstanceOptions, callback?: (error: Error | null, items: IpAddressInstance[]) => any): Promise; + /** + * Lists IpAddressInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAddressListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: IpAddressListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of IpAddressInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAddressListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: IpAddressPage) => any): Promise; + page(params: IpAddressListInstancePageOptions, callback?: (error: Error | null, items: IpAddressPage) => any): Promise; + /** + * Retrieve a single page of IpAddressInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAddressListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: IpAddressListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function IpAddressListInstance(version: V2010, accountSid: string, ipAccessControlListSid: string): IpAddressListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(ipAccessControlListSid)) { + throw new Error('Parameter \'ipAccessControlListSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as IpAddressListInstance; + + instance.get = function get(sid, ): IpAddressContext { + return new IpAddressContextImpl(version, accountSid, ipAccessControlListSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, ipAccessControlListSid, }; + instance._uri = `/Accounts/${accountSid}/SIP/IpAccessControlLists/${ipAccessControlListSid}/IpAddresses.json`; + + instance.create = function create(params: IpAddressListInstanceCreateOptions, callback?: (error: Error | null, items: IpAddressInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["ipAddress"] === null || params["ipAddress"] === undefined) { + throw new Error('Required parameter "params[\'ipAddress\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["IpAddress"] = params["ipAddress"]; + if (params["cidrPrefixLength"] !== undefined) + data["CidrPrefixLength"] = params["cidrPrefixLength"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IpAddressInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.ipAccessControlListSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: IpAddressListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["ipAddress"] === null || params["ipAddress"] === undefined) { + throw new Error('Required parameter "params[\'ipAddress\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["IpAddress"] = params["ipAddress"]; + if (params["cidrPrefixLength"] !== undefined) + data["CidrPrefixLength"] = params["cidrPrefixLength"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new IpAddressInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.ipAccessControlListSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: IpAddressListInstancePageOptions | ((error: Error | null, items: IpAddressPage) => any), callback?: (error: Error | null, items: IpAddressPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new IpAddressPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: IpAddressPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new IpAddressPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: IpAddressListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpAddressPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpAddressPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class IpAddressPage extends Page { +/** +* Initialize the IpAddressPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: IpAddressSolution) { + super(version, response, solution); + } + + /** + * Build an instance of IpAddressInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: IpAddressResource): IpAddressInstance { + + return new IpAddressInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.ipAccessControlListSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/record.ts b/rest/api/v2010/record.ts new file mode 100644 index 000000000..73fd8a1db --- /dev/null +++ b/rest/api/v2010/record.ts @@ -0,0 +1,618 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2010 from "../V2010"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { AllTimeListInstance } from "./record/allTime"; +import { DailyListInstance } from "./record/daily"; +import { LastMonthListInstance } from "./record/lastMonth"; +import { MonthlyListInstance } from "./record/monthly"; +import { ThisMonthListInstance } from "./record/thisMonth"; +import { TodayListInstance } from "./record/today"; +import { YearlyListInstance } from "./record/yearly"; +import { YesterdayListInstance } from "./record/yesterday"; + + + +/** + * Options to pass to each + */ +export interface RecordListInstanceEachOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RecordInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RecordListInstanceOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RecordListInstancePageOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface RecordSolution { + accountSid: string; +} + +export interface RecordListInstance { + _version: V2010; + _solution: RecordSolution; + _uri: string; + + + _allTime?: AllTimeListInstance; + allTime: AllTimeListInstance; + _daily?: DailyListInstance; + daily: DailyListInstance; + _lastMonth?: LastMonthListInstance; + lastMonth: LastMonthListInstance; + _monthly?: MonthlyListInstance; + monthly: MonthlyListInstance; + _thisMonth?: ThisMonthListInstance; + thisMonth: ThisMonthListInstance; + _today?: TodayListInstance; + today: TodayListInstance; + _yearly?: YearlyListInstance; + yearly: YearlyListInstance; + _yesterday?: YesterdayListInstance; + yesterday: YesterdayListInstance; + + + /** + * Streams RecordInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RecordInstance, done: (err?: Error) => void) => void): void; + each(params: RecordListInstanceEachOptions, callback?: (item: RecordInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RecordInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RecordInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RecordListInstanceEachOptions, callback?: (item: RecordInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RecordInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RecordPage) => any): Promise; + /** + * Retrieve a single target page of RecordInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RecordInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RecordInstance[]) => any): Promise; + list(params: RecordListInstanceOptions, callback?: (error: Error | null, items: RecordInstance[]) => any): Promise; + /** + * Lists RecordInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RecordListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RecordInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RecordPage) => any): Promise; + page(params: RecordListInstancePageOptions, callback?: (error: Error | null, items: RecordPage) => any): Promise; + /** + * Retrieve a single page of RecordInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RecordListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RecordListInstance(version: V2010, accountSid: string): RecordListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as RecordListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Usage/Records.json`; + + Object.defineProperty(instance, "allTime", { + get: function allTime() { + if (!instance._allTime) { + instance._allTime = AllTimeListInstance(instance._version, instance._solution.accountSid); + } + return instance._allTime; + } + }); + + Object.defineProperty(instance, "daily", { + get: function daily() { + if (!instance._daily) { + instance._daily = DailyListInstance(instance._version, instance._solution.accountSid); + } + return instance._daily; + } + }); + + Object.defineProperty(instance, "lastMonth", { + get: function lastMonth() { + if (!instance._lastMonth) { + instance._lastMonth = LastMonthListInstance(instance._version, instance._solution.accountSid); + } + return instance._lastMonth; + } + }); + + Object.defineProperty(instance, "monthly", { + get: function monthly() { + if (!instance._monthly) { + instance._monthly = MonthlyListInstance(instance._version, instance._solution.accountSid); + } + return instance._monthly; + } + }); + + Object.defineProperty(instance, "thisMonth", { + get: function thisMonth() { + if (!instance._thisMonth) { + instance._thisMonth = ThisMonthListInstance(instance._version, instance._solution.accountSid); + } + return instance._thisMonth; + } + }); + + Object.defineProperty(instance, "today", { + get: function today() { + if (!instance._today) { + instance._today = TodayListInstance(instance._version, instance._solution.accountSid); + } + return instance._today; + } + }); + + Object.defineProperty(instance, "yearly", { + get: function yearly() { + if (!instance._yearly) { + instance._yearly = YearlyListInstance(instance._version, instance._solution.accountSid); + } + return instance._yearly; + } + }); + + Object.defineProperty(instance, "yesterday", { + get: function yesterday() { + if (!instance._yesterday) { + instance._yesterday = YesterdayListInstance(instance._version, instance._solution.accountSid); + } + return instance._yesterday; + } + }); + + instance.page = function page(params?: RecordListInstancePageOptions | ((error: Error | null, items: RecordPage) => any), callback?: (error: Error | null, items: RecordPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RecordPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RecordPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RecordPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RecordListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface RecordPayload extends TwilioResponsePayload { + usage_records: RecordResource[]; +} + +interface RecordResource { + account_sid: string; + api_version: string; + as_of: string; + category: string; + count: string; + count_unit: string; + description: string; + end_date: Date; + price: number; + price_unit: string; + start_date: Date; + subresource_uris: Record; + uri: string; + usage: string; + usage_unit: string; +} + +export class RecordInstance { + + constructor(protected _version: V2010, payload: RecordResource, accountSid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.asOf = (payload.as_of); + this.category = (payload.category); + this.count = (payload.count); + this.countUnit = (payload.count_unit); + this.description = (payload.description); + this.endDate = deserialize.iso8601Date(payload.end_date); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.startDate = deserialize.iso8601Date(payload.start_date); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + this.usage = (payload.usage); + this.usageUnit = (payload.usage_unit); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + */ + accountSid: string; + /** + * The API version used to create the resource. + */ + apiVersion: string; + /** + * Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + */ + asOf: string; + /** + * The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + */ + category: string; + /** + * The number of usage events, such as the number of calls. + */ + count: string; + /** + * The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + */ + countUnit: string; + /** + * A plain-language description of the usage category. + */ + description: string; + /** + * The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + endDate: Date; + /** + * The total price of the usage in the currency specified in `price_unit` and associated with the account. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + */ + priceUnit: string; + /** + * The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + startDate: Date; + /** + * A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + */ + subresourceUris: Record; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The amount used to bill usage and measured in units described in `usage_unit`. + */ + usage: string; + /** + * The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + */ + usageUnit: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + asOf: this.asOf, + category: this.category, + count: this.count, + countUnit: this.countUnit, + description: this.description, + endDate: this.endDate, + price: this.price, + priceUnit: this.priceUnit, + startDate: this.startDate, + subresourceUris: this.subresourceUris, + uri: this.uri, + usage: this.usage, + usageUnit: this.usageUnit, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class RecordPage extends Page { +/** +* Initialize the RecordPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: RecordSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RecordInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RecordResource): RecordInstance { + + return new RecordInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/record/allTime.ts b/rest/api/v2010/record/allTime.ts new file mode 100644 index 000000000..ddb160d2f --- /dev/null +++ b/rest/api/v2010/record/allTime.ts @@ -0,0 +1,522 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface AllTimeListInstanceEachOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AllTimeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AllTimeListInstanceOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AllTimeListInstancePageOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface AllTimeSolution { + accountSid: string; +} + +export interface AllTimeListInstance { + _version: V2010; + _solution: AllTimeSolution; + _uri: string; + + + + + /** + * Streams AllTimeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AllTimeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AllTimeInstance, done: (err?: Error) => void) => void): void; + each(params: AllTimeListInstanceEachOptions, callback?: (item: AllTimeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AllTimeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AllTimeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AllTimeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AllTimeListInstanceEachOptions, callback?: (item: AllTimeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AllTimeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AllTimePage) => any): Promise; + /** + * Retrieve a single target page of AllTimeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AllTimeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AllTimeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AllTimeInstance[]) => any): Promise; + list(params: AllTimeListInstanceOptions, callback?: (error: Error | null, items: AllTimeInstance[]) => any): Promise; + /** + * Lists AllTimeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AllTimeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AllTimeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AllTimeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AllTimeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AllTimePage) => any): Promise; + page(params: AllTimeListInstancePageOptions, callback?: (error: Error | null, items: AllTimePage) => any): Promise; + /** + * Retrieve a single page of AllTimeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AllTimeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AllTimeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AllTimeListInstance(version: V2010, accountSid: string): AllTimeListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as AllTimeListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Usage/Records/AllTime.json`; + + instance.page = function page(params?: AllTimeListInstancePageOptions | ((error: Error | null, items: AllTimePage) => any), callback?: (error: Error | null, items: AllTimePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AllTimePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AllTimePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AllTimePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AllTimeListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AllTimePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AllTimePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface AllTimePayload extends TwilioResponsePayload { + usage_records: AllTimeResource[]; +} + +interface AllTimeResource { + account_sid: string; + api_version: string; + as_of: string; + category: string; + count: string; + count_unit: string; + description: string; + end_date: Date; + price: number; + price_unit: string; + start_date: Date; + subresource_uris: Record; + uri: string; + usage: string; + usage_unit: string; +} + +export class AllTimeInstance { + + constructor(protected _version: V2010, payload: AllTimeResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.asOf = (payload.as_of); + this.category = (payload.category); + this.count = (payload.count); + this.countUnit = (payload.count_unit); + this.description = (payload.description); + this.endDate = deserialize.iso8601Date(payload.end_date); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.startDate = deserialize.iso8601Date(payload.start_date); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + this.usage = (payload.usage); + this.usageUnit = (payload.usage_unit); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + */ + accountSid: string; + /** + * The API version used to create the resource. + */ + apiVersion: string; + /** + * Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + */ + asOf: string; + /** + * The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + */ + category: string; + /** + * The number of usage events, such as the number of calls. + */ + count: string; + /** + * The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + */ + countUnit: string; + /** + * A plain-language description of the usage category. + */ + description: string; + /** + * The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + endDate: Date; + /** + * The total price of the usage in the currency specified in `price_unit` and associated with the account. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + */ + priceUnit: string; + /** + * The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + startDate: Date; + /** + * A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + */ + subresourceUris: Record; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The amount used to bill usage and measured in units described in `usage_unit`. + */ + usage: string; + /** + * The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + */ + usageUnit: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + asOf: this.asOf, + category: this.category, + count: this.count, + countUnit: this.countUnit, + description: this.description, + endDate: this.endDate, + price: this.price, + priceUnit: this.priceUnit, + startDate: this.startDate, + subresourceUris: this.subresourceUris, + uri: this.uri, + usage: this.usage, + usageUnit: this.usageUnit, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class AllTimePage extends Page { +/** +* Initialize the AllTimePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: AllTimeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AllTimeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AllTimeResource): AllTimeInstance { + + return new AllTimeInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/record/daily.ts b/rest/api/v2010/record/daily.ts new file mode 100644 index 000000000..184e02dd2 --- /dev/null +++ b/rest/api/v2010/record/daily.ts @@ -0,0 +1,522 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface DailyListInstanceEachOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DailyInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DailyListInstanceOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DailyListInstancePageOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface DailySolution { + accountSid: string; +} + +export interface DailyListInstance { + _version: V2010; + _solution: DailySolution; + _uri: string; + + + + + /** + * Streams DailyInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DailyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DailyInstance, done: (err?: Error) => void) => void): void; + each(params: DailyListInstanceEachOptions, callback?: (item: DailyInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DailyInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DailyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DailyInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DailyListInstanceEachOptions, callback?: (item: DailyInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DailyInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DailyPage) => any): Promise; + /** + * Retrieve a single target page of DailyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists DailyInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DailyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DailyInstance[]) => any): Promise; + list(params: DailyListInstanceOptions, callback?: (error: Error | null, items: DailyInstance[]) => any): Promise; + /** + * Lists DailyInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DailyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: DailyListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of DailyInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DailyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DailyPage) => any): Promise; + page(params: DailyListInstancePageOptions, callback?: (error: Error | null, items: DailyPage) => any): Promise; + /** + * Retrieve a single page of DailyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DailyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: DailyListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DailyListInstance(version: V2010, accountSid: string): DailyListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as DailyListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Usage/Records/Daily.json`; + + instance.page = function page(params?: DailyListInstancePageOptions | ((error: Error | null, items: DailyPage) => any), callback?: (error: Error | null, items: DailyPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DailyPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DailyPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DailyPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DailyListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DailyPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DailyPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface DailyPayload extends TwilioResponsePayload { + usage_records: DailyResource[]; +} + +interface DailyResource { + account_sid: string; + api_version: string; + as_of: string; + category: string; + count: string; + count_unit: string; + description: string; + end_date: Date; + price: number; + price_unit: string; + start_date: Date; + subresource_uris: Record; + uri: string; + usage: string; + usage_unit: string; +} + +export class DailyInstance { + + constructor(protected _version: V2010, payload: DailyResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.asOf = (payload.as_of); + this.category = (payload.category); + this.count = (payload.count); + this.countUnit = (payload.count_unit); + this.description = (payload.description); + this.endDate = deserialize.iso8601Date(payload.end_date); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.startDate = deserialize.iso8601Date(payload.start_date); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + this.usage = (payload.usage); + this.usageUnit = (payload.usage_unit); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + */ + accountSid: string; + /** + * The API version used to create the resource. + */ + apiVersion: string; + /** + * Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + */ + asOf: string; + /** + * The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + */ + category: string; + /** + * The number of usage events, such as the number of calls. + */ + count: string; + /** + * The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + */ + countUnit: string; + /** + * A plain-language description of the usage category. + */ + description: string; + /** + * The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + endDate: Date; + /** + * The total price of the usage in the currency specified in `price_unit` and associated with the account. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + */ + priceUnit: string; + /** + * The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + startDate: Date; + /** + * A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + */ + subresourceUris: Record; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The amount used to bill usage and measured in units described in `usage_unit`. + */ + usage: string; + /** + * The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + */ + usageUnit: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + asOf: this.asOf, + category: this.category, + count: this.count, + countUnit: this.countUnit, + description: this.description, + endDate: this.endDate, + price: this.price, + priceUnit: this.priceUnit, + startDate: this.startDate, + subresourceUris: this.subresourceUris, + uri: this.uri, + usage: this.usage, + usageUnit: this.usageUnit, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class DailyPage extends Page { +/** +* Initialize the DailyPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: DailySolution) { + super(version, response, solution); + } + + /** + * Build an instance of DailyInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DailyResource): DailyInstance { + + return new DailyInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/record/lastMonth.ts b/rest/api/v2010/record/lastMonth.ts new file mode 100644 index 000000000..f391c6337 --- /dev/null +++ b/rest/api/v2010/record/lastMonth.ts @@ -0,0 +1,522 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface LastMonthListInstanceEachOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: LastMonthInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface LastMonthListInstanceOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface LastMonthListInstancePageOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface LastMonthSolution { + accountSid: string; +} + +export interface LastMonthListInstance { + _version: V2010; + _solution: LastMonthSolution; + _uri: string; + + + + + /** + * Streams LastMonthInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LastMonthListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: LastMonthInstance, done: (err?: Error) => void) => void): void; + each(params: LastMonthListInstanceEachOptions, callback?: (item: LastMonthInstance, done: (err?: Error) => void) => void): void; + /** + * Streams LastMonthInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LastMonthListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: LastMonthInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: LastMonthListInstanceEachOptions, callback?: (item: LastMonthInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of LastMonthInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: LastMonthPage) => any): Promise; + /** + * Retrieve a single target page of LastMonthInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists LastMonthInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LastMonthListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: LastMonthInstance[]) => any): Promise; + list(params: LastMonthListInstanceOptions, callback?: (error: Error | null, items: LastMonthInstance[]) => any): Promise; + /** + * Lists LastMonthInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LastMonthListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: LastMonthListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of LastMonthInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LastMonthListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: LastMonthPage) => any): Promise; + page(params: LastMonthListInstancePageOptions, callback?: (error: Error | null, items: LastMonthPage) => any): Promise; + /** + * Retrieve a single page of LastMonthInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LastMonthListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: LastMonthListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function LastMonthListInstance(version: V2010, accountSid: string): LastMonthListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as LastMonthListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Usage/Records/LastMonth.json`; + + instance.page = function page(params?: LastMonthListInstancePageOptions | ((error: Error | null, items: LastMonthPage) => any), callback?: (error: Error | null, items: LastMonthPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new LastMonthPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: LastMonthPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new LastMonthPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: LastMonthListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new LastMonthPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new LastMonthPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface LastMonthPayload extends TwilioResponsePayload { + usage_records: LastMonthResource[]; +} + +interface LastMonthResource { + account_sid: string; + api_version: string; + as_of: string; + category: string; + count: string; + count_unit: string; + description: string; + end_date: Date; + price: number; + price_unit: string; + start_date: Date; + subresource_uris: Record; + uri: string; + usage: string; + usage_unit: string; +} + +export class LastMonthInstance { + + constructor(protected _version: V2010, payload: LastMonthResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.asOf = (payload.as_of); + this.category = (payload.category); + this.count = (payload.count); + this.countUnit = (payload.count_unit); + this.description = (payload.description); + this.endDate = deserialize.iso8601Date(payload.end_date); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.startDate = deserialize.iso8601Date(payload.start_date); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + this.usage = (payload.usage); + this.usageUnit = (payload.usage_unit); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + */ + accountSid: string; + /** + * The API version used to create the resource. + */ + apiVersion: string; + /** + * Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + */ + asOf: string; + /** + * The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + */ + category: string; + /** + * The number of usage events, such as the number of calls. + */ + count: string; + /** + * The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + */ + countUnit: string; + /** + * A plain-language description of the usage category. + */ + description: string; + /** + * The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + endDate: Date; + /** + * The total price of the usage in the currency specified in `price_unit` and associated with the account. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + */ + priceUnit: string; + /** + * The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + startDate: Date; + /** + * A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + */ + subresourceUris: Record; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The amount used to bill usage and measured in units described in `usage_unit`. + */ + usage: string; + /** + * The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + */ + usageUnit: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + asOf: this.asOf, + category: this.category, + count: this.count, + countUnit: this.countUnit, + description: this.description, + endDate: this.endDate, + price: this.price, + priceUnit: this.priceUnit, + startDate: this.startDate, + subresourceUris: this.subresourceUris, + uri: this.uri, + usage: this.usage, + usageUnit: this.usageUnit, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class LastMonthPage extends Page { +/** +* Initialize the LastMonthPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: LastMonthSolution) { + super(version, response, solution); + } + + /** + * Build an instance of LastMonthInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: LastMonthResource): LastMonthInstance { + + return new LastMonthInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/record/monthly.ts b/rest/api/v2010/record/monthly.ts new file mode 100644 index 000000000..3fffdfeb5 --- /dev/null +++ b/rest/api/v2010/record/monthly.ts @@ -0,0 +1,522 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface MonthlyListInstanceEachOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MonthlyInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MonthlyListInstanceOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MonthlyListInstancePageOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface MonthlySolution { + accountSid: string; +} + +export interface MonthlyListInstance { + _version: V2010; + _solution: MonthlySolution; + _uri: string; + + + + + /** + * Streams MonthlyInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MonthlyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MonthlyInstance, done: (err?: Error) => void) => void): void; + each(params: MonthlyListInstanceEachOptions, callback?: (item: MonthlyInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MonthlyInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MonthlyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MonthlyInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MonthlyListInstanceEachOptions, callback?: (item: MonthlyInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MonthlyInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MonthlyPage) => any): Promise; + /** + * Retrieve a single target page of MonthlyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MonthlyInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MonthlyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MonthlyInstance[]) => any): Promise; + list(params: MonthlyListInstanceOptions, callback?: (error: Error | null, items: MonthlyInstance[]) => any): Promise; + /** + * Lists MonthlyInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MonthlyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MonthlyListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MonthlyInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MonthlyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MonthlyPage) => any): Promise; + page(params: MonthlyListInstancePageOptions, callback?: (error: Error | null, items: MonthlyPage) => any): Promise; + /** + * Retrieve a single page of MonthlyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MonthlyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MonthlyListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MonthlyListInstance(version: V2010, accountSid: string): MonthlyListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as MonthlyListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Usage/Records/Monthly.json`; + + instance.page = function page(params?: MonthlyListInstancePageOptions | ((error: Error | null, items: MonthlyPage) => any), callback?: (error: Error | null, items: MonthlyPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MonthlyPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MonthlyPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MonthlyPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MonthlyListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MonthlyPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MonthlyPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface MonthlyPayload extends TwilioResponsePayload { + usage_records: MonthlyResource[]; +} + +interface MonthlyResource { + account_sid: string; + api_version: string; + as_of: string; + category: string; + count: string; + count_unit: string; + description: string; + end_date: Date; + price: number; + price_unit: string; + start_date: Date; + subresource_uris: Record; + uri: string; + usage: string; + usage_unit: string; +} + +export class MonthlyInstance { + + constructor(protected _version: V2010, payload: MonthlyResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.asOf = (payload.as_of); + this.category = (payload.category); + this.count = (payload.count); + this.countUnit = (payload.count_unit); + this.description = (payload.description); + this.endDate = deserialize.iso8601Date(payload.end_date); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.startDate = deserialize.iso8601Date(payload.start_date); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + this.usage = (payload.usage); + this.usageUnit = (payload.usage_unit); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + */ + accountSid: string; + /** + * The API version used to create the resource. + */ + apiVersion: string; + /** + * Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + */ + asOf: string; + /** + * The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + */ + category: string; + /** + * The number of usage events, such as the number of calls. + */ + count: string; + /** + * The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + */ + countUnit: string; + /** + * A plain-language description of the usage category. + */ + description: string; + /** + * The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + endDate: Date; + /** + * The total price of the usage in the currency specified in `price_unit` and associated with the account. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + */ + priceUnit: string; + /** + * The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + startDate: Date; + /** + * A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + */ + subresourceUris: Record; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The amount used to bill usage and measured in units described in `usage_unit`. + */ + usage: string; + /** + * The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + */ + usageUnit: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + asOf: this.asOf, + category: this.category, + count: this.count, + countUnit: this.countUnit, + description: this.description, + endDate: this.endDate, + price: this.price, + priceUnit: this.priceUnit, + startDate: this.startDate, + subresourceUris: this.subresourceUris, + uri: this.uri, + usage: this.usage, + usageUnit: this.usageUnit, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class MonthlyPage extends Page { +/** +* Initialize the MonthlyPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: MonthlySolution) { + super(version, response, solution); + } + + /** + * Build an instance of MonthlyInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MonthlyResource): MonthlyInstance { + + return new MonthlyInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/record/thisMonth.ts b/rest/api/v2010/record/thisMonth.ts new file mode 100644 index 000000000..2dbaf605d --- /dev/null +++ b/rest/api/v2010/record/thisMonth.ts @@ -0,0 +1,522 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface ThisMonthListInstanceEachOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ThisMonthInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ThisMonthListInstanceOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ThisMonthListInstancePageOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface ThisMonthSolution { + accountSid: string; +} + +export interface ThisMonthListInstance { + _version: V2010; + _solution: ThisMonthSolution; + _uri: string; + + + + + /** + * Streams ThisMonthInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ThisMonthListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ThisMonthInstance, done: (err?: Error) => void) => void): void; + each(params: ThisMonthListInstanceEachOptions, callback?: (item: ThisMonthInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ThisMonthInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ThisMonthListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ThisMonthInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ThisMonthListInstanceEachOptions, callback?: (item: ThisMonthInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ThisMonthInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ThisMonthPage) => any): Promise; + /** + * Retrieve a single target page of ThisMonthInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ThisMonthInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ThisMonthListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ThisMonthInstance[]) => any): Promise; + list(params: ThisMonthListInstanceOptions, callback?: (error: Error | null, items: ThisMonthInstance[]) => any): Promise; + /** + * Lists ThisMonthInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ThisMonthListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ThisMonthListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ThisMonthInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ThisMonthListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ThisMonthPage) => any): Promise; + page(params: ThisMonthListInstancePageOptions, callback?: (error: Error | null, items: ThisMonthPage) => any): Promise; + /** + * Retrieve a single page of ThisMonthInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ThisMonthListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ThisMonthListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ThisMonthListInstance(version: V2010, accountSid: string): ThisMonthListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as ThisMonthListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Usage/Records/ThisMonth.json`; + + instance.page = function page(params?: ThisMonthListInstancePageOptions | ((error: Error | null, items: ThisMonthPage) => any), callback?: (error: Error | null, items: ThisMonthPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ThisMonthPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ThisMonthPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ThisMonthPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ThisMonthListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ThisMonthPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ThisMonthPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ThisMonthPayload extends TwilioResponsePayload { + usage_records: ThisMonthResource[]; +} + +interface ThisMonthResource { + account_sid: string; + api_version: string; + as_of: string; + category: string; + count: string; + count_unit: string; + description: string; + end_date: Date; + price: number; + price_unit: string; + start_date: Date; + subresource_uris: Record; + uri: string; + usage: string; + usage_unit: string; +} + +export class ThisMonthInstance { + + constructor(protected _version: V2010, payload: ThisMonthResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.asOf = (payload.as_of); + this.category = (payload.category); + this.count = (payload.count); + this.countUnit = (payload.count_unit); + this.description = (payload.description); + this.endDate = deserialize.iso8601Date(payload.end_date); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.startDate = deserialize.iso8601Date(payload.start_date); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + this.usage = (payload.usage); + this.usageUnit = (payload.usage_unit); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + */ + accountSid: string; + /** + * The API version used to create the resource. + */ + apiVersion: string; + /** + * Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + */ + asOf: string; + /** + * The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + */ + category: string; + /** + * The number of usage events, such as the number of calls. + */ + count: string; + /** + * The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + */ + countUnit: string; + /** + * A plain-language description of the usage category. + */ + description: string; + /** + * The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + endDate: Date; + /** + * The total price of the usage in the currency specified in `price_unit` and associated with the account. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + */ + priceUnit: string; + /** + * The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + startDate: Date; + /** + * A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + */ + subresourceUris: Record; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The amount used to bill usage and measured in units described in `usage_unit`. + */ + usage: string; + /** + * The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + */ + usageUnit: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + asOf: this.asOf, + category: this.category, + count: this.count, + countUnit: this.countUnit, + description: this.description, + endDate: this.endDate, + price: this.price, + priceUnit: this.priceUnit, + startDate: this.startDate, + subresourceUris: this.subresourceUris, + uri: this.uri, + usage: this.usage, + usageUnit: this.usageUnit, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class ThisMonthPage extends Page { +/** +* Initialize the ThisMonthPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: ThisMonthSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ThisMonthInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ThisMonthResource): ThisMonthInstance { + + return new ThisMonthInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/record/today.ts b/rest/api/v2010/record/today.ts new file mode 100644 index 000000000..292b54855 --- /dev/null +++ b/rest/api/v2010/record/today.ts @@ -0,0 +1,522 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface TodayListInstanceEachOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TodayInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TodayListInstanceOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TodayListInstancePageOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface TodaySolution { + accountSid: string; +} + +export interface TodayListInstance { + _version: V2010; + _solution: TodaySolution; + _uri: string; + + + + + /** + * Streams TodayInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TodayListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TodayInstance, done: (err?: Error) => void) => void): void; + each(params: TodayListInstanceEachOptions, callback?: (item: TodayInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TodayInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TodayListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TodayInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TodayListInstanceEachOptions, callback?: (item: TodayInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TodayInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TodayPage) => any): Promise; + /** + * Retrieve a single target page of TodayInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists TodayInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TodayListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TodayInstance[]) => any): Promise; + list(params: TodayListInstanceOptions, callback?: (error: Error | null, items: TodayInstance[]) => any): Promise; + /** + * Lists TodayInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TodayListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: TodayListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of TodayInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TodayListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TodayPage) => any): Promise; + page(params: TodayListInstancePageOptions, callback?: (error: Error | null, items: TodayPage) => any): Promise; + /** + * Retrieve a single page of TodayInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TodayListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: TodayListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TodayListInstance(version: V2010, accountSid: string): TodayListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as TodayListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Usage/Records/Today.json`; + + instance.page = function page(params?: TodayListInstancePageOptions | ((error: Error | null, items: TodayPage) => any), callback?: (error: Error | null, items: TodayPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TodayPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TodayPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TodayPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TodayListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TodayPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TodayPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TodayPayload extends TwilioResponsePayload { + usage_records: TodayResource[]; +} + +interface TodayResource { + account_sid: string; + api_version: string; + as_of: string; + category: string; + count: string; + count_unit: string; + description: string; + end_date: Date; + price: number; + price_unit: string; + start_date: Date; + subresource_uris: Record; + uri: string; + usage: string; + usage_unit: string; +} + +export class TodayInstance { + + constructor(protected _version: V2010, payload: TodayResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.asOf = (payload.as_of); + this.category = (payload.category); + this.count = (payload.count); + this.countUnit = (payload.count_unit); + this.description = (payload.description); + this.endDate = deserialize.iso8601Date(payload.end_date); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.startDate = deserialize.iso8601Date(payload.start_date); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + this.usage = (payload.usage); + this.usageUnit = (payload.usage_unit); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + */ + accountSid: string; + /** + * The API version used to create the resource. + */ + apiVersion: string; + /** + * Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + */ + asOf: string; + /** + * The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + */ + category: string; + /** + * The number of usage events, such as the number of calls. + */ + count: string; + /** + * The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + */ + countUnit: string; + /** + * A plain-language description of the usage category. + */ + description: string; + /** + * The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + endDate: Date; + /** + * The total price of the usage in the currency specified in `price_unit` and associated with the account. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + */ + priceUnit: string; + /** + * The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + startDate: Date; + /** + * A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + */ + subresourceUris: Record; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The amount used to bill usage and measured in units described in `usage_unit`. + */ + usage: string; + /** + * The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + */ + usageUnit: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + asOf: this.asOf, + category: this.category, + count: this.count, + countUnit: this.countUnit, + description: this.description, + endDate: this.endDate, + price: this.price, + priceUnit: this.priceUnit, + startDate: this.startDate, + subresourceUris: this.subresourceUris, + uri: this.uri, + usage: this.usage, + usageUnit: this.usageUnit, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class TodayPage extends Page { +/** +* Initialize the TodayPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: TodaySolution) { + super(version, response, solution); + } + + /** + * Build an instance of TodayInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TodayResource): TodayInstance { + + return new TodayInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/record/yearly.ts b/rest/api/v2010/record/yearly.ts new file mode 100644 index 000000000..3fee3eeca --- /dev/null +++ b/rest/api/v2010/record/yearly.ts @@ -0,0 +1,522 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface YearlyListInstanceEachOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: YearlyInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface YearlyListInstanceOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface YearlyListInstancePageOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface YearlySolution { + accountSid: string; +} + +export interface YearlyListInstance { + _version: V2010; + _solution: YearlySolution; + _uri: string; + + + + + /** + * Streams YearlyInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YearlyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: YearlyInstance, done: (err?: Error) => void) => void): void; + each(params: YearlyListInstanceEachOptions, callback?: (item: YearlyInstance, done: (err?: Error) => void) => void): void; + /** + * Streams YearlyInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YearlyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: YearlyInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: YearlyListInstanceEachOptions, callback?: (item: YearlyInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of YearlyInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: YearlyPage) => any): Promise; + /** + * Retrieve a single target page of YearlyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists YearlyInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YearlyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: YearlyInstance[]) => any): Promise; + list(params: YearlyListInstanceOptions, callback?: (error: Error | null, items: YearlyInstance[]) => any): Promise; + /** + * Lists YearlyInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YearlyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: YearlyListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of YearlyInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YearlyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: YearlyPage) => any): Promise; + page(params: YearlyListInstancePageOptions, callback?: (error: Error | null, items: YearlyPage) => any): Promise; + /** + * Retrieve a single page of YearlyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YearlyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: YearlyListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function YearlyListInstance(version: V2010, accountSid: string): YearlyListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as YearlyListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Usage/Records/Yearly.json`; + + instance.page = function page(params?: YearlyListInstancePageOptions | ((error: Error | null, items: YearlyPage) => any), callback?: (error: Error | null, items: YearlyPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new YearlyPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: YearlyPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new YearlyPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: YearlyListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new YearlyPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new YearlyPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface YearlyPayload extends TwilioResponsePayload { + usage_records: YearlyResource[]; +} + +interface YearlyResource { + account_sid: string; + api_version: string; + as_of: string; + category: string; + count: string; + count_unit: string; + description: string; + end_date: Date; + price: number; + price_unit: string; + start_date: Date; + subresource_uris: Record; + uri: string; + usage: string; + usage_unit: string; +} + +export class YearlyInstance { + + constructor(protected _version: V2010, payload: YearlyResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.asOf = (payload.as_of); + this.category = (payload.category); + this.count = (payload.count); + this.countUnit = (payload.count_unit); + this.description = (payload.description); + this.endDate = deserialize.iso8601Date(payload.end_date); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.startDate = deserialize.iso8601Date(payload.start_date); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + this.usage = (payload.usage); + this.usageUnit = (payload.usage_unit); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + */ + accountSid: string; + /** + * The API version used to create the resource. + */ + apiVersion: string; + /** + * Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + */ + asOf: string; + /** + * The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + */ + category: string; + /** + * The number of usage events, such as the number of calls. + */ + count: string; + /** + * The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + */ + countUnit: string; + /** + * A plain-language description of the usage category. + */ + description: string; + /** + * The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + endDate: Date; + /** + * The total price of the usage in the currency specified in `price_unit` and associated with the account. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + */ + priceUnit: string; + /** + * The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + startDate: Date; + /** + * A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + */ + subresourceUris: Record; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The amount used to bill usage and measured in units described in `usage_unit`. + */ + usage: string; + /** + * The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + */ + usageUnit: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + asOf: this.asOf, + category: this.category, + count: this.count, + countUnit: this.countUnit, + description: this.description, + endDate: this.endDate, + price: this.price, + priceUnit: this.priceUnit, + startDate: this.startDate, + subresourceUris: this.subresourceUris, + uri: this.uri, + usage: this.usage, + usageUnit: this.usageUnit, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class YearlyPage extends Page { +/** +* Initialize the YearlyPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: YearlySolution) { + super(version, response, solution); + } + + /** + * Build an instance of YearlyInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: YearlyResource): YearlyInstance { + + return new YearlyInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/record/yesterday.ts b/rest/api/v2010/record/yesterday.ts new file mode 100644 index 000000000..6bffbe4a3 --- /dev/null +++ b/rest/api/v2010/record/yesterday.ts @@ -0,0 +1,522 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2010 from "../../V2010"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface YesterdayListInstanceEachOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: YesterdayInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface YesterdayListInstanceOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface YesterdayListInstancePageOptions { + /** The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. */ + "category"?: string; + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. */ + "endDate"?: Date; + /** Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. */ + "includeSubaccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface YesterdaySolution { + accountSid: string; +} + +export interface YesterdayListInstance { + _version: V2010; + _solution: YesterdaySolution; + _uri: string; + + + + + /** + * Streams YesterdayInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YesterdayListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: YesterdayInstance, done: (err?: Error) => void) => void): void; + each(params: YesterdayListInstanceEachOptions, callback?: (item: YesterdayInstance, done: (err?: Error) => void) => void): void; + /** + * Streams YesterdayInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YesterdayListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: YesterdayInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: YesterdayListInstanceEachOptions, callback?: (item: YesterdayInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of YesterdayInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: YesterdayPage) => any): Promise; + /** + * Retrieve a single target page of YesterdayInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists YesterdayInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YesterdayListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: YesterdayInstance[]) => any): Promise; + list(params: YesterdayListInstanceOptions, callback?: (error: Error | null, items: YesterdayInstance[]) => any): Promise; + /** + * Lists YesterdayInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YesterdayListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: YesterdayListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of YesterdayInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YesterdayListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: YesterdayPage) => any): Promise; + page(params: YesterdayListInstancePageOptions, callback?: (error: Error | null, items: YesterdayPage) => any): Promise; + /** + * Retrieve a single page of YesterdayInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { YesterdayListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: YesterdayListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function YesterdayListInstance(version: V2010, accountSid: string): YesterdayListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = {} as YesterdayListInstance; + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Usage/Records/Yesterday.json`; + + instance.page = function page(params?: YesterdayListInstancePageOptions | ((error: Error | null, items: YesterdayPage) => any), callback?: (error: Error | null, items: YesterdayPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new YesterdayPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: YesterdayPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new YesterdayPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: YesterdayListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["category"] !== undefined) + data["Category"] = params["category"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["includeSubaccounts"] !== undefined) + data["IncludeSubaccounts"] = serialize.bool(params["includeSubaccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new YesterdayPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new YesterdayPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface YesterdayPayload extends TwilioResponsePayload { + usage_records: YesterdayResource[]; +} + +interface YesterdayResource { + account_sid: string; + api_version: string; + as_of: string; + category: string; + count: string; + count_unit: string; + description: string; + end_date: Date; + price: number; + price_unit: string; + start_date: Date; + subresource_uris: Record; + uri: string; + usage: string; + usage_unit: string; +} + +export class YesterdayInstance { + + constructor(protected _version: V2010, payload: YesterdayResource, accountSid: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.asOf = (payload.as_of); + this.category = (payload.category); + this.count = (payload.count); + this.countUnit = (payload.count_unit); + this.description = (payload.description); + this.endDate = deserialize.iso8601Date(payload.end_date); + this.price = (payload.price); + this.priceUnit = (payload.price_unit); + this.startDate = deserialize.iso8601Date(payload.start_date); + this.subresourceUris = (payload.subresource_uris); + this.uri = (payload.uri); + this.usage = (payload.usage); + this.usageUnit = (payload.usage_unit); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + */ + accountSid: string; + /** + * The API version used to create the resource. + */ + apiVersion: string; + /** + * Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + */ + asOf: string; + /** + * The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + */ + category: string; + /** + * The number of usage events, such as the number of calls. + */ + count: string; + /** + * The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + */ + countUnit: string; + /** + * A plain-language description of the usage category. + */ + description: string; + /** + * The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + endDate: Date; + /** + * The total price of the usage in the currency specified in `price_unit` and associated with the account. + */ + price: number; + /** + * The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + */ + priceUnit: string; + /** + * The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + */ + startDate: Date; + /** + * A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + */ + subresourceUris: Record; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The amount used to bill usage and measured in units described in `usage_unit`. + */ + usage: string; + /** + * The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + */ + usageUnit: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + asOf: this.asOf, + category: this.category, + count: this.count, + countUnit: this.countUnit, + description: this.description, + endDate: this.endDate, + price: this.price, + priceUnit: this.priceUnit, + startDate: this.startDate, + subresourceUris: this.subresourceUris, + uri: this.uri, + usage: this.usage, + usageUnit: this.usageUnit, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class YesterdayPage extends Page { +/** +* Initialize the YesterdayPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: YesterdaySolution) { + super(version, response, solution); + } + + /** + * Build an instance of YesterdayInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: YesterdayResource): YesterdayInstance { + + return new YesterdayInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/api/v2010/trigger.ts b/rest/api/v2010/trigger.ts new file mode 100644 index 000000000..7293cae18 --- /dev/null +++ b/rest/api/v2010/trigger.ts @@ -0,0 +1,1068 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Api + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2010 from "../V2010"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The frequency of a recurring UsageTrigger. Can be: `daily`, `monthly`, or `yearly` for recurring triggers or empty for non-recurring triggers. A trigger will only fire once during each period. Recurring times are in GMT. + */ +export type TriggerRecurring = 'daily'|'monthly'|'yearly'|'alltime'; + +/** + * The field in the [UsageRecord](https://www.twilio.com/docs/usage/api/usage-record) resource that fires the trigger. Can be: `count`, `usage`, or `price`, as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + */ +export type TriggerTriggerField = 'count'|'usage'|'price'; + + + + +/** + * Options to pass to update a TriggerInstance + */ +export interface TriggerContextUpdateOptions { + /** The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. */ + "callbackMethod"?: string; + /** The URL we should call using `callback_method` when the trigger fires. */ + "callbackUrl"?: string; + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a TriggerInstance + */ +export interface TriggerListInstanceCreateOptions { + /** The URL we should call using `callback_method` when the trigger fires. */ + "callbackUrl": string; + /** The usage value at which the trigger should fire. For convenience, you can use an offset value such as `+30` to specify a trigger_value that is 30 units more than the current usage value. Be sure to urlencode a `+` as `%2B`. */ + "triggerValue": string; + /** The usage category that the trigger should watch. Use one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) for this value. */ + "usageCategory": string; + /** The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. */ + "callbackMethod"?: string; + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** */ + "recurring"?: TriggerRecurring; + /** */ + "triggerBy"?: TriggerTriggerField; +} + +/** + * Options to pass to each + */ +export interface TriggerListInstanceEachOptions { + /** The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. */ + "recurring"?: TriggerRecurring; + /** The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). */ + "triggerBy"?: TriggerTriggerField; + /** The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). */ + "usageCategory"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TriggerInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TriggerListInstanceOptions { + /** The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. */ + "recurring"?: TriggerRecurring; + /** The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). */ + "triggerBy"?: TriggerTriggerField; + /** The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). */ + "usageCategory"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TriggerListInstancePageOptions { + /** The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. */ + "recurring"?: TriggerRecurring; + /** The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). */ + "triggerBy"?: TriggerTriggerField; + /** The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). */ + "usageCategory"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TriggerContext { + + /** + * Remove a TriggerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a TriggerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a TriggerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance + */ + fetch(callback?: (error: Error | null, item?: TriggerInstance) => any): Promise + + /** + * Fetch a TriggerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a TriggerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance + */ + update(callback?: (error: Error | null, item?: TriggerInstance) => any): Promise; + /** + * Update a TriggerInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance + */ + update(params: TriggerContextUpdateOptions, callback?: (error: Error | null, item?: TriggerInstance) => any): Promise; + + /** + * Update a TriggerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a TriggerInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance with HTTP metadata + */ + updateWithHttpInfo(params: TriggerContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TriggerContextSolution { + "accountSid": string; + "sid": string; +} + +export class TriggerContextImpl implements TriggerContext { + protected _solution: TriggerContextSolution; + protected _uri: string; + + + constructor(protected _version: V2010, accountSid: string, sid: string) { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { accountSid, sid, }; + this._uri = `/Accounts/${accountSid}/Usage/Triggers/${sid}.json`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TriggerInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TriggerInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new TriggerInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: TriggerContextUpdateOptions | ((error: Error | null, item?: TriggerInstance) => any),callback?: (error: Error | null, item?: TriggerInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TriggerInstance(operationVersion, payload, instance._solution.accountSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: TriggerContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new TriggerInstance(operationVersion, response.body, instance._solution.accountSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TriggerPayload extends TwilioResponsePayload { + usage_triggers: TriggerResource[]; +} + +interface TriggerResource { + account_sid: string; + api_version: string; + callback_method: string; + callback_url: string; + current_value: string; + date_created: Date; + date_fired: Date; + date_updated: Date; + friendly_name: string; + recurring: TriggerRecurring; + sid: string; + trigger_by: TriggerTriggerField; + trigger_value: string; + uri: string; + usage_category: string; + usage_record_uri: string; +} + +export class TriggerInstance { + protected _solution: TriggerContextSolution; + protected _context?: TriggerContext; + + constructor(protected _version: V2010, payload: TriggerResource, accountSid?: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.apiVersion = (payload.api_version); + this.callbackMethod = (payload.callback_method); + this.callbackUrl = (payload.callback_url); + this.currentValue = (payload.current_value); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateFired = deserialize.rfc2822DateTime(payload.date_fired); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.recurring = payload.recurring; + this.sid = (payload.sid); + this.triggerBy = payload.trigger_by; + this.triggerValue = (payload.trigger_value); + this.uri = (payload.uri); + this.usageCategory = (payload.usage_category); + this.usageRecordUri = (payload.usage_record_uri); + + this._solution = { accountSid: accountSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the trigger monitors. + */ + accountSid: string; + /** + * The API version used to create the resource. + */ + apiVersion: string; + /** + * The HTTP method we use to call `callback_url`. Can be: `GET` or `POST`. + */ + callbackMethod: string; + /** + * The URL we call using the `callback_method` when the trigger fires. + */ + callbackUrl: string; + /** + * The current value of the field the trigger is watching. + */ + currentValue: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the trigger was last fired specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateFired: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the trigger. + */ + friendlyName: string; + recurring: TriggerRecurring; + /** + * The unique string that that we created to identify the UsageTrigger resource. + */ + sid: string; + triggerBy: TriggerTriggerField; + /** + * The value at which the trigger will fire. Must be a positive, numeric value. + */ + triggerValue: string; + /** + * The URI of the resource, relative to `https://api.twilio.com`. + */ + uri: string; + /** + * The usage category the trigger watches. Must be one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + */ + usageCategory: string; + /** + * The URI of the [UsageRecord](https://www.twilio.com/docs/usage/api/usage-record) resource this trigger watches, relative to `https://api.twilio.com`. + */ + usageRecordUri: string; + + private get _proxy(): TriggerContext { + this._context = this._context || new TriggerContextImpl(this._version, this._solution.accountSid, this._solution.sid); + return this._context; + } + + /** + * Remove a TriggerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TriggerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TriggerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance + */ + fetch(callback?: (error: Error | null, item?: TriggerInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TriggerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TriggerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance + */ + update(callback?: (error: Error | null, item?: TriggerInstance) => any): Promise; + /** + * Update a TriggerInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance + */ + update(params: TriggerContextUpdateOptions, callback?: (error: Error | null, item?: TriggerInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: TriggerInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a TriggerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a TriggerInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance with HTTP metadata + */ + updateWithHttpInfo(params: TriggerContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + apiVersion: this.apiVersion, + callbackMethod: this.callbackMethod, + callbackUrl: this.callbackUrl, + currentValue: this.currentValue, + dateCreated: this.dateCreated, + dateFired: this.dateFired, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + recurring: this.recurring, + sid: this.sid, + triggerBy: this.triggerBy, + triggerValue: this.triggerValue, + uri: this.uri, + usageCategory: this.usageCategory, + usageRecordUri: this.usageRecordUri, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TriggerSolution { + accountSid: string; +} + +export interface TriggerListInstance { + _version: V2010; + _solution: TriggerSolution; + _uri: string; + + (accountSid: string, sid: string, ): TriggerContext; + get(accountSid: string, sid: string, ): TriggerContext; + + + + + + + + + /** + * Create a TriggerInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance + */ + create(params: TriggerListInstanceCreateOptions, callback?: (error: Error | null, item?: TriggerInstance) => any): Promise; + + /** + * Create a TriggerInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TriggerInstance with HTTP metadata + */ + createWithHttpInfo(params: TriggerListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams TriggerInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TriggerListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TriggerInstance, done: (err?: Error) => void) => void): void; + each(params: TriggerListInstanceEachOptions, callback?: (item: TriggerInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TriggerInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TriggerListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TriggerInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TriggerListInstanceEachOptions, callback?: (item: TriggerInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TriggerInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TriggerPage) => any): Promise; + /** + * Retrieve a single target page of TriggerInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists TriggerInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TriggerListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TriggerInstance[]) => any): Promise; + list(params: TriggerListInstanceOptions, callback?: (error: Error | null, items: TriggerInstance[]) => any): Promise; + /** + * Lists TriggerInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TriggerListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: TriggerListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of TriggerInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TriggerListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TriggerPage) => any): Promise; + page(params: TriggerListInstancePageOptions, callback?: (error: Error | null, items: TriggerPage) => any): Promise; + /** + * Retrieve a single page of TriggerInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TriggerListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: TriggerListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TriggerListInstance(version: V2010, accountSid: string): TriggerListInstance { + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + const instance = ((accountSid, sid, ) => instance.get(accountSid, sid, )) as TriggerListInstance; + + instance.get = function get(accountSid, sid, ): TriggerContext { + return new TriggerContextImpl(version, accountSid, sid); + } + + instance._version = version; + instance._solution = { accountSid, }; + instance._uri = `/Accounts/${accountSid}/Usage/Triggers.json`; + + instance.create = function create(params: TriggerListInstanceCreateOptions, callback?: (error: Error | null, items: TriggerInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["callbackUrl"] === null || params["callbackUrl"] === undefined) { + throw new Error('Required parameter "params[\'callbackUrl\']" missing.'); + } + + if (params["triggerValue"] === null || params["triggerValue"] === undefined) { + throw new Error('Required parameter "params[\'triggerValue\']" missing.'); + } + + if (params["usageCategory"] === null || params["usageCategory"] === undefined) { + throw new Error('Required parameter "params[\'usageCategory\']" missing.'); + } + + let data: any = {}; + + + + data["CallbackUrl"] = params["callbackUrl"]; + + data["TriggerValue"] = params["triggerValue"]; + + data["UsageCategory"] = params["usageCategory"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["recurring"] !== undefined) + data["Recurring"] = params["recurring"]; + if (params["triggerBy"] !== undefined) + data["TriggerBy"] = params["triggerBy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TriggerInstance(operationVersion, payload, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TriggerListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["callbackUrl"] === null || params["callbackUrl"] === undefined) { + throw new Error('Required parameter "params[\'callbackUrl\']" missing.'); + } + + if (params["triggerValue"] === null || params["triggerValue"] === undefined) { + throw new Error('Required parameter "params[\'triggerValue\']" missing.'); + } + + if (params["usageCategory"] === null || params["usageCategory"] === undefined) { + throw new Error('Required parameter "params[\'usageCategory\']" missing.'); + } + + let data: any = {}; + + + + data["CallbackUrl"] = params["callbackUrl"]; + + data["TriggerValue"] = params["triggerValue"]; + + data["UsageCategory"] = params["usageCategory"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["recurring"] !== undefined) + data["Recurring"] = params["recurring"]; + if (params["triggerBy"] !== undefined) + data["TriggerBy"] = params["triggerBy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new TriggerInstance(operationVersion, response.body, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TriggerListInstancePageOptions | ((error: Error | null, items: TriggerPage) => any), callback?: (error: Error | null, items: TriggerPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["recurring"] !== undefined) + data["Recurring"] = params["recurring"]; + if (params["triggerBy"] !== undefined) + data["TriggerBy"] = params["triggerBy"]; + if (params["usageCategory"] !== undefined) + data["UsageCategory"] = params["usageCategory"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TriggerPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TriggerPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TriggerPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TriggerListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["recurring"] !== undefined) + data["Recurring"] = params["recurring"]; + if (params["triggerBy"] !== undefined) + data["TriggerBy"] = params["triggerBy"]; + if (params["usageCategory"] !== undefined) + data["UsageCategory"] = params["usageCategory"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TriggerPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TriggerPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TriggerPage extends Page { +/** +* Initialize the TriggerPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2010, response: Response, solution: TriggerSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TriggerInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TriggerResource): TriggerInstance { + + return new TriggerInstance( + this._version, + payload, + this._solution.accountSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/assistants/V1.ts b/rest/assistants/V1.ts new file mode 100644 index 000000000..9bb326df3 --- /dev/null +++ b/rest/assistants/V1.ts @@ -0,0 +1,74 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import AssistantsBase from "../AssistantsBase"; +import Version from "../../base/Version"; +import { AssistantListInstance } from "./v1/assistant"; +import { KnowledgeListInstance } from "./v1/knowledge"; +import { PolicyListInstance } from "./v1/policy"; +import { SessionListInstance } from "./v1/session"; +import { ToolListInstance } from "./v1/tool"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Assistants + * + * @param domain - The Twilio (Twilio.Assistants) domain + */ + constructor(domain: AssistantsBase) { + super(domain, "v1"); + } + + /** assistants - { Twilio.Assistants.V1.AssistantListInstance } resource */ + protected _assistants?: AssistantListInstance; + /** knowledge - { Twilio.Assistants.V1.KnowledgeListInstance } resource */ + protected _knowledge?: KnowledgeListInstance; + /** policies - { Twilio.Assistants.V1.PolicyListInstance } resource */ + protected _policies?: PolicyListInstance; + /** sessions - { Twilio.Assistants.V1.SessionListInstance } resource */ + protected _sessions?: SessionListInstance; + /** tools - { Twilio.Assistants.V1.ToolListInstance } resource */ + protected _tools?: ToolListInstance; + + /** Getter for assistants resource */ + get assistants(): AssistantListInstance { + this._assistants = this._assistants || AssistantListInstance(this); + return this._assistants; + } + + /** Getter for knowledge resource */ + get knowledge(): KnowledgeListInstance { + this._knowledge = this._knowledge || KnowledgeListInstance(this); + return this._knowledge; + } + + /** Getter for policies resource */ + get policies(): PolicyListInstance { + this._policies = this._policies || PolicyListInstance(this); + return this._policies; + } + + /** Getter for sessions resource */ + get sessions(): SessionListInstance { + this._sessions = this._sessions || SessionListInstance(this); + return this._sessions; + } + + /** Getter for tools resource */ + get tools(): ToolListInstance { + this._tools = this._tools || ToolListInstance(this); + return this._tools; + } + +} diff --git a/rest/assistants/v1/assistant.ts b/rest/assistants/v1/assistant.ts new file mode 100644 index 000000000..598b095da --- /dev/null +++ b/rest/assistants/v1/assistant.ts @@ -0,0 +1,1208 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { AssistantsKnowledgeListInstance } from "./assistant/assistantsKnowledge"; +import { AssistantsToolListInstance } from "./assistant/assistantsTool"; +import { FeedbackListInstance } from "./assistant/feedback"; +import { MessageListInstance } from "./assistant/message"; + + +export class AssistantsV1ServiceCreateAssistantRequest { + "customerAi"?: AssistantsV1ServiceCustomerAi; + /** + * The name of the assistant. + */ + "name": string; + /** + * The owner/company of the assistant. + */ + "owner"?: string; + /** + * The personality prompt to be used for assistant. + */ + "personalityPrompt"?: string; + "segmentCredential"?: AssistantsV1ServiceSegmentCredential; + + constructor(payload) { + this.customerAi = payload["customer_ai"]; + this.name = payload["name"]; + this.owner = payload["owner"]; + this.personalityPrompt = payload["personality_prompt"]; + this.segmentCredential = payload["segment_credential"]; + } +} + + +export class AssistantsV1ServiceCustomerAi { + /** + * True if the perception engine is enabled. + */ + "perceptionEngineEnabled": boolean; + /** + * True if the personalization engine is enabled. + */ + "personalizationEngineEnabled": boolean; + + constructor(payload) { + this.perceptionEngineEnabled = payload["perception_engine_enabled"]; + this.personalizationEngineEnabled = payload["personalization_engine_enabled"]; + } +} + + +export class AssistantsV1ServiceKnowledge { + /** + * The type of knowledge source. + */ + "description"?: string; + /** + * The description of knowledge. + */ + "id": string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + */ + "accountSid"?: string; + /** + * The details of the knowledge source based on the type. + */ + "knowledgeSourceDetails"?: Record; + /** + * The name of the knowledge source. + */ + "name": string; + /** + * The status of processing the knowledge source (\'QUEUED\', \'PROCESSING\', \'COMPLETED\', \'FAILED\') + */ + "status"?: string; + /** + * The type of knowledge source (\'Web\', \'Database\', \'Text\', \'File\') + */ + "type": string; + /** + * The url of the knowledge resource. + */ + "url"?: string; + /** + * The embedding model to be used for the knowledge source. + */ + "embeddingModel"?: string; + /** + * The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + "dateCreated": Date; + /** + * The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + "dateUpdated": Date; + + constructor(payload) { + this.description = payload["description"]; + this.id = payload["id"]; + this.accountSid = payload["account_sid"]; + this.knowledgeSourceDetails = payload["knowledge_source_details"]; + this.name = payload["name"]; + this.status = payload["status"]; + this.type = payload["type"]; + this.url = payload["url"]; + this.embeddingModel = payload["embedding_model"]; + this.dateCreated = payload["date_created"]; + this.dateUpdated = payload["date_updated"]; + } +} + + +export class AssistantsV1ServiceSegmentCredential { + /** + * The profile API key. + */ + "profileApiKey"?: string; + /** + * The space ID. + */ + "spaceId"?: string; + /** + * The write key. + */ + "writeKey"?: string; + + constructor(payload) { + this.profileApiKey = payload["profile_api_key"]; + this.spaceId = payload["space_id"]; + this.writeKey = payload["write_key"]; + } +} + + +export class AssistantsV1ServiceTool { + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tool resource. + */ + "accountSid"?: string; + /** + * The description of the tool. + */ + "description": string; + /** + * True if the tool is enabled. + */ + "enabled": boolean; + /** + * The tool ID. + */ + "id": string; + /** + * The metadata related to method, url, input_schema to used with the Tool. + */ + "meta": Record; + /** + * The name of the tool. + */ + "name": string; + /** + * The authentication requirement for the tool. + */ + "requiresAuth": boolean; + /** + * The type of the tool. (\'WEBHOOK\') + */ + "type": string; + /** + * The url of the tool resource. + */ + "url"?: string; + /** + * The date and time in GMT when the Tool was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + "dateCreated": Date; + /** + * The date and time in GMT when the Tool was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + "dateUpdated": Date; + + constructor(payload) { + this.accountSid = payload["account_sid"]; + this.description = payload["description"]; + this.enabled = payload["enabled"]; + this.id = payload["id"]; + this.meta = payload["meta"]; + this.name = payload["name"]; + this.requiresAuth = payload["requires_auth"]; + this.type = payload["type"]; + this.url = payload["url"]; + this.dateCreated = payload["date_created"]; + this.dateUpdated = payload["date_updated"]; + } +} + + +export class AssistantsV1ServiceUpdateAssistantRequest { + "customerAi"?: AssistantsV1ServiceCustomerAi; + /** + * The name of the assistant. + */ + "name"?: string; + /** + * The owner/company of the assistant. + */ + "owner"?: string; + /** + * The personality prompt to be used for assistant. + */ + "personalityPrompt"?: string; + "segmentCredential"?: AssistantsV1ServiceSegmentCredential; + + constructor(payload) { + this.customerAi = payload["customer_ai"]; + this.name = payload["name"]; + this.owner = payload["owner"]; + this.personalityPrompt = payload["personality_prompt"]; + this.segmentCredential = payload["segment_credential"]; + } +} + + + + + +/** + * Options to pass to update a AssistantInstance + */ +export interface AssistantContextUpdateOptions { + /** */ + "assistantsV1ServiceUpdateAssistantRequest"?: AssistantsV1ServiceUpdateAssistantRequest; +} + +/** + * Options to pass to create a AssistantInstance + */ +export interface AssistantListInstanceCreateOptions { + /** */ + "assistantsV1ServiceCreateAssistantRequest": AssistantsV1ServiceCreateAssistantRequest; +} + +/** + * Options to pass to each + */ +export interface AssistantListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AssistantInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AssistantListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AssistantListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AssistantContext { + assistantsKnowledge: AssistantsKnowledgeListInstance; + assistantsTools: AssistantsToolListInstance; + feedbacks: FeedbackListInstance; + messages: MessageListInstance; + + /** + * Remove a AssistantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AssistantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a AssistantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance + */ + fetch(callback?: (error: Error | null, item?: AssistantInstance) => any): Promise + + /** + * Fetch a AssistantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a AssistantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance + */ + update(callback?: (error: Error | null, item?: AssistantInstance) => any): Promise; + /** + * Update a AssistantInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance + */ + update(params: AssistantsV1ServiceUpdateAssistantRequest, headers?: any, callback?: (error: Error | null, item?: AssistantInstance) => any): Promise; + + /** + * Update a AssistantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AssistantInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance with HTTP metadata + */ + updateWithHttpInfo(params: AssistantsV1ServiceUpdateAssistantRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AssistantContextSolution { + "id": string; +} + +export class AssistantContextImpl implements AssistantContext { + protected _solution: AssistantContextSolution; + protected _uri: string; + + protected _assistantsKnowledge?: AssistantsKnowledgeListInstance; + protected _assistantsTools?: AssistantsToolListInstance; + protected _feedbacks?: FeedbackListInstance; + protected _messages?: MessageListInstance; + + constructor(protected _version: V1, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/Assistants/${id}`; + } + + get assistantsKnowledge(): AssistantsKnowledgeListInstance { + this._assistantsKnowledge = this._assistantsKnowledge || AssistantsKnowledgeListInstance(this._version, this._solution.id); + return this._assistantsKnowledge; + } + + get assistantsTools(): AssistantsToolListInstance { + this._assistantsTools = this._assistantsTools || AssistantsToolListInstance(this._version, this._solution.id); + return this._assistantsTools; + } + + get feedbacks(): FeedbackListInstance { + this._feedbacks = this._feedbacks || FeedbackListInstance(this._version, this._solution.id); + return this._feedbacks; + } + + get messages(): MessageListInstance { + this._messages = this._messages || MessageListInstance(this._version, this._solution.id); + return this._messages; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AssistantInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AssistantInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AssistantInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: AssistantsV1ServiceUpdateAssistantRequest | ((error: Error | null, item?: AssistantInstance) => any), headers?: any,callback?: (error: Error | null, item?: AssistantInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as AssistantsV1ServiceUpdateAssistantRequest; + } else { + params = params || {} as Partial as AssistantsV1ServiceUpdateAssistantRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new AssistantInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: AssistantsV1ServiceUpdateAssistantRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as AssistantsV1ServiceUpdateAssistantRequest; + } else { + params = params || {} as Partial as AssistantsV1ServiceUpdateAssistantRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AssistantInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AssistantPayload extends TwilioResponsePayload { + assistants: AssistantResource[]; +} + +interface AssistantResource { + account_sid: string; + customer_ai: Record; + id: string; + model: string; + name: string; + owner: string; + url: string; + personality_prompt: string; + date_created: Date; + date_updated: Date; + knowledge: Array; + tools: Array; +} + +export class AssistantInstance { + protected _solution: AssistantContextSolution; + protected _context?: AssistantContext; + + constructor(protected _version: V1, payload: AssistantResource, id?: string) { + + this.accountSid = (payload.account_sid); + this.customerAi = (payload.customer_ai); + this.id = (payload.id); + this.model = (payload.model); + this.name = (payload.name); + this.owner = (payload.owner); + this.url = (payload.url); + this.personalityPrompt = (payload.personality_prompt); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.knowledge = payload.knowledge !== null && payload.knowledge !== undefined ? payload.knowledge.map( + (payload: any) => new AssistantsV1ServiceKnowledge(payload) + ) : null; + this.tools = payload.tools !== null && payload.tools !== undefined ? payload.tools.map( + (payload: any) => new AssistantsV1ServiceTool(payload) + ) : null; + + this._solution = { id: id, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Assistant resource. + */ + accountSid: string; + /** + * The Personalization and Perception Engine settings. + */ + customerAi: Record; + /** + * The Assistant ID. + */ + id: string; + /** + * The default model used by the assistant. + */ + model: string; + /** + * The name of the assistant. + */ + name: string; + /** + * The owner/company of the assistant. + */ + owner: string; + /** + * The url of the assistant resource. + */ + url: string; + /** + * The personality prompt to be used for assistant. + */ + personalityPrompt: string; + /** + * The date and time in GMT when the Assistant was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Assistant was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The list of knowledge sources associated with the assistant. + */ + knowledge: Array; + /** + * The list of tools associated with the assistant. + */ + tools: Array; + + private get _proxy(): AssistantContext { + this._context = this._context || new AssistantContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Remove a AssistantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AssistantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AssistantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance + */ + fetch(callback?: (error: Error | null, item?: AssistantInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AssistantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a AssistantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance + */ + update(callback?: (error: Error | null, item?: AssistantInstance) => any): Promise; + /** + * Update a AssistantInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance + */ + update(params: AssistantsV1ServiceUpdateAssistantRequest, headers?: any, callback?: (error: Error | null, item?: AssistantInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: AssistantInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a AssistantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AssistantInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance with HTTP metadata + */ + updateWithHttpInfo(params: AssistantsV1ServiceUpdateAssistantRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the assistantsKnowledge. + */ + assistantsKnowledge(): AssistantsKnowledgeListInstance { + return this._proxy.assistantsKnowledge; + } + + /** + * Access the assistantsTools. + */ + assistantsTools(): AssistantsToolListInstance { + return this._proxy.assistantsTools; + } + + /** + * Access the feedbacks. + */ + feedbacks(): FeedbackListInstance { + return this._proxy.feedbacks; + } + + /** + * Access the messages. + */ + messages(): MessageListInstance { + return this._proxy.messages; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + customerAi: this.customerAi, + id: this.id, + model: this.model, + name: this.name, + owner: this.owner, + url: this.url, + personalityPrompt: this.personalityPrompt, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + knowledge: this.knowledge, + tools: this.tools, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AssistantSolution { +} + +export interface AssistantListInstance { + _version: V1; + _solution: AssistantSolution; + _uri: string; + + (id: string, ): AssistantContext; + get(id: string, ): AssistantContext; + + + + + + + + + /** + * Create a AssistantInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance + */ + create(params: AssistantsV1ServiceCreateAssistantRequest, headers?: any, callback?: (error: Error | null, item?: AssistantInstance) => any): Promise; + + /** + * Create a AssistantInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantInstance with HTTP metadata + */ + createWithHttpInfo(params: AssistantsV1ServiceCreateAssistantRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams AssistantInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AssistantInstance, done: (err?: Error) => void) => void): void; + each(params: AssistantListInstanceEachOptions, callback?: (item: AssistantInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AssistantInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AssistantInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AssistantListInstanceEachOptions, callback?: (item: AssistantInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AssistantInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AssistantPage) => any): Promise; + /** + * Retrieve a single target page of AssistantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AssistantInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AssistantInstance[]) => any): Promise; + list(params: AssistantListInstanceOptions, callback?: (error: Error | null, items: AssistantInstance[]) => any): Promise; + /** + * Lists AssistantInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AssistantListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AssistantInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AssistantPage) => any): Promise; + page(params: AssistantListInstancePageOptions, callback?: (error: Error | null, items: AssistantPage) => any): Promise; + /** + * Retrieve a single page of AssistantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AssistantListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AssistantListInstance(version: V1): AssistantListInstance { + const instance = ((id, ) => instance.get(id, )) as AssistantListInstance; + + instance.get = function get(id, ): AssistantContext { + return new AssistantContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Assistants`; + + instance.create = function create(params: AssistantsV1ServiceCreateAssistantRequest, headers?: any, callback?: (error: Error | null, items: AssistantInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AssistantInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AssistantsV1ServiceCreateAssistantRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AssistantInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AssistantListInstancePageOptions | ((error: Error | null, items: AssistantPage) => any), callback?: (error: Error | null, items: AssistantPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AssistantPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AssistantPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AssistantPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AssistantListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssistantPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssistantPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AssistantPage extends Page { +/** +* Initialize the AssistantPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: AssistantSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AssistantInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AssistantResource): AssistantInstance { + + return new AssistantInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/assistants/v1/assistant/assistantsKnowledge.ts b/rest/assistants/v1/assistant/assistantsKnowledge.ts new file mode 100644 index 000000000..4b364317e --- /dev/null +++ b/rest/assistants/v1/assistant/assistantsKnowledge.ts @@ -0,0 +1,673 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to each + */ +export interface AssistantsKnowledgeListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AssistantsKnowledgeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AssistantsKnowledgeListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AssistantsKnowledgeListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AssistantsKnowledgeContext { + + /** + * Create a AssistantsKnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantsKnowledgeInstance + */ + create(callback?: (error: Error | null, item?: AssistantsKnowledgeInstance) => any): Promise + + /** + * Create a AssistantsKnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantsKnowledgeInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Remove a AssistantsKnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AssistantsKnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AssistantsKnowledgeContextSolution { + "assistantId": string; + "id": string; +} + +export class AssistantsKnowledgeContextImpl implements AssistantsKnowledgeContext { + protected _solution: AssistantsKnowledgeContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, assistantId: string, id: string) { + if (!isValidPathParam(assistantId)) { + throw new Error('Parameter \'assistantId\' is not valid.'); + } + + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { assistantId, id, }; + this._uri = `/Assistants/${assistantId}/Knowledge/${id}`; + } + + create(callback?: (error: Error | null, item?: AssistantsKnowledgeInstance) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new AssistantsKnowledgeInstance(operationVersion, payload, instance._solution.assistantId, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AssistantsKnowledgeInstance(operationVersion, response.body, instance._solution.assistantId, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AssistantsKnowledgePayload extends TwilioResponsePayload { + knowledge: AssistantsKnowledgeResource[]; +} + +interface AssistantsKnowledgeResource { + description: string; + id: string; + account_sid: string; + knowledge_source_details: Record; + name: string; + status: string; + type: string; + url: string; + embedding_model: string; + date_created: Date; + date_updated: Date; +} + +export class AssistantsKnowledgeInstance { + protected _solution: AssistantsKnowledgeContextSolution; + protected _context?: AssistantsKnowledgeContext; + + constructor(protected _version: V1, payload: AssistantsKnowledgeResource, assistantId: string, id?: string) { + + this.description = (payload.description); + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.knowledgeSourceDetails = (payload.knowledge_source_details); + this.name = (payload.name); + this.status = (payload.status); + this.type = (payload.type); + this.url = (payload.url); + this.embeddingModel = (payload.embedding_model); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { assistantId, id: id, }; + } + + /** + * The type of knowledge source. + */ + description: string; + /** + * The description of knowledge. + */ + id: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + */ + accountSid: string; + /** + * The details of the knowledge source based on the type. + */ + knowledgeSourceDetails: Record; + /** + * The name of the knowledge source. + */ + name: string; + /** + * The status of processing the knowledge source (\'QUEUED\', \'PROCESSING\', \'COMPLETED\', \'FAILED\') + */ + status: string; + /** + * The type of knowledge source (\'Web\', \'Database\', \'Text\', \'File\') + */ + type: string; + /** + * The url of the knowledge resource. + */ + url: string; + /** + * The embedding model to be used for the knowledge source. + */ + embeddingModel: string; + /** + * The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + private get _proxy(): AssistantsKnowledgeContext { + this._context = this._context || new AssistantsKnowledgeContextImpl(this._version, this._solution.assistantId, this._solution.id); + return this._context; + } + + /** + * Create a AssistantsKnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantsKnowledgeInstance + */ + create(callback?: (error: Error | null, item?: AssistantsKnowledgeInstance) => any): Promise + + { + return this._proxy.create(callback); + } + + /** + * Create a AssistantsKnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantsKnowledgeInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.createWithHttpInfo(callback); + } + + /** + * Remove a AssistantsKnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AssistantsKnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + description: this.description, + id: this.id, + accountSid: this.accountSid, + knowledgeSourceDetails: this.knowledgeSourceDetails, + name: this.name, + status: this.status, + type: this.type, + url: this.url, + embeddingModel: this.embeddingModel, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AssistantsKnowledgeSolution { + assistantId: string; +} + +export interface AssistantsKnowledgeListInstance { + _version: V1; + _solution: AssistantsKnowledgeSolution; + _uri: string; + + (id: string, ): AssistantsKnowledgeContext; + get(id: string, ): AssistantsKnowledgeContext; + + + + + + + + /** + * Streams AssistantsKnowledgeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsKnowledgeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AssistantsKnowledgeInstance, done: (err?: Error) => void) => void): void; + each(params: AssistantsKnowledgeListInstanceEachOptions, callback?: (item: AssistantsKnowledgeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AssistantsKnowledgeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsKnowledgeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AssistantsKnowledgeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AssistantsKnowledgeListInstanceEachOptions, callback?: (item: AssistantsKnowledgeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AssistantsKnowledgeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AssistantsKnowledgePage) => any): Promise; + /** + * Retrieve a single target page of AssistantsKnowledgeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AssistantsKnowledgeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsKnowledgeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AssistantsKnowledgeInstance[]) => any): Promise; + list(params: AssistantsKnowledgeListInstanceOptions, callback?: (error: Error | null, items: AssistantsKnowledgeInstance[]) => any): Promise; + /** + * Lists AssistantsKnowledgeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsKnowledgeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AssistantsKnowledgeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AssistantsKnowledgeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsKnowledgeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AssistantsKnowledgePage) => any): Promise; + page(params: AssistantsKnowledgeListInstancePageOptions, callback?: (error: Error | null, items: AssistantsKnowledgePage) => any): Promise; + /** + * Retrieve a single page of AssistantsKnowledgeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsKnowledgeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AssistantsKnowledgeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AssistantsKnowledgeListInstance(version: V1, assistantId: string): AssistantsKnowledgeListInstance { + if (!isValidPathParam(assistantId)) { + throw new Error('Parameter \'assistantId\' is not valid.'); + } + + const instance = ((id, ) => instance.get(id, )) as AssistantsKnowledgeListInstance; + + instance.get = function get(id, ): AssistantsKnowledgeContext { + return new AssistantsKnowledgeContextImpl(version, assistantId, id); + } + + instance._version = version; + instance._solution = { assistantId, }; + instance._uri = `/Assistants/${assistantId}/Knowledge`; + + instance.page = function page(params?: AssistantsKnowledgeListInstancePageOptions | ((error: Error | null, items: AssistantsKnowledgePage) => any), callback?: (error: Error | null, items: AssistantsKnowledgePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AssistantsKnowledgePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AssistantsKnowledgePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AssistantsKnowledgePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AssistantsKnowledgeListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssistantsKnowledgePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssistantsKnowledgePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AssistantsKnowledgePage extends Page { +/** +* Initialize the AssistantsKnowledgePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: AssistantsKnowledgeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AssistantsKnowledgeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AssistantsKnowledgeResource): AssistantsKnowledgeInstance { + + return new AssistantsKnowledgeInstance( + this._version, + payload, + this._solution.assistantId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/assistants/v1/assistant/assistantsTool.ts b/rest/assistants/v1/assistant/assistantsTool.ts new file mode 100644 index 000000000..f7a767699 --- /dev/null +++ b/rest/assistants/v1/assistant/assistantsTool.ts @@ -0,0 +1,673 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to each + */ +export interface AssistantsToolListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AssistantsToolInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AssistantsToolListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AssistantsToolListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AssistantsToolContext { + + /** + * Create a AssistantsToolInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantsToolInstance + */ + create(callback?: (error: Error | null, item?: AssistantsToolInstance) => any): Promise + + /** + * Create a AssistantsToolInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantsToolInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Remove a AssistantsToolInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AssistantsToolInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AssistantsToolContextSolution { + "assistantId": string; + "id": string; +} + +export class AssistantsToolContextImpl implements AssistantsToolContext { + protected _solution: AssistantsToolContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, assistantId: string, id: string) { + if (!isValidPathParam(assistantId)) { + throw new Error('Parameter \'assistantId\' is not valid.'); + } + + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { assistantId, id, }; + this._uri = `/Assistants/${assistantId}/Tools/${id}`; + } + + create(callback?: (error: Error | null, item?: AssistantsToolInstance) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new AssistantsToolInstance(operationVersion, payload, instance._solution.assistantId, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AssistantsToolInstance(operationVersion, response.body, instance._solution.assistantId, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AssistantsToolPayload extends TwilioResponsePayload { + tools: AssistantsToolResource[]; +} + +interface AssistantsToolResource { + account_sid: string; + description: string; + enabled: boolean; + id: string; + meta: Record; + name: string; + requires_auth: boolean; + type: string; + url: string; + date_created: Date; + date_updated: Date; +} + +export class AssistantsToolInstance { + protected _solution: AssistantsToolContextSolution; + protected _context?: AssistantsToolContext; + + constructor(protected _version: V1, payload: AssistantsToolResource, assistantId: string, id?: string) { + + this.accountSid = (payload.account_sid); + this.description = (payload.description); + this.enabled = (payload.enabled); + this.id = (payload.id); + this.meta = (payload.meta); + this.name = (payload.name); + this.requiresAuth = (payload.requires_auth); + this.type = (payload.type); + this.url = (payload.url); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { assistantId, id: id, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tool resource. + */ + accountSid: string; + /** + * The description of the tool. + */ + description: string; + /** + * True if the tool is enabled. + */ + enabled: boolean; + /** + * The tool ID. + */ + id: string; + /** + * The metadata related to method, url, input_schema to used with the Tool. + */ + meta: Record; + /** + * The name of the tool. + */ + name: string; + /** + * The authentication requirement for the tool. + */ + requiresAuth: boolean; + /** + * The type of the tool. (\'WEBHOOK\') + */ + type: string; + /** + * The url of the tool resource. + */ + url: string; + /** + * The date and time in GMT when the Tool was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Tool was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + private get _proxy(): AssistantsToolContext { + this._context = this._context || new AssistantsToolContextImpl(this._version, this._solution.assistantId, this._solution.id); + return this._context; + } + + /** + * Create a AssistantsToolInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantsToolInstance + */ + create(callback?: (error: Error | null, item?: AssistantsToolInstance) => any): Promise + + { + return this._proxy.create(callback); + } + + /** + * Create a AssistantsToolInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssistantsToolInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.createWithHttpInfo(callback); + } + + /** + * Remove a AssistantsToolInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AssistantsToolInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + description: this.description, + enabled: this.enabled, + id: this.id, + meta: this.meta, + name: this.name, + requiresAuth: this.requiresAuth, + type: this.type, + url: this.url, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AssistantsToolSolution { + assistantId: string; +} + +export interface AssistantsToolListInstance { + _version: V1; + _solution: AssistantsToolSolution; + _uri: string; + + (id: string, ): AssistantsToolContext; + get(id: string, ): AssistantsToolContext; + + + + + + + + /** + * Streams AssistantsToolInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsToolListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AssistantsToolInstance, done: (err?: Error) => void) => void): void; + each(params: AssistantsToolListInstanceEachOptions, callback?: (item: AssistantsToolInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AssistantsToolInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsToolListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AssistantsToolInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AssistantsToolListInstanceEachOptions, callback?: (item: AssistantsToolInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AssistantsToolInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AssistantsToolPage) => any): Promise; + /** + * Retrieve a single target page of AssistantsToolInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AssistantsToolInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsToolListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AssistantsToolInstance[]) => any): Promise; + list(params: AssistantsToolListInstanceOptions, callback?: (error: Error | null, items: AssistantsToolInstance[]) => any): Promise; + /** + * Lists AssistantsToolInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsToolListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AssistantsToolListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AssistantsToolInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsToolListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AssistantsToolPage) => any): Promise; + page(params: AssistantsToolListInstancePageOptions, callback?: (error: Error | null, items: AssistantsToolPage) => any): Promise; + /** + * Retrieve a single page of AssistantsToolInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssistantsToolListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AssistantsToolListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AssistantsToolListInstance(version: V1, assistantId: string): AssistantsToolListInstance { + if (!isValidPathParam(assistantId)) { + throw new Error('Parameter \'assistantId\' is not valid.'); + } + + const instance = ((id, ) => instance.get(id, )) as AssistantsToolListInstance; + + instance.get = function get(id, ): AssistantsToolContext { + return new AssistantsToolContextImpl(version, assistantId, id); + } + + instance._version = version; + instance._solution = { assistantId, }; + instance._uri = `/Assistants/${assistantId}/Tools`; + + instance.page = function page(params?: AssistantsToolListInstancePageOptions | ((error: Error | null, items: AssistantsToolPage) => any), callback?: (error: Error | null, items: AssistantsToolPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AssistantsToolPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AssistantsToolPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AssistantsToolPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AssistantsToolListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssistantsToolPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssistantsToolPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AssistantsToolPage extends Page { +/** +* Initialize the AssistantsToolPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: AssistantsToolSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AssistantsToolInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AssistantsToolResource): AssistantsToolInstance { + + return new AssistantsToolInstance( + this._version, + payload, + this._solution.assistantId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/assistants/v1/assistant/feedback.ts b/rest/assistants/v1/assistant/feedback.ts new file mode 100644 index 000000000..1b7041216 --- /dev/null +++ b/rest/assistants/v1/assistant/feedback.ts @@ -0,0 +1,567 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class AssistantsV1ServiceCreateFeedbackRequest { + /** + * The message ID. + */ + "messageId"?: string; + /** + * The score to be given(0-1). + */ + "score"?: number; + /** + * The Session ID. + */ + "sessionId": string; + /** + * The text to be given as feedback. + */ + "text"?: string; + + constructor(payload) { + this.messageId = payload["message_id"]; + this.score = payload["score"]; + this.sessionId = payload["session_id"]; + this.text = payload["text"]; + } +} + + + +/** + * Options to pass to create a FeedbackInstance + */ +export interface FeedbackListInstanceCreateOptions { + /** */ + "assistantsV1ServiceCreateFeedbackRequest": AssistantsV1ServiceCreateFeedbackRequest; +} + +/** + * Options to pass to each + */ +export interface FeedbackListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: FeedbackInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface FeedbackListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface FeedbackListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface FeedbackSolution { + id: string; +} + +export interface FeedbackListInstance { + _version: V1; + _solution: FeedbackSolution; + _uri: string; + + + + /** + * Create a FeedbackInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FeedbackInstance + */ + create(params: AssistantsV1ServiceCreateFeedbackRequest, headers?: any, callback?: (error: Error | null, item?: FeedbackInstance) => any): Promise; + + /** + * Create a FeedbackInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FeedbackInstance with HTTP metadata + */ + createWithHttpInfo(params: AssistantsV1ServiceCreateFeedbackRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams FeedbackInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FeedbackListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: FeedbackInstance, done: (err?: Error) => void) => void): void; + each(params: FeedbackListInstanceEachOptions, callback?: (item: FeedbackInstance, done: (err?: Error) => void) => void): void; + /** + * Streams FeedbackInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FeedbackListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: FeedbackInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: FeedbackListInstanceEachOptions, callback?: (item: FeedbackInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of FeedbackInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: FeedbackPage) => any): Promise; + /** + * Retrieve a single target page of FeedbackInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists FeedbackInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FeedbackListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: FeedbackInstance[]) => any): Promise; + list(params: FeedbackListInstanceOptions, callback?: (error: Error | null, items: FeedbackInstance[]) => any): Promise; + /** + * Lists FeedbackInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FeedbackListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: FeedbackListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of FeedbackInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FeedbackListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: FeedbackPage) => any): Promise; + page(params: FeedbackListInstancePageOptions, callback?: (error: Error | null, items: FeedbackPage) => any): Promise; + /** + * Retrieve a single page of FeedbackInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FeedbackListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: FeedbackListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FeedbackListInstance(version: V1, id: string): FeedbackListInstance { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + const instance = {} as FeedbackListInstance; + + instance._version = version; + instance._solution = { id, }; + instance._uri = `/Assistants/${id}/Feedbacks`; + + instance.create = function create(params: AssistantsV1ServiceCreateFeedbackRequest, headers?: any, callback?: (error: Error | null, items: FeedbackInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FeedbackInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AssistantsV1ServiceCreateFeedbackRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new FeedbackInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: FeedbackListInstancePageOptions | ((error: Error | null, items: FeedbackPage) => any), callback?: (error: Error | null, items: FeedbackPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new FeedbackPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: FeedbackPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new FeedbackPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: FeedbackListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FeedbackPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FeedbackPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface FeedbackPayload extends TwilioResponsePayload { + feedbacks: FeedbackResource[]; +} + +interface FeedbackResource { + assistant_id: string; + id: string; + account_sid: string; + user_sid: string; + message_id: string; + score: number; + session_id: string; + text: string; + date_created: Date; + date_updated: Date; +} + +export class FeedbackInstance { + + constructor(protected _version: V1, payload: FeedbackResource, id: string) { + + this.assistantId = (payload.assistant_id); + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.userSid = (payload.user_sid); + this.messageId = (payload.message_id); + this.score = (payload.score); + this.sessionId = (payload.session_id); + this.text = (payload.text); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The Assistant ID. + */ + assistantId: string; + /** + * The Feedback ID. + */ + id: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Feedback. + */ + accountSid: string; + /** + * The SID of the User created the Feedback. + */ + userSid: string; + /** + * The Message ID. + */ + messageId: string; + /** + * The Score to provide as Feedback (0-1) + */ + score: number; + /** + * The Session ID. + */ + sessionId: string; + /** + * The text to be given as feedback. + */ + text: string; + /** + * The date and time in GMT when the Feedback was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Feedback was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + assistantId: this.assistantId, + id: this.id, + accountSid: this.accountSid, + userSid: this.userSid, + messageId: this.messageId, + score: this.score, + sessionId: this.sessionId, + text: this.text, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class FeedbackPage extends Page { +/** +* Initialize the FeedbackPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: FeedbackSolution) { + super(version, response, solution); + } + + /** + * Build an instance of FeedbackInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: FeedbackResource): FeedbackInstance { + + return new FeedbackInstance( + this._version, + payload, + this._solution.id, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/assistants/v1/assistant/message.ts b/rest/assistants/v1/assistant/message.ts new file mode 100644 index 000000000..383e2670c --- /dev/null +++ b/rest/assistants/v1/assistant/message.ts @@ -0,0 +1,268 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class AssistantsV1ServiceAssistantSendMessageRequest { + /** + * The unique identity of user for the session. + */ + "identity": string; + /** + * The unique name for the session. + */ + "sessionId"?: string; + /** + * The query to ask the assistant. + */ + "body": string; + /** + * The webhook url to call after the assistant has generated a response or report an error. + */ + "webhook"?: string; + /** + * one of the modes \'chat\', \'email\' or \'voice\' + */ + "mode"?: string; + + constructor(payload) { + this.identity = payload["identity"]; + this.sessionId = payload["session_id"]; + this.body = payload["body"]; + this.webhook = payload["webhook"]; + this.mode = payload["mode"]; + } +} + + + +/** + * Options to pass to create a MessageInstance + */ +export interface MessageListInstanceCreateOptions { + /** */ + "assistantsV1ServiceAssistantSendMessageRequest": AssistantsV1ServiceAssistantSendMessageRequest; +} + + +export interface MessageSolution { + id: string; +} + +export interface MessageListInstance { + _version: V1; + _solution: MessageSolution; + _uri: string; + + + + /** + * Create a MessageInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(params: AssistantsV1ServiceAssistantSendMessageRequest, headers?: any, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Create a MessageInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(params: AssistantsV1ServiceAssistantSendMessageRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessageListInstance(version: V1, id: string): MessageListInstance { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + const instance = {} as MessageListInstance; + + instance._version = version; + instance._solution = { id, }; + instance._uri = `/Assistants/${id}/Messages`; + + instance.create = function create(params: AssistantsV1ServiceAssistantSendMessageRequest, headers?: any, callback?: (error: Error | null, items: MessageInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AssistantsV1ServiceAssistantSendMessageRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface MessagePayload extends MessageResource {} + +interface MessageResource { + status: string; + flagged: boolean; + aborted: boolean; + session_id: string; + account_sid: string; + body: string; + error: string; +} + +export class MessageInstance { + + constructor(protected _version: V1, payload: MessageResource, id: string) { + + this.status = (payload.status); + this.flagged = (payload.flagged); + this.aborted = (payload.aborted); + this.sessionId = (payload.session_id); + this.accountSid = (payload.account_sid); + this.body = (payload.body); + this.error = (payload.error); + + } + + /** + * success or failure based on whether the request successfully generated a response. + */ + status: string; + /** + * If successful, this property will denote whether the response was flagged or not. + */ + flagged: boolean; + /** + * This property will denote whether the request was aborted or not. + */ + aborted: boolean; + /** + * The unique name for the session. + */ + sessionId: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that sent the Message. + */ + accountSid: string; + /** + * If successful, the body of the generated response + */ + body: string; + /** + * The error message if generation was not successful + */ + error: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + status: this.status, + flagged: this.flagged, + aborted: this.aborted, + sessionId: this.sessionId, + accountSid: this.accountSid, + body: this.body, + error: this.error, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/assistants/v1/knowledge.ts b/rest/assistants/v1/knowledge.ts new file mode 100644 index 000000000..b54e47b9b --- /dev/null +++ b/rest/assistants/v1/knowledge.ts @@ -0,0 +1,1064 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ChunkListInstance } from "./knowledge/chunk"; +import { KnowledgeStatusListInstance } from "./knowledge/knowledgeStatus"; + + +export class AssistantsV1ServiceCreateKnowledgeRequest { + /** + * The Assistant ID. + */ + "assistantId"?: string; + /** + * The description of the knowledge source. + */ + "description"?: string; + /** + * The details of the knowledge source based on the type. + */ + "knowledgeSourceDetails"?: Record; + /** + * The name of the tool. + */ + "name": string; + "policy"?: AssistantsV1ServiceCreatePolicyRequest; + /** + * The type of the knowledge source. + */ + "type": string; + /** + * The embedding model to be used for the knowledge source. It\'s required for \'Database\' type but disallowed for other types. + */ + "embeddingModel"?: string; + + constructor(payload) { + this.assistantId = payload["assistant_id"]; + this.description = payload["description"]; + this.knowledgeSourceDetails = payload["knowledge_source_details"]; + this.name = payload["name"]; + this.policy = payload["policy"]; + this.type = payload["type"]; + this.embeddingModel = payload["embedding_model"]; + } +} + + +export class AssistantsV1ServiceCreatePolicyRequest { + /** + * The description of the policy. + */ + "description"?: string; + /** + * The Policy ID. + */ + "id"?: string; + /** + * The name of the policy. + */ + "name"?: string; + "policyDetails": any | null; + /** + * The description of the policy. + */ + "type"?: string; + + constructor(payload) { + this.description = payload["description"]; + this.id = payload["id"]; + this.name = payload["name"]; + this.policyDetails = payload["policy_details"]; + this.type = payload["type"]; + } +} + + +export class AssistantsV1ServiceUpdateKnowledgeRequest { + /** + * The description of the knowledge source. + */ + "description"?: string; + /** + * The details of the knowledge source based on the type. + */ + "knowledgeSourceDetails"?: Record; + /** + * The name of the knowledge source. + */ + "name"?: string; + "policy"?: AssistantsV1ServiceCreatePolicyRequest; + /** + * The description of the knowledge source. + */ + "type"?: string; + /** + * The embedding model to be used for the knowledge source. It\'s only applicable to \'Database\' type. + */ + "embeddingModel"?: string; + + constructor(payload) { + this.description = payload["description"]; + this.knowledgeSourceDetails = payload["knowledge_source_details"]; + this.name = payload["name"]; + this.policy = payload["policy"]; + this.type = payload["type"]; + this.embeddingModel = payload["embedding_model"]; + } +} + + + + + +/** + * Options to pass to update a KnowledgeInstance + */ +export interface KnowledgeContextUpdateOptions { + /** */ + "assistantsV1ServiceUpdateKnowledgeRequest"?: AssistantsV1ServiceUpdateKnowledgeRequest; +} + +/** + * Options to pass to create a KnowledgeInstance + */ +export interface KnowledgeListInstanceCreateOptions { + /** */ + "assistantsV1ServiceCreateKnowledgeRequest": AssistantsV1ServiceCreateKnowledgeRequest; +} + +/** + * Options to pass to each + */ +export interface KnowledgeListInstanceEachOptions { + /** */ + "assistantId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface KnowledgeListInstanceOptions { + /** */ + "assistantId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface KnowledgeListInstancePageOptions { + /** */ + "assistantId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface KnowledgeContext { + chunks: ChunkListInstance; + knowledgeStatus: KnowledgeStatusListInstance; + + /** + * Remove a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise + + /** + * Fetch a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise; + /** + * Update a KnowledgeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(params: AssistantsV1ServiceUpdateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise; + + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(params: AssistantsV1ServiceUpdateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface KnowledgeContextSolution { + "id": string; +} + +export class KnowledgeContextImpl implements KnowledgeContext { + protected _solution: KnowledgeContextSolution; + protected _uri: string; + + protected _chunks?: ChunkListInstance; + protected _knowledgeStatus?: KnowledgeStatusListInstance; + + constructor(protected _version: V1, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/Knowledge/${id}`; + } + + get chunks(): ChunkListInstance { + this._chunks = this._chunks || ChunkListInstance(this._version, this._solution.id); + return this._chunks; + } + + get knowledgeStatus(): KnowledgeStatusListInstance { + this._knowledgeStatus = this._knowledgeStatus || KnowledgeStatusListInstance(this._version, this._solution.id); + return this._knowledgeStatus; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new KnowledgeInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: AssistantsV1ServiceUpdateKnowledgeRequest | ((error: Error | null, item?: KnowledgeInstance) => any), headers?: any,callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as AssistantsV1ServiceUpdateKnowledgeRequest; + } else { + params = params || {} as Partial as AssistantsV1ServiceUpdateKnowledgeRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: AssistantsV1ServiceUpdateKnowledgeRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as AssistantsV1ServiceUpdateKnowledgeRequest; + } else { + params = params || {} as Partial as AssistantsV1ServiceUpdateKnowledgeRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new KnowledgeInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface KnowledgePayload extends TwilioResponsePayload { + knowledge: KnowledgeResource[]; +} + +interface KnowledgeResource { + description: string; + id: string; + account_sid: string; + knowledge_source_details: Record; + name: string; + status: string; + type: string; + url: string; + embedding_model: string; + date_created: Date; + date_updated: Date; +} + +export class KnowledgeInstance { + protected _solution: KnowledgeContextSolution; + protected _context?: KnowledgeContext; + + constructor(protected _version: V1, payload: KnowledgeResource, id?: string) { + + this.description = (payload.description); + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.knowledgeSourceDetails = (payload.knowledge_source_details); + this.name = (payload.name); + this.status = (payload.status); + this.type = (payload.type); + this.url = (payload.url); + this.embeddingModel = (payload.embedding_model); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { id: id, }; + } + + /** + * The type of knowledge source. + */ + description: string; + /** + * The description of knowledge. + */ + id: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + */ + accountSid: string; + /** + * The details of the knowledge source based on the type. + */ + knowledgeSourceDetails: Record; + /** + * The name of the knowledge source. + */ + name: string; + /** + * The status of processing the knowledge source (\'QUEUED\', \'PROCESSING\', \'COMPLETED\', \'FAILED\') + */ + status: string; + /** + * The type of knowledge source (\'Web\', \'Database\', \'Text\', \'File\') + */ + type: string; + /** + * The url of the knowledge resource. + */ + url: string; + /** + * The embedding model to be used for the knowledge source. + */ + embeddingModel: string; + /** + * The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + private get _proxy(): KnowledgeContext { + this._context = this._context || new KnowledgeContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Remove a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise; + /** + * Update a KnowledgeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(params: AssistantsV1ServiceUpdateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(params: AssistantsV1ServiceUpdateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the chunks. + */ + chunks(): ChunkListInstance { + return this._proxy.chunks; + } + + /** + * Access the knowledgeStatus. + */ + knowledgeStatus(): KnowledgeStatusListInstance { + return this._proxy.knowledgeStatus; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + description: this.description, + id: this.id, + accountSid: this.accountSid, + knowledgeSourceDetails: this.knowledgeSourceDetails, + name: this.name, + status: this.status, + type: this.type, + url: this.url, + embeddingModel: this.embeddingModel, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface KnowledgeSolution { +} + +export interface KnowledgeListInstance { + _version: V1; + _solution: KnowledgeSolution; + _uri: string; + + (id: string, ): KnowledgeContext; + get(id: string, ): KnowledgeContext; + + + + + + + + + /** + * Create a KnowledgeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + create(params: AssistantsV1ServiceCreateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise; + + /** + * Create a KnowledgeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + createWithHttpInfo(params: AssistantsV1ServiceCreateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams KnowledgeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + each(params: KnowledgeListInstanceEachOptions, callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams KnowledgeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: KnowledgeListInstanceEachOptions, callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of KnowledgeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: KnowledgePage) => any): Promise; + /** + * Retrieve a single target page of KnowledgeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists KnowledgeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: KnowledgeInstance[]) => any): Promise; + list(params: KnowledgeListInstanceOptions, callback?: (error: Error | null, items: KnowledgeInstance[]) => any): Promise; + /** + * Lists KnowledgeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: KnowledgeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of KnowledgeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: KnowledgePage) => any): Promise; + page(params: KnowledgeListInstancePageOptions, callback?: (error: Error | null, items: KnowledgePage) => any): Promise; + /** + * Retrieve a single page of KnowledgeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: KnowledgeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function KnowledgeListInstance(version: V1): KnowledgeListInstance { + const instance = ((id, ) => instance.get(id, )) as KnowledgeListInstance; + + instance.get = function get(id, ): KnowledgeContext { + return new KnowledgeContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Knowledge`; + + instance.create = function create(params: AssistantsV1ServiceCreateKnowledgeRequest, headers?: any, callback?: (error: Error | null, items: KnowledgeInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AssistantsV1ServiceCreateKnowledgeRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new KnowledgeInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: KnowledgeListInstancePageOptions | ((error: Error | null, items: KnowledgePage) => any), callback?: (error: Error | null, items: KnowledgePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["assistantId"] !== undefined) + data["AssistantId"] = params["assistantId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new KnowledgePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: KnowledgePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new KnowledgePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: KnowledgeListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["assistantId"] !== undefined) + data["AssistantId"] = params["assistantId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new KnowledgePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new KnowledgePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class KnowledgePage extends Page { +/** +* Initialize the KnowledgePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: KnowledgeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of KnowledgeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: KnowledgeResource): KnowledgeInstance { + + return new KnowledgeInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/assistants/v1/knowledge/chunk.ts b/rest/assistants/v1/knowledge/chunk.ts new file mode 100644 index 000000000..caeebd1e2 --- /dev/null +++ b/rest/assistants/v1/knowledge/chunk.ts @@ -0,0 +1,412 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface ChunkListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChunkInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChunkListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChunkListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface ChunkSolution { + id: string; +} + +export interface ChunkListInstance { + _version: V1; + _solution: ChunkSolution; + _uri: string; + + + + + /** + * Streams ChunkInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + each(params: ChunkListInstanceEachOptions, callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChunkInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ChunkListInstanceEachOptions, callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChunkInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChunkPage) => any): Promise; + /** + * Retrieve a single target page of ChunkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ChunkInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ChunkInstance[]) => any): Promise; + list(params: ChunkListInstanceOptions, callback?: (error: Error | null, items: ChunkInstance[]) => any): Promise; + /** + * Lists ChunkInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ChunkListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ChunkInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ChunkPage) => any): Promise; + page(params: ChunkListInstancePageOptions, callback?: (error: Error | null, items: ChunkPage) => any): Promise; + /** + * Retrieve a single page of ChunkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ChunkListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChunkListInstance(version: V1, id: string): ChunkListInstance { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + const instance = {} as ChunkListInstance; + + instance._version = version; + instance._solution = { id, }; + instance._uri = `/Knowledge/${id}/Chunks`; + + instance.page = function page(params?: ChunkListInstancePageOptions | ((error: Error | null, items: ChunkPage) => any), callback?: (error: Error | null, items: ChunkPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChunkPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChunkPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChunkPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ChunkListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChunkPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChunkPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ChunkPayload extends TwilioResponsePayload { + chunks: ChunkResource[]; +} + +interface ChunkResource { + account_sid: string; + content: string; + metadata: Record; + date_created: Date; + date_updated: Date; +} + +export class ChunkInstance { + + constructor(protected _version: V1, payload: ChunkResource, id: string) { + + this.accountSid = (payload.account_sid); + this.content = (payload.content); + this.metadata = (payload.metadata); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + */ + accountSid: string; + /** + * The chunk content. + */ + content: string; + /** + * The metadata of the chunk. + */ + metadata: Record; + /** + * The date and time in GMT when the Chunk was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Chunk was updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + content: this.content, + metadata: this.metadata, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class ChunkPage extends Page { +/** +* Initialize the ChunkPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ChunkSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ChunkInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChunkResource): ChunkInstance { + + return new ChunkInstance( + this._version, + payload, + this._solution.id, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/assistants/v1/knowledge/knowledgeStatus.ts b/rest/assistants/v1/knowledge/knowledgeStatus.ts new file mode 100644 index 000000000..9000c93e3 --- /dev/null +++ b/rest/assistants/v1/knowledge/knowledgeStatus.ts @@ -0,0 +1,260 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +export interface KnowledgeStatusContext { + + /** + * Fetch a KnowledgeStatusInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeStatusInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeStatusInstance) => any): Promise + + /** + * Fetch a KnowledgeStatusInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeStatusInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface KnowledgeStatusContextSolution { + "id": string; +} + +export class KnowledgeStatusContextImpl implements KnowledgeStatusContext { + protected _solution: KnowledgeStatusContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/Knowledge/${id}/Status`; + } + + fetch(callback?: (error: Error | null, item?: KnowledgeStatusInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeStatusInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new KnowledgeStatusInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface KnowledgeStatusPayload extends KnowledgeStatusResource {} + +interface KnowledgeStatusResource { + account_sid: string; + status: string; + last_status: string; + date_updated: Date; +} + +export class KnowledgeStatusInstance { + protected _solution: KnowledgeStatusContextSolution; + protected _context?: KnowledgeStatusContext; + + constructor(protected _version: V1, payload: KnowledgeStatusResource, id: string) { + + this.accountSid = (payload.account_sid); + this.status = (payload.status); + this.lastStatus = (payload.last_status); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { id, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + */ + accountSid: string; + /** + * The status of processing the knowledge source (\'QUEUED\', \'PROCESSING\', \'COMPLETED\', \'FAILED\') + */ + status: string; + /** + * The last status of processing the knowledge source (\'QUEUED\', \'PROCESSING\', \'COMPLETED\', \'FAILED\') + */ + lastStatus: string; + /** + * The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + private get _proxy(): KnowledgeStatusContext { + this._context = this._context || new KnowledgeStatusContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Fetch a KnowledgeStatusInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeStatusInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeStatusInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a KnowledgeStatusInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeStatusInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + status: this.status, + lastStatus: this.lastStatus, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface KnowledgeStatusSolution { + id: string; +} + +export interface KnowledgeStatusListInstance { + _version: V1; + _solution: KnowledgeStatusSolution; + _uri: string; + + (): KnowledgeStatusContext; + get(): KnowledgeStatusContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function KnowledgeStatusListInstance(version: V1, id: string): KnowledgeStatusListInstance { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + const instance = (() => instance.get()) as KnowledgeStatusListInstance; + + instance.get = function get(): KnowledgeStatusContext { + return new KnowledgeStatusContextImpl(version, id); + } + + instance._version = version; + instance._solution = { id, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/assistants/v1/policy.ts b/rest/assistants/v1/policy.ts new file mode 100644 index 000000000..a7e6ee2de --- /dev/null +++ b/rest/assistants/v1/policy.ts @@ -0,0 +1,454 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface PolicyListInstanceEachOptions { + /** The tool ID. */ + "toolId"?: string; + /** The knowledge ID. */ + "knowledgeId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PolicyInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PolicyListInstanceOptions { + /** The tool ID. */ + "toolId"?: string; + /** The knowledge ID. */ + "knowledgeId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PolicyListInstancePageOptions { + /** The tool ID. */ + "toolId"?: string; + /** The knowledge ID. */ + "knowledgeId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface PolicySolution { +} + +export interface PolicyListInstance { + _version: V1; + _solution: PolicySolution; + _uri: string; + + + + + /** + * Streams PolicyInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PolicyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PolicyInstance, done: (err?: Error) => void) => void): void; + each(params: PolicyListInstanceEachOptions, callback?: (item: PolicyInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PolicyInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PolicyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PolicyInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PolicyListInstanceEachOptions, callback?: (item: PolicyInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PolicyInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PolicyPage) => any): Promise; + /** + * Retrieve a single target page of PolicyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists PolicyInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PolicyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PolicyInstance[]) => any): Promise; + list(params: PolicyListInstanceOptions, callback?: (error: Error | null, items: PolicyInstance[]) => any): Promise; + /** + * Lists PolicyInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PolicyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: PolicyListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of PolicyInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PolicyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PolicyPage) => any): Promise; + page(params: PolicyListInstancePageOptions, callback?: (error: Error | null, items: PolicyPage) => any): Promise; + /** + * Retrieve a single page of PolicyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PolicyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: PolicyListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PolicyListInstance(version: V1): PolicyListInstance { + const instance = {} as PolicyListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Policies`; + + instance.page = function page(params?: PolicyListInstancePageOptions | ((error: Error | null, items: PolicyPage) => any), callback?: (error: Error | null, items: PolicyPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["toolId"] !== undefined) + data["ToolId"] = params["toolId"]; + if (params["knowledgeId"] !== undefined) + data["KnowledgeId"] = params["knowledgeId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PolicyPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PolicyPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PolicyPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PolicyListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["toolId"] !== undefined) + data["ToolId"] = params["toolId"]; + if (params["knowledgeId"] !== undefined) + data["KnowledgeId"] = params["knowledgeId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PolicyPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PolicyPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface PolicyPayload extends TwilioResponsePayload { + policies: PolicyResource[]; +} + +interface PolicyResource { + id: string; + name: string; + description: string; + account_sid: string; + user_sid: string; + type: string; + policy_details: Record; + date_created: Date; + date_updated: Date; +} + +export class PolicyInstance { + + constructor(protected _version: V1, payload: PolicyResource) { + + this.id = (payload.id); + this.name = (payload.name); + this.description = (payload.description); + this.accountSid = (payload.account_sid); + this.userSid = (payload.user_sid); + this.type = (payload.type); + this.policyDetails = (payload.policy_details); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The Policy ID. + */ + id: string; + /** + * The name of the policy. + */ + name: string; + /** + * The description of the policy. + */ + description: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Policy resource. + */ + accountSid: string; + /** + * The SID of the User that created the Policy resource. + */ + userSid: string; + /** + * The type of the policy. + */ + type: string; + /** + * The details of the policy based on the type. + */ + policyDetails: Record; + /** + * The date and time in GMT when the Policy was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Policy was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + name: this.name, + description: this.description, + accountSid: this.accountSid, + userSid: this.userSid, + type: this.type, + policyDetails: this.policyDetails, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class PolicyPage extends Page { +/** +* Initialize the PolicyPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: PolicySolution) { + super(version, response, solution); + } + + /** + * Build an instance of PolicyInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PolicyResource): PolicyInstance { + + return new PolicyInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/assistants/v1/session.ts b/rest/assistants/v1/session.ts new file mode 100644 index 000000000..6d02bcc10 --- /dev/null +++ b/rest/assistants/v1/session.ts @@ -0,0 +1,573 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { MessageListInstance } from "./session/message"; + + + + +/** + * Options to pass to each + */ +export interface SessionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SessionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SessionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SessionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SessionContext { + messages: MessageListInstance; + + /** + * Fetch a SessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance + */ + fetch(callback?: (error: Error | null, item?: SessionInstance) => any): Promise + + /** + * Fetch a SessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SessionContextSolution { + "id": string; +} + +export class SessionContextImpl implements SessionContext { + protected _solution: SessionContextSolution; + protected _uri: string; + + protected _messages?: MessageListInstance; + + constructor(protected _version: V1, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/Sessions/${id}`; + } + + get messages(): MessageListInstance { + this._messages = this._messages || MessageListInstance(this._version, this._solution.id); + return this._messages; + } + + fetch(callback?: (error: Error | null, item?: SessionInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SessionInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new SessionInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SessionPayload extends TwilioResponsePayload { + sessions: SessionResource[]; +} + +interface SessionResource { + id: string; + account_sid: string; + assistant_id: string; + verified: boolean; + identity: string; + date_created: Date; + date_updated: Date; +} + +export class SessionInstance { + protected _solution: SessionContextSolution; + protected _context?: SessionContext; + + constructor(protected _version: V1, payload: SessionResource, id?: string) { + + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.assistantId = (payload.assistant_id); + this.verified = (payload.verified); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { id: id, }; + } + + /** + * The Session ID. + */ + id: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Session resource. + */ + accountSid: string; + /** + * The Assistant ID. + */ + assistantId: string; + /** + * True if the session is verified. + */ + verified: boolean; + /** + * The unique identity of user for the session. + */ + identity: string; + /** + * The date and time in GMT when the Session was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Session was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + private get _proxy(): SessionContext { + this._context = this._context || new SessionContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Fetch a SessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance + */ + fetch(callback?: (error: Error | null, item?: SessionInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the messages. + */ + messages(): MessageListInstance { + return this._proxy.messages; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + accountSid: this.accountSid, + assistantId: this.assistantId, + verified: this.verified, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SessionSolution { +} + +export interface SessionListInstance { + _version: V1; + _solution: SessionSolution; + _uri: string; + + (id: string, ): SessionContext; + get(id: string, ): SessionContext; + + + + + + /** + * Streams SessionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SessionInstance, done: (err?: Error) => void) => void): void; + each(params: SessionListInstanceEachOptions, callback?: (item: SessionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SessionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SessionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SessionListInstanceEachOptions, callback?: (item: SessionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SessionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SessionPage) => any): Promise; + /** + * Retrieve a single target page of SessionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists SessionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SessionInstance[]) => any): Promise; + list(params: SessionListInstanceOptions, callback?: (error: Error | null, items: SessionInstance[]) => any): Promise; + /** + * Lists SessionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: SessionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of SessionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SessionPage) => any): Promise; + page(params: SessionListInstancePageOptions, callback?: (error: Error | null, items: SessionPage) => any): Promise; + /** + * Retrieve a single page of SessionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: SessionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SessionListInstance(version: V1): SessionListInstance { + const instance = ((id, ) => instance.get(id, )) as SessionListInstance; + + instance.get = function get(id, ): SessionContext { + return new SessionContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Sessions`; + + instance.page = function page(params?: SessionListInstancePageOptions | ((error: Error | null, items: SessionPage) => any), callback?: (error: Error | null, items: SessionPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SessionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SessionPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SessionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SessionListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SessionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SessionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SessionPage extends Page { +/** +* Initialize the SessionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: SessionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SessionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SessionResource): SessionInstance { + + return new SessionInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/assistants/v1/session/message.ts b/rest/assistants/v1/session/message.ts new file mode 100644 index 000000000..47bb237e1 --- /dev/null +++ b/rest/assistants/v1/session/message.ts @@ -0,0 +1,447 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface MessageListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MessageInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MessageListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MessageListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface MessageSolution { + sessionId: string; +} + +export interface MessageListInstance { + _version: V1; + _solution: MessageSolution; + _uri: string; + + + + + /** + * Streams MessageInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + each(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MessageInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single target page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MessageInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + list(params: MessageListInstanceOptions, callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + /** + * Lists MessageInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MessageListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MessagePage) => any): Promise; + page(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessageListInstance(version: V1, sessionId: string): MessageListInstance { + if (!isValidPathParam(sessionId)) { + throw new Error('Parameter \'sessionId\' is not valid.'); + } + + const instance = {} as MessageListInstance; + + instance._version = version; + instance._solution = { sessionId, }; + instance._uri = `/Sessions/${sessionId}/Messages`; + + instance.page = function page(params?: MessageListInstancePageOptions | ((error: Error | null, items: MessagePage) => any), callback?: (error: Error | null, items: MessagePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MessagePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MessagePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MessageListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface MessagePayload extends TwilioResponsePayload { + messages: MessageResource[]; +} + +interface MessageResource { + id: string; + account_sid: string; + assistant_id: string; + session_id: string; + identity: string; + role: string; + content: Record; + meta: Record; + date_created: Date; + date_updated: Date; +} + +export class MessageInstance { + + constructor(protected _version: V1, payload: MessageResource, sessionId: string) { + + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.assistantId = (payload.assistant_id); + this.sessionId = (payload.session_id); + this.identity = (payload.identity); + this.role = (payload.role); + this.content = (payload.content); + this.meta = (payload.meta); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The message ID. + */ + id: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Message resource. + */ + accountSid: string; + /** + * The Assistant ID. + */ + assistantId: string; + /** + * The Session ID. + */ + sessionId: string; + /** + * The identity of the user. + */ + identity: string; + /** + * The role of the user associated with the message. + */ + role: string; + /** + * The content of the message. + */ + content: Record; + /** + * The metadata of the message. + */ + meta: Record; + /** + * The date and time in GMT when the Message was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Message was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + accountSid: this.accountSid, + assistantId: this.assistantId, + sessionId: this.sessionId, + identity: this.identity, + role: this.role, + content: this.content, + meta: this.meta, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class MessagePage extends Page { +/** +* Initialize the MessagePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: MessageSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MessageInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MessageResource): MessageInstance { + + return new MessageInstance( + this._version, + payload, + this._solution.sessionId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/assistants/v1/tool.ts b/rest/assistants/v1/tool.ts new file mode 100644 index 000000000..dfa696172 --- /dev/null +++ b/rest/assistants/v1/tool.ts @@ -0,0 +1,1100 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Assistants + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class AssistantsV1ServiceCreatePolicyRequest { + /** + * The description of the policy. + */ + "description"?: string; + /** + * The Policy ID. + */ + "id"?: string; + /** + * The name of the policy. + */ + "name"?: string; + "policyDetails": any | null; + /** + * The description of the policy. + */ + "type"?: string; + + constructor(payload) { + this.description = payload["description"]; + this.id = payload["id"]; + this.name = payload["name"]; + this.policyDetails = payload["policy_details"]; + this.type = payload["type"]; + } +} + + +export class AssistantsV1ServiceCreateToolRequest { + /** + * The Assistant ID. + */ + "assistantId"?: string; + /** + * The description of the tool. + */ + "description"?: string; + /** + * True if the tool is enabled. + */ + "enabled": boolean; + /** + * The metadata related to method, url, input_schema to used with the Tool. + */ + "meta"?: Record; + /** + * The name of the tool. + */ + "name": string; + "policy"?: AssistantsV1ServiceCreatePolicyRequest; + /** + * The description of the tool. + */ + "type": string; + + constructor(payload) { + this.assistantId = payload["assistant_id"]; + this.description = payload["description"]; + this.enabled = payload["enabled"]; + this.meta = payload["meta"]; + this.name = payload["name"]; + this.policy = payload["policy"]; + this.type = payload["type"]; + } +} + + +export class AssistantsV1ServicePolicy { + /** + * The Policy ID. + */ + "id"?: string; + /** + * The name of the policy. + */ + "name"?: string; + /** + * The description of the policy. + */ + "description"?: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Policy resource. + */ + "accountSid"?: string; + /** + * The SID of the User that created the Policy resource. + */ + "userSid"?: string; + /** + * The type of the policy. + */ + "type": string; + /** + * The details of the policy based on the type. + */ + "policyDetails": Record; + /** + * The date and time in GMT when the Policy was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + "dateCreated"?: Date; + /** + * The date and time in GMT when the Policy was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + "dateUpdated"?: Date; + + constructor(payload) { + this.id = payload["id"]; + this.name = payload["name"]; + this.description = payload["description"]; + this.accountSid = payload["account_sid"]; + this.userSid = payload["user_sid"]; + this.type = payload["type"]; + this.policyDetails = payload["policy_details"]; + this.dateCreated = payload["date_created"]; + this.dateUpdated = payload["date_updated"]; + } +} + + +export class AssistantsV1ServiceUpdateToolRequest { + /** + * The Assistant ID. + */ + "assistantId"?: string; + /** + * The description of the tool. + */ + "description"?: string; + /** + * True if the tool is enabled. + */ + "enabled"?: boolean; + /** + * The metadata related to method, url, input_schema to used with the Tool. + */ + "meta"?: Record; + /** + * The name of the tool. + */ + "name"?: string; + "policy"?: AssistantsV1ServiceCreatePolicyRequest; + /** + * The type of the tool. + */ + "type"?: string; + + constructor(payload) { + this.assistantId = payload["assistant_id"]; + this.description = payload["description"]; + this.enabled = payload["enabled"]; + this.meta = payload["meta"]; + this.name = payload["name"]; + this.policy = payload["policy"]; + this.type = payload["type"]; + } +} + + + + + +/** + * Options to pass to update a ToolInstance + */ +export interface ToolContextUpdateOptions { + /** */ + "assistantsV1ServiceUpdateToolRequest"?: AssistantsV1ServiceUpdateToolRequest; +} + +/** + * Options to pass to create a ToolInstance + */ +export interface ToolListInstanceCreateOptions { + /** */ + "assistantsV1ServiceCreateToolRequest": AssistantsV1ServiceCreateToolRequest; +} + +/** + * Options to pass to each + */ +export interface ToolListInstanceEachOptions { + /** */ + "assistantId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ToolInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ToolListInstanceOptions { + /** */ + "assistantId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ToolListInstancePageOptions { + /** */ + "assistantId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ToolContext { + + /** + * Remove a ToolInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ToolInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ToolInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance + */ + fetch(callback?: (error: Error | null, item?: ToolInstance) => any): Promise + + /** + * Fetch a ToolInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ToolInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance + */ + update(callback?: (error: Error | null, item?: ToolInstance) => any): Promise; + /** + * Update a ToolInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance + */ + update(params: AssistantsV1ServiceUpdateToolRequest, headers?: any, callback?: (error: Error | null, item?: ToolInstance) => any): Promise; + + /** + * Update a ToolInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ToolInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance with HTTP metadata + */ + updateWithHttpInfo(params: AssistantsV1ServiceUpdateToolRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ToolContextSolution { + "id": string; +} + +export class ToolContextImpl implements ToolContext { + protected _solution: ToolContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/Tools/${id}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ToolInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ToolInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ToolInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: AssistantsV1ServiceUpdateToolRequest | ((error: Error | null, item?: ToolInstance) => any), headers?: any,callback?: (error: Error | null, item?: ToolInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as AssistantsV1ServiceUpdateToolRequest; + } else { + params = params || {} as Partial as AssistantsV1ServiceUpdateToolRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new ToolInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: AssistantsV1ServiceUpdateToolRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as AssistantsV1ServiceUpdateToolRequest; + } else { + params = params || {} as Partial as AssistantsV1ServiceUpdateToolRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ToolInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ToolPayload extends TwilioResponsePayload { + tools: ToolResource[]; +} + +interface ToolResource { + account_sid: string; + description: string; + enabled: boolean; + id: string; + meta: Record; + name: string; + requires_auth: boolean; + type: string; + url: string; + date_created: Date; + date_updated: Date; + policies: Array; +} + +export class ToolInstance { + protected _solution: ToolContextSolution; + protected _context?: ToolContext; + + constructor(protected _version: V1, payload: ToolResource, id?: string) { + + this.accountSid = (payload.account_sid); + this.description = (payload.description); + this.enabled = (payload.enabled); + this.id = (payload.id); + this.meta = (payload.meta); + this.name = (payload.name); + this.requiresAuth = (payload.requires_auth); + this.type = (payload.type); + this.url = (payload.url); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.policies = payload.policies !== null && payload.policies !== undefined ? payload.policies.map( + (payload: any) => new AssistantsV1ServicePolicy(payload) + ) : null; + + this._solution = { id: id, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tool resource. + */ + accountSid: string; + /** + * The description of the tool. + */ + description: string; + /** + * True if the tool is enabled. + */ + enabled: boolean; + /** + * The tool ID. + */ + id: string; + /** + * The metadata related to method, url, input_schema to used with the Tool. + */ + meta: Record; + /** + * The name of the tool. + */ + name: string; + /** + * The authentication requirement for the tool. + */ + requiresAuth: boolean; + /** + * The type of the tool. (\'WEBHOOK\') + */ + type: string; + /** + * The url of the tool resource. + */ + url: string; + /** + * The date and time in GMT when the Tool was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Tool was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The Policies associated with the tool. + */ + policies: Array; + + private get _proxy(): ToolContext { + this._context = this._context || new ToolContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Remove a ToolInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ToolInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ToolInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance + */ + fetch(callback?: (error: Error | null, item?: ToolInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ToolInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ToolInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance + */ + update(callback?: (error: Error | null, item?: ToolInstance) => any): Promise; + /** + * Update a ToolInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance + */ + update(params: AssistantsV1ServiceUpdateToolRequest, headers?: any, callback?: (error: Error | null, item?: ToolInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ToolInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ToolInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ToolInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance with HTTP metadata + */ + updateWithHttpInfo(params: AssistantsV1ServiceUpdateToolRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + description: this.description, + enabled: this.enabled, + id: this.id, + meta: this.meta, + name: this.name, + requiresAuth: this.requiresAuth, + type: this.type, + url: this.url, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + policies: this.policies, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ToolSolution { +} + +export interface ToolListInstance { + _version: V1; + _solution: ToolSolution; + _uri: string; + + (id: string, ): ToolContext; + get(id: string, ): ToolContext; + + + + + + + + + /** + * Create a ToolInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance + */ + create(params: AssistantsV1ServiceCreateToolRequest, headers?: any, callback?: (error: Error | null, item?: ToolInstance) => any): Promise; + + /** + * Create a ToolInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ToolInstance with HTTP metadata + */ + createWithHttpInfo(params: AssistantsV1ServiceCreateToolRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ToolInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ToolListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ToolInstance, done: (err?: Error) => void) => void): void; + each(params: ToolListInstanceEachOptions, callback?: (item: ToolInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ToolInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ToolListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ToolInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ToolListInstanceEachOptions, callback?: (item: ToolInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ToolInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ToolPage) => any): Promise; + /** + * Retrieve a single target page of ToolInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ToolInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ToolListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ToolInstance[]) => any): Promise; + list(params: ToolListInstanceOptions, callback?: (error: Error | null, items: ToolInstance[]) => any): Promise; + /** + * Lists ToolInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ToolListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ToolListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ToolInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ToolListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ToolPage) => any): Promise; + page(params: ToolListInstancePageOptions, callback?: (error: Error | null, items: ToolPage) => any): Promise; + /** + * Retrieve a single page of ToolInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ToolListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ToolListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ToolListInstance(version: V1): ToolListInstance { + const instance = ((id, ) => instance.get(id, )) as ToolListInstance; + + instance.get = function get(id, ): ToolContext { + return new ToolContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Tools`; + + instance.create = function create(params: AssistantsV1ServiceCreateToolRequest, headers?: any, callback?: (error: Error | null, items: ToolInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ToolInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AssistantsV1ServiceCreateToolRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ToolInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ToolListInstancePageOptions | ((error: Error | null, items: ToolPage) => any), callback?: (error: Error | null, items: ToolPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["assistantId"] !== undefined) + data["AssistantId"] = params["assistantId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ToolPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ToolPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ToolPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ToolListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["assistantId"] !== undefined) + data["AssistantId"] = params["assistantId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ToolPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ToolPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ToolPage extends Page { +/** +* Initialize the ToolPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ToolSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ToolInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ToolResource): ToolInstance { + + return new ToolInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/bulkexports/V1.ts b/rest/bulkexports/V1.ts new file mode 100644 index 000000000..1c6ecc8dd --- /dev/null +++ b/rest/bulkexports/V1.ts @@ -0,0 +1,56 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Bulkexports + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import BulkexportsBase from "../BulkexportsBase"; +import Version from "../../base/Version"; +import { ExportListInstance } from "./v1/export"; +import { ExportConfigurationListInstance } from "./v1/exportConfiguration"; +import { JobListInstance } from "./v1/job"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Bulkexports + * + * @param domain - The Twilio (Twilio.Bulkexports) domain + */ + constructor(domain: BulkexportsBase) { + super(domain, "v1"); + } + + /** exports - { Twilio.Bulkexports.V1.ExportListInstance } resource */ + protected _exports?: ExportListInstance; + /** exportConfiguration - { Twilio.Bulkexports.V1.ExportConfigurationListInstance } resource */ + protected _exportConfiguration?: ExportConfigurationListInstance; + /** jobs - { Twilio.Bulkexports.V1.JobListInstance } resource */ + protected _jobs?: JobListInstance; + + /** Getter for exports resource */ + get exports(): ExportListInstance { + this._exports = this._exports || ExportListInstance(this); + return this._exports; + } + + /** Getter for exportConfiguration resource */ + get exportConfiguration(): ExportConfigurationListInstance { + this._exportConfiguration = this._exportConfiguration || ExportConfigurationListInstance(this); + return this._exportConfiguration; + } + + /** Getter for jobs resource */ + get jobs(): JobListInstance { + this._jobs = this._jobs || JobListInstance(this); + return this._jobs; + } + +} diff --git a/rest/bulkexports/v1/export.ts b/rest/bulkexports/v1/export.ts new file mode 100644 index 000000000..aa6be0a90 --- /dev/null +++ b/rest/bulkexports/v1/export.ts @@ -0,0 +1,278 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Bulkexports + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { DayListInstance } from "./export/day"; +import { ExportCustomJobListInstance } from "./export/exportCustomJob"; + + + + +export interface ExportContext { + days: DayListInstance; + exportCustomJobs: ExportCustomJobListInstance; + + /** + * Fetch a ExportInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportInstance + */ + fetch(callback?: (error: Error | null, item?: ExportInstance) => any): Promise + + /** + * Fetch a ExportInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ExportContextSolution { + "resourceType": string; +} + +export class ExportContextImpl implements ExportContext { + protected _solution: ExportContextSolution; + protected _uri: string; + + protected _days?: DayListInstance; + protected _exportCustomJobs?: ExportCustomJobListInstance; + + constructor(protected _version: V1, resourceType: string) { + if (!isValidPathParam(resourceType)) { + throw new Error('Parameter \'resourceType\' is not valid.'); + } + + this._solution = { resourceType, }; + this._uri = `/Exports/${resourceType}`; + } + + get days(): DayListInstance { + this._days = this._days || DayListInstance(this._version, this._solution.resourceType); + return this._days; + } + + get exportCustomJobs(): ExportCustomJobListInstance { + this._exportCustomJobs = this._exportCustomJobs || ExportCustomJobListInstance(this._version, this._solution.resourceType); + return this._exportCustomJobs; + } + + fetch(callback?: (error: Error | null, item?: ExportInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ExportInstance(operationVersion, payload, instance._solution.resourceType)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ExportInstance(operationVersion, response.body, instance._solution.resourceType) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ExportPayload extends ExportResource {} + +interface ExportResource { + resource_type: string; + url: string; + links: Record; +} + +export class ExportInstance { + protected _solution: ExportContextSolution; + protected _context?: ExportContext; + + constructor(protected _version: V1, payload: ExportResource, resourceType?: string) { + + this.resourceType = (payload.resource_type); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { resourceType: resourceType, }; + } + + /** + * The type of communication – Messages, Calls, Conferences, and Participants + */ + resourceType: string; + /** + * The URL of this resource. + */ + url: string; + /** + * Contains a dictionary of URL links to nested resources of this Export. + */ + links: Record; + + private get _proxy(): ExportContext { + this._context = this._context || new ExportContextImpl(this._version, this._solution.resourceType); + return this._context; + } + + /** + * Fetch a ExportInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportInstance + */ + fetch(callback?: (error: Error | null, item?: ExportInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ExportInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the days. + */ + days(): DayListInstance { + return this._proxy.days; + } + + /** + * Access the exportCustomJobs. + */ + exportCustomJobs(): ExportCustomJobListInstance { + return this._proxy.exportCustomJobs; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + resourceType: this.resourceType, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ExportSolution { +} + +export interface ExportListInstance { + _version: V1; + _solution: ExportSolution; + _uri: string; + + (resourceType: string, ): ExportContext; + get(resourceType: string, ): ExportContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExportListInstance(version: V1): ExportListInstance { + const instance = ((resourceType, ) => instance.get(resourceType, )) as ExportListInstance; + + instance.get = function get(resourceType, ): ExportContext { + return new ExportContextImpl(version, resourceType); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/bulkexports/v1/export/day.ts b/rest/bulkexports/v1/export/day.ts new file mode 100644 index 000000000..91fd03451 --- /dev/null +++ b/rest/bulkexports/v1/export/day.ts @@ -0,0 +1,559 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Bulkexports + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface DayListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 400. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DayInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DayListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 400. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DayListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 400. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface DayContext { + + /** + * Fetch a DayInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DayInstance + */ + fetch(callback?: (error: Error | null, item?: DayInstance) => any): Promise + + /** + * Fetch a DayInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DayInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DayContextSolution { + "resourceType": string; + "day": string; +} + +export class DayContextImpl implements DayContext { + protected _solution: DayContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, resourceType: string, day: string) { + if (!isValidPathParam(resourceType)) { + throw new Error('Parameter \'resourceType\' is not valid.'); + } + + if (!isValidPathParam(day)) { + throw new Error('Parameter \'day\' is not valid.'); + } + + this._solution = { resourceType, day, }; + this._uri = `/Exports/${resourceType}/Days/${day}`; + } + + fetch(callback?: (error: Error | null, item?: DayInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DayInstance(operationVersion, payload, instance._solution.resourceType, instance._solution.day)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new DayInstance(operationVersion, response.body, instance._solution.resourceType, instance._solution.day) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DayPayload extends TwilioResponsePayload { + days: DayResource[]; +} + +interface DayResource { + redirect_to: string; + day: string; + size: number; + create_date: string; + friendly_name: string; + resource_type: string; +} + +export class DayInstance { + protected _solution: DayContextSolution; + protected _context?: DayContext; + + constructor(protected _version: V1, payload: DayResource, resourceType: string, day?: string) { + + this.redirectTo = (payload.redirect_to); + this.day = (payload.day); + this.size = deserialize.integer(payload.size); + this.createDate = (payload.create_date); + this.friendlyName = (payload.friendly_name); + this.resourceType = (payload.resource_type); + + this._solution = { resourceType, day: day, }; + } + + redirectTo: string; + /** + * The ISO 8601 format date of the resources in the file, for a UTC day + */ + day: string; + /** + * The size of the day\'s data file in bytes + */ + size: number; + /** + * The ISO 8601 format date when resources is created + */ + createDate: string; + /** + * The friendly name specified when creating the job + */ + friendlyName: string; + /** + * The type of communication – Messages, Calls, Conferences, and Participants + */ + resourceType: string; + + private get _proxy(): DayContext { + this._context = this._context || new DayContextImpl(this._version, this._solution.resourceType, this._solution.day); + return this._context; + } + + /** + * Fetch a DayInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DayInstance + */ + fetch(callback?: (error: Error | null, item?: DayInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DayInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DayInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + redirectTo: this.redirectTo, + day: this.day, + size: this.size, + createDate: this.createDate, + friendlyName: this.friendlyName, + resourceType: this.resourceType, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DaySolution { + resourceType: string; +} + +export interface DayListInstance { + _version: V1; + _solution: DaySolution; + _uri: string; + + (day: string, ): DayContext; + get(day: string, ): DayContext; + + + + + + /** + * Streams DayInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DayListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DayInstance, done: (err?: Error) => void) => void): void; + each(params: DayListInstanceEachOptions, callback?: (item: DayInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DayInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DayListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DayInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DayListInstanceEachOptions, callback?: (item: DayInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DayInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DayPage) => any): Promise; + /** + * Retrieve a single target page of DayInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists DayInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DayListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DayInstance[]) => any): Promise; + list(params: DayListInstanceOptions, callback?: (error: Error | null, items: DayInstance[]) => any): Promise; + /** + * Lists DayInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DayListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: DayListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of DayInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DayListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DayPage) => any): Promise; + page(params: DayListInstancePageOptions, callback?: (error: Error | null, items: DayPage) => any): Promise; + /** + * Retrieve a single page of DayInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DayListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: DayListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DayListInstance(version: V1, resourceType: string): DayListInstance { + if (!isValidPathParam(resourceType)) { + throw new Error('Parameter \'resourceType\' is not valid.'); + } + + const instance = ((day, ) => instance.get(day, )) as DayListInstance; + + instance.get = function get(day, ): DayContext { + return new DayContextImpl(version, resourceType, day); + } + + instance._version = version; + instance._solution = { resourceType, }; + instance._uri = `/Exports/${resourceType}/Days`; + + instance.page = function page(params?: DayListInstancePageOptions | ((error: Error | null, items: DayPage) => any), callback?: (error: Error | null, items: DayPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DayPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DayPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DayPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DayListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DayPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DayPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class DayPage extends Page { +/** +* Initialize the DayPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: DaySolution) { + super(version, response, solution); + } + + /** + * Build an instance of DayInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DayResource): DayInstance { + + return new DayInstance( + this._version, + payload, + this._solution.resourceType, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/bulkexports/v1/export/exportCustomJob.ts b/rest/bulkexports/v1/export/exportCustomJob.ts new file mode 100644 index 000000000..adb81abef --- /dev/null +++ b/rest/bulkexports/v1/export/exportCustomJob.ts @@ -0,0 +1,599 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Bulkexports + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to create a ExportCustomJobInstance + */ +export interface ExportCustomJobListInstanceCreateOptions { + /** The start day for the custom export specified as a string in the format of yyyy-mm-dd */ + "startDay": string; + /** The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. */ + "endDay": string; + /** The friendly name specified when creating the job */ + "friendlyName": string; + /** The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job\\\'s status manually. */ + "webhookUrl"?: string; + /** This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. */ + "webhookMethod"?: string; + /** The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job\\\'s status. */ + "email"?: string; +} + +/** + * Options to pass to each + */ +export interface ExportCustomJobListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ExportCustomJobInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ExportCustomJobListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ExportCustomJobListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface ExportCustomJobSolution { + resourceType: string; +} + +export interface ExportCustomJobListInstance { + _version: V1; + _solution: ExportCustomJobSolution; + _uri: string; + + + + /** + * Create a ExportCustomJobInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportCustomJobInstance + */ + create(params: ExportCustomJobListInstanceCreateOptions, callback?: (error: Error | null, item?: ExportCustomJobInstance) => any): Promise; + + /** + * Create a ExportCustomJobInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportCustomJobInstance with HTTP metadata + */ + createWithHttpInfo(params: ExportCustomJobListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ExportCustomJobInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExportCustomJobListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ExportCustomJobInstance, done: (err?: Error) => void) => void): void; + each(params: ExportCustomJobListInstanceEachOptions, callback?: (item: ExportCustomJobInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ExportCustomJobInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExportCustomJobListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ExportCustomJobInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ExportCustomJobListInstanceEachOptions, callback?: (item: ExportCustomJobInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ExportCustomJobInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ExportCustomJobPage) => any): Promise; + /** + * Retrieve a single target page of ExportCustomJobInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ExportCustomJobInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExportCustomJobListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ExportCustomJobInstance[]) => any): Promise; + list(params: ExportCustomJobListInstanceOptions, callback?: (error: Error | null, items: ExportCustomJobInstance[]) => any): Promise; + /** + * Lists ExportCustomJobInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExportCustomJobListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ExportCustomJobListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ExportCustomJobInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExportCustomJobListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ExportCustomJobPage) => any): Promise; + page(params: ExportCustomJobListInstancePageOptions, callback?: (error: Error | null, items: ExportCustomJobPage) => any): Promise; + /** + * Retrieve a single page of ExportCustomJobInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExportCustomJobListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ExportCustomJobListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExportCustomJobListInstance(version: V1, resourceType: string): ExportCustomJobListInstance { + if (!isValidPathParam(resourceType)) { + throw new Error('Parameter \'resourceType\' is not valid.'); + } + + const instance = {} as ExportCustomJobListInstance; + + instance._version = version; + instance._solution = { resourceType, }; + instance._uri = `/Exports/${resourceType}/Jobs`; + + instance.create = function create(params: ExportCustomJobListInstanceCreateOptions, callback?: (error: Error | null, items: ExportCustomJobInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["startDay"] === null || params["startDay"] === undefined) { + throw new Error('Required parameter "params[\'startDay\']" missing.'); + } + + if (params["endDay"] === null || params["endDay"] === undefined) { + throw new Error('Required parameter "params[\'endDay\']" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["StartDay"] = params["startDay"]; + + data["EndDay"] = params["endDay"]; + + data["FriendlyName"] = params["friendlyName"]; + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ExportCustomJobInstance(operationVersion, payload, instance._solution.resourceType)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ExportCustomJobListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["startDay"] === null || params["startDay"] === undefined) { + throw new Error('Required parameter "params[\'startDay\']" missing.'); + } + + if (params["endDay"] === null || params["endDay"] === undefined) { + throw new Error('Required parameter "params[\'endDay\']" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["StartDay"] = params["startDay"]; + + data["EndDay"] = params["endDay"]; + + data["FriendlyName"] = params["friendlyName"]; + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ExportCustomJobInstance(operationVersion, response.body, instance._solution.resourceType) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ExportCustomJobListInstancePageOptions | ((error: Error | null, items: ExportCustomJobPage) => any), callback?: (error: Error | null, items: ExportCustomJobPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ExportCustomJobPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ExportCustomJobPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ExportCustomJobPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ExportCustomJobListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ExportCustomJobPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ExportCustomJobPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ExportCustomJobPayload extends TwilioResponsePayload { + jobs: ExportCustomJobResource[]; +} + +interface ExportCustomJobResource { + friendly_name: string; + resource_type: string; + start_day: string; + end_day: string; + webhook_url: string; + webhook_method: string; + email: string; + job_sid: string; + details: Array; + job_queue_position: string; + estimated_completion_time: string; +} + +export class ExportCustomJobInstance { + + constructor(protected _version: V1, payload: ExportCustomJobResource, resourceType: string) { + + this.friendlyName = (payload.friendly_name); + this.resourceType = (payload.resource_type); + this.startDay = (payload.start_day); + this.endDay = (payload.end_day); + this.webhookUrl = (payload.webhook_url); + this.webhookMethod = (payload.webhook_method); + this.email = (payload.email); + this.jobSid = (payload.job_sid); + this.details = (payload.details); + this.jobQueuePosition = (payload.job_queue_position); + this.estimatedCompletionTime = (payload.estimated_completion_time); + + } + + /** + * The friendly name specified when creating the job + */ + friendlyName: string; + /** + * The type of communication – Messages, Calls, Conferences, and Participants + */ + resourceType: string; + /** + * The start day for the custom export specified when creating the job + */ + startDay: string; + /** + * The end day for the export specified when creating the job + */ + endDay: string; + /** + * The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. + */ + webhookUrl: string; + /** + * This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + */ + webhookMethod: string; + /** + * The optional email to send the completion notification to + */ + email: string; + /** + * The unique job_sid returned when the custom export was created + */ + jobSid: string; + /** + * The details of a job which is an object that contains an array of status grouped by `status` state. Each `status` object has a `status` string, a count which is the number of days in that `status`, and list of days in that `status`. The day strings are in the format yyyy-MM-dd. As an example, a currently running job may have a status object for COMPLETED and a `status` object for SUBMITTED each with its own count and list of days. + */ + details: Array; + /** + * This is the job position from the 1st in line. Your queue position will never increase. As jobs ahead of yours in the queue are processed, the queue position number will decrease + */ + jobQueuePosition: string; + /** + * this is the time estimated until your job is complete. This is calculated each time you request the job list. The time is calculated based on the current rate of job completion (which may vary) and your job queue position + */ + estimatedCompletionTime: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + friendlyName: this.friendlyName, + resourceType: this.resourceType, + startDay: this.startDay, + endDay: this.endDay, + webhookUrl: this.webhookUrl, + webhookMethod: this.webhookMethod, + email: this.email, + jobSid: this.jobSid, + details: this.details, + jobQueuePosition: this.jobQueuePosition, + estimatedCompletionTime: this.estimatedCompletionTime, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class ExportCustomJobPage extends Page { +/** +* Initialize the ExportCustomJobPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ExportCustomJobSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ExportCustomJobInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ExportCustomJobResource): ExportCustomJobInstance { + + return new ExportCustomJobInstance( + this._version, + payload, + this._solution.resourceType, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/bulkexports/v1/exportConfiguration.ts b/rest/bulkexports/v1/exportConfiguration.ts new file mode 100644 index 000000000..5007c9976 --- /dev/null +++ b/rest/bulkexports/v1/exportConfiguration.ts @@ -0,0 +1,435 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Bulkexports + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a ExportConfigurationInstance + */ +export interface ExportConfigurationContextUpdateOptions { + /** If true, Twilio will automatically generate every day\\\'s file when the day is over. */ + "enabled"?: boolean; + /** Stores the URL destination for the method specified in webhook_method. */ + "webhookUrl"?: string; + /** Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url */ + "webhookMethod"?: string; +} + +export interface ExportConfigurationContext { + + /** + * Fetch a ExportConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ExportConfigurationInstance) => any): Promise + + /** + * Fetch a ExportConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ExportConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance + */ + update(callback?: (error: Error | null, item?: ExportConfigurationInstance) => any): Promise; + /** + * Update a ExportConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance + */ + update(params: ExportConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ExportConfigurationInstance) => any): Promise; + + /** + * Update a ExportConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ExportConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ExportConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ExportConfigurationContextSolution { + "resourceType": string; +} + +export class ExportConfigurationContextImpl implements ExportConfigurationContext { + protected _solution: ExportConfigurationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, resourceType: string) { + if (!isValidPathParam(resourceType)) { + throw new Error('Parameter \'resourceType\' is not valid.'); + } + + this._solution = { resourceType, }; + this._uri = `/Exports/${resourceType}/Configuration`; + } + + fetch(callback?: (error: Error | null, item?: ExportConfigurationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ExportConfigurationInstance(operationVersion, payload, instance._solution.resourceType)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ExportConfigurationInstance(operationVersion, response.body, instance._solution.resourceType) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ExportConfigurationContextUpdateOptions | ((error: Error | null, item?: ExportConfigurationInstance) => any),callback?: (error: Error | null, item?: ExportConfigurationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ExportConfigurationInstance(operationVersion, payload, instance._solution.resourceType)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ExportConfigurationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ExportConfigurationInstance(operationVersion, response.body, instance._solution.resourceType) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ExportConfigurationPayload extends ExportConfigurationResource {} + +interface ExportConfigurationResource { + enabled: boolean; + webhook_url: string; + webhook_method: string; + resource_type: string; + url: string; +} + +export class ExportConfigurationInstance { + protected _solution: ExportConfigurationContextSolution; + protected _context?: ExportConfigurationContext; + + constructor(protected _version: V1, payload: ExportConfigurationResource, resourceType?: string) { + + this.enabled = (payload.enabled); + this.webhookUrl = (payload.webhook_url); + this.webhookMethod = (payload.webhook_method); + this.resourceType = (payload.resource_type); + this.url = (payload.url); + + this._solution = { resourceType: resourceType, }; + } + + /** + * If true, Twilio will automatically generate every day\'s file when the day is over. + */ + enabled: boolean; + /** + * Stores the URL destination for the method specified in webhook_method. + */ + webhookUrl: string; + /** + * Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + */ + webhookMethod: string; + /** + * The type of communication – Messages, Calls, Conferences, and Participants + */ + resourceType: string; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): ExportConfigurationContext { + this._context = this._context || new ExportConfigurationContextImpl(this._version, this._solution.resourceType); + return this._context; + } + + /** + * Fetch a ExportConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ExportConfigurationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ExportConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ExportConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance + */ + update(callback?: (error: Error | null, item?: ExportConfigurationInstance) => any): Promise; + /** + * Update a ExportConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance + */ + update(params: ExportConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ExportConfigurationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ExportConfigurationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ExportConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ExportConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExportConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ExportConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + enabled: this.enabled, + webhookUrl: this.webhookUrl, + webhookMethod: this.webhookMethod, + resourceType: this.resourceType, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ExportConfigurationSolution { +} + +export interface ExportConfigurationListInstance { + _version: V1; + _solution: ExportConfigurationSolution; + _uri: string; + + (resourceType: string, ): ExportConfigurationContext; + get(resourceType: string, ): ExportConfigurationContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExportConfigurationListInstance(version: V1): ExportConfigurationListInstance { + const instance = ((resourceType, ) => instance.get(resourceType, )) as ExportConfigurationListInstance; + + instance.get = function get(resourceType, ): ExportConfigurationContext { + return new ExportConfigurationContextImpl(version, resourceType); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/bulkexports/v1/job.ts b/rest/bulkexports/v1/job.ts new file mode 100644 index 000000000..35e039a27 --- /dev/null +++ b/rest/bulkexports/v1/job.ts @@ -0,0 +1,386 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Bulkexports + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface JobContext { + + /** + * Remove a JobInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a JobInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a JobInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed JobInstance + */ + fetch(callback?: (error: Error | null, item?: JobInstance) => any): Promise + + /** + * Fetch a JobInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed JobInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface JobContextSolution { + "jobSid": string; +} + +export class JobContextImpl implements JobContext { + protected _solution: JobContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, jobSid: string) { + if (!isValidPathParam(jobSid)) { + throw new Error('Parameter \'jobSid\' is not valid.'); + } + + this._solution = { jobSid, }; + this._uri = `/Exports/Jobs/${jobSid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: JobInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new JobInstance(operationVersion, payload, instance._solution.jobSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new JobInstance(operationVersion, response.body, instance._solution.jobSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface JobPayload extends JobResource {} + +interface JobResource { + resource_type: string; + friendly_name: string; + details: Array; + start_day: string; + end_day: string; + job_sid: string; + webhook_url: string; + webhook_method: string; + email: string; + url: string; + job_queue_position: string; + estimated_completion_time: string; +} + +export class JobInstance { + protected _solution: JobContextSolution; + protected _context?: JobContext; + + constructor(protected _version: V1, payload: JobResource, jobSid?: string) { + + this.resourceType = (payload.resource_type); + this.friendlyName = (payload.friendly_name); + this.details = (payload.details); + this.startDay = (payload.start_day); + this.endDay = (payload.end_day); + this.jobSid = (payload.job_sid); + this.webhookUrl = (payload.webhook_url); + this.webhookMethod = (payload.webhook_method); + this.email = (payload.email); + this.url = (payload.url); + this.jobQueuePosition = (payload.job_queue_position); + this.estimatedCompletionTime = (payload.estimated_completion_time); + + this._solution = { jobSid: jobSid, }; + } + + /** + * The type of communication – Messages, Calls, Conferences, and Participants + */ + resourceType: string; + /** + * The friendly name specified when creating the job + */ + friendlyName: string; + /** + * The details of a job which is an object that contains an array of status grouped by `status` state. Each `status` object has a `status` string, a count which is the number of days in that `status`, and list of days in that `status`. The day strings are in the format yyyy-MM-dd. As an example, a currently running job may have a status object for COMPLETED and a `status` object for SUBMITTED each with its own count and list of days. + */ + details: Array; + /** + * The start time for the export specified when creating the job + */ + startDay: string; + /** + * The end time for the export specified when creating the job + */ + endDay: string; + /** + * The job_sid returned when the export was created + */ + jobSid: string; + /** + * The optional webhook url called on completion + */ + webhookUrl: string; + /** + * This is the method used to call the webhook + */ + webhookMethod: string; + /** + * The optional email to send the completion notification to + */ + email: string; + url: string; + /** + * This is the job position from the 1st in line. Your queue position will never increase. As jobs ahead of yours in the queue are processed, the queue position number will decrease + */ + jobQueuePosition: string; + /** + * this is the time estimated until your job is complete. This is calculated each time you request the job list. The time is calculated based on the current rate of job completion (which may vary) and your job queue position + */ + estimatedCompletionTime: string; + + private get _proxy(): JobContext { + this._context = this._context || new JobContextImpl(this._version, this._solution.jobSid); + return this._context; + } + + /** + * Remove a JobInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a JobInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a JobInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed JobInstance + */ + fetch(callback?: (error: Error | null, item?: JobInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a JobInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed JobInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + resourceType: this.resourceType, + friendlyName: this.friendlyName, + details: this.details, + startDay: this.startDay, + endDay: this.endDay, + jobSid: this.jobSid, + webhookUrl: this.webhookUrl, + webhookMethod: this.webhookMethod, + email: this.email, + url: this.url, + jobQueuePosition: this.jobQueuePosition, + estimatedCompletionTime: this.estimatedCompletionTime, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface JobSolution { +} + +export interface JobListInstance { + _version: V1; + _solution: JobSolution; + _uri: string; + + (jobSid: string, ): JobContext; + get(jobSid: string, ): JobContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function JobListInstance(version: V1): JobListInstance { + const instance = ((jobSid, ) => instance.get(jobSid, )) as JobListInstance; + + instance.get = function get(jobSid, ): JobContext { + return new JobContextImpl(version, jobSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/chat/V1.ts b/rest/chat/V1.ts new file mode 100644 index 000000000..d888d598f --- /dev/null +++ b/rest/chat/V1.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import ChatBase from "../ChatBase"; +import Version from "../../base/Version"; +import { CredentialListInstance } from "./v1/credential"; +import { ServiceListInstance } from "./v1/service"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Chat + * + * @param domain - The Twilio (Twilio.Chat) domain + */ + constructor(domain: ChatBase) { + super(domain, "v1"); + } + + /** credentials - { Twilio.Chat.V1.CredentialListInstance } resource */ + protected _credentials?: CredentialListInstance; + /** services - { Twilio.Chat.V1.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + + /** Getter for credentials resource */ + get credentials(): CredentialListInstance { + this._credentials = this._credentials || CredentialListInstance(this); + return this._credentials; + } + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + +} diff --git a/rest/chat/V2.ts b/rest/chat/V2.ts new file mode 100644 index 000000000..049a3002b --- /dev/null +++ b/rest/chat/V2.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import ChatBase from "../ChatBase"; +import Version from "../../base/Version"; +import { CredentialListInstance } from "./v2/credential"; +import { ServiceListInstance } from "./v2/service"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Chat + * + * @param domain - The Twilio (Twilio.Chat) domain + */ + constructor(domain: ChatBase) { + super(domain, "v2"); + } + + /** credentials - { Twilio.Chat.V2.CredentialListInstance } resource */ + protected _credentials?: CredentialListInstance; + /** services - { Twilio.Chat.V2.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + + /** Getter for credentials resource */ + get credentials(): CredentialListInstance { + this._credentials = this._credentials || CredentialListInstance(this); + return this._credentials; + } + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + +} diff --git a/rest/chat/V3.ts b/rest/chat/V3.ts new file mode 100644 index 000000000..88149d756 --- /dev/null +++ b/rest/chat/V3.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import ChatBase from "../ChatBase"; +import Version from "../../base/Version"; +import { ChannelListInstance } from "./v3/channel"; + +export default class V3 extends Version { + /** + * Initialize the V3 version of Chat + * + * @param domain - The Twilio (Twilio.Chat) domain + */ + constructor(domain: ChatBase) { + super(domain, "v3"); + } + + /** channels - { Twilio.Chat.V3.ChannelListInstance } resource */ + protected _channels?: ChannelListInstance; + + /** Getter for channels resource */ + get channels(): ChannelListInstance { + this._channels = this._channels || ChannelListInstance(this); + return this._channels; + } + +} diff --git a/rest/chat/v1/credential.ts b/rest/chat/v1/credential.ts new file mode 100644 index 000000000..6ff488cbc --- /dev/null +++ b/rest/chat/v1/credential.ts @@ -0,0 +1,971 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The type of push-notification service the credential is for. Can be: `gcm`, `fcm`, or `apn`. + */ +export type CredentialPushService = 'gcm'|'apn'|'fcm'; + + + + +/** + * Options to pass to update a CredentialInstance + */ +export interface CredentialContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` */ + "certificate"?: string; + /** [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` */ + "privateKey"?: string; + /** [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. */ + "sandbox"?: boolean; + /** [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. */ + "apiKey"?: string; + /** [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. */ + "secret"?: string; +} + +/** + * Options to pass to create a CredentialInstance + */ +export interface CredentialListInstanceCreateOptions { + /** */ + "type": CredentialPushService; + /** A descriptive string that you create to describe the new resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` */ + "certificate"?: string; + /** [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` */ + "privateKey"?: string; + /** [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. */ + "sandbox"?: boolean; + /** [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. */ + "apiKey"?: string; + /** [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. */ + "secret"?: string; +} + +/** + * Options to pass to each + */ +export interface CredentialListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CredentialInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CredentialListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CredentialListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CredentialContext { + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CredentialContextSolution { + "sid": string; +} + +export class CredentialContextImpl implements CredentialContext { + protected _solution: CredentialContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Credentials/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: CredentialInstance) => any),callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CredentialPayload extends TwilioResponsePayload { + credentials: CredentialResource[]; +} + +interface CredentialResource { + sid: string; + account_sid: string; + friendly_name: string; + type: CredentialPushService; + sandbox: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CredentialInstance { + protected _solution: CredentialContextSolution; + protected _context?: CredentialContext; + + constructor(protected _version: V1, payload: CredentialResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.sandbox = (payload.sandbox); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Credential resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Credential resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + type: CredentialPushService; + /** + * [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + */ + sandbox: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Credential resource. + */ + url: string; + + private get _proxy(): CredentialContext { + this._context = this._context || new CredentialContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + type: this.type, + sandbox: this.sandbox, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CredentialSolution { +} + +export interface CredentialListInstance { + _version: V1; + _solution: CredentialSolution; + _uri: string; + + (sid: string, ): CredentialContext; + get(sid: string, ): CredentialContext; + + + + + + + + + /** + * Create a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Create a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CredentialInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + each(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CredentialInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single target page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CredentialInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + list(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + /** + * Lists CredentialInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CredentialPage) => any): Promise; + page(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CredentialListInstance(version: V1): CredentialListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CredentialListInstance; + + instance.get = function get(sid, ): CredentialContext { + return new CredentialContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Credentials`; + + instance.create = function create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: CredentialInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CredentialListInstancePageOptions | ((error: Error | null, items: CredentialPage) => any), callback?: (error: Error | null, items: CredentialPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CredentialPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CredentialPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CredentialListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CredentialPage extends Page { +/** +* Initialize the CredentialPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: CredentialSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CredentialInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CredentialResource): CredentialInstance { + + return new CredentialInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v1/service.ts b/rest/chat/v1/service.ts new file mode 100644 index 000000000..ba2e79110 --- /dev/null +++ b/rest/chat/v1/service.ts @@ -0,0 +1,1357 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ChannelListInstance } from "./service/channel"; +import { RoleListInstance } from "./service/role"; +import { UserListInstance } from "./service/user"; + + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. */ + "defaultServiceRoleSid"?: string; + /** The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. */ + "defaultChannelRoleSid"?: string; + /** The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. */ + "defaultChannelCreatorRoleSid"?: string; + /** Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. */ + "readStatusEnabled"?: boolean; + /** Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. */ + "reachabilityEnabled"?: boolean; + /** How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. */ + "typingIndicatorTimeout"?: number; + /** DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. */ + "consumptionReportInterval"?: number; + /** Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. */ + "notifications.newMessage.enabled"?: boolean; + /** The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. */ + "notifications.newMessage.template"?: string; + /** Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. */ + "notifications.addedToChannel.enabled"?: boolean; + /** The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. */ + "notifications.addedToChannel.template"?: string; + /** Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. */ + "notifications.removedFromChannel.enabled"?: boolean; + /** The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. */ + "notifications.removedFromChannel.template"?: string; + /** Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. */ + "notifications.invitedToChannel.enabled"?: boolean; + /** The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. */ + "notifications.invitedToChannel.template"?: string; + /** The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. */ + "preWebhookUrl"?: string; + /** The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. */ + "postWebhookUrl"?: string; + /** The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. */ + "webhookMethod"?: string; + /** The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. */ + "webhookFilters"?: Array; + /** The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. */ + "webhooks.onMessageSend.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_message_send.url`. */ + "webhooks.onMessageSend.method"?: string; + /** The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. */ + "webhooks.onMessageUpdate.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_message_update.url`. */ + "webhooks.onMessageUpdate.method"?: string; + /** The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. */ + "webhooks.onMessageRemove.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_message_remove.url`. */ + "webhooks.onMessageRemove.method"?: string; + /** The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. */ + "webhooks.onChannelAdd.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_channel_add.url`. */ + "webhooks.onChannelAdd.method"?: string; + /** The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. */ + "webhooks.onChannelDestroy.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. */ + "webhooks.onChannelDestroy.method"?: string; + /** The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. */ + "webhooks.onChannelUpdate.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_channel_update.url`. */ + "webhooks.onChannelUpdate.method"?: string; + /** The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. */ + "webhooks.onMemberAdd.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_member_add.url`. */ + "webhooks.onMemberAdd.method"?: string; + /** The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. */ + "webhooks.onMemberRemove.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_member_remove.url`. */ + "webhooks.onMemberRemove.method"?: string; + /** The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. */ + "webhooks.onMessageSent.url"?: string; + /** The URL of the webhook to call in response to the `on_message_sent` event`. */ + "webhooks.onMessageSent.method"?: string; + /** The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. */ + "webhooks.onMessageUpdated.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_message_updated.url`. */ + "webhooks.onMessageUpdated.method"?: string; + /** The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. */ + "webhooks.onMessageRemoved.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_message_removed.url`. */ + "webhooks.onMessageRemoved.method"?: string; + /** The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. */ + "webhooks.onChannelAdded.url"?: string; + /** The URL of the webhook to call in response to the `on_channel_added` event`. */ + "webhooks.onChannelAdded.method"?: string; + /** The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. */ + "webhooks.onChannelDestroyed.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. */ + "webhooks.onChannelDestroyed.method"?: string; + /** The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. */ + "webhooks.onChannelUpdated.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_channel_updated.url`. */ + "webhooks.onChannelUpdated.method"?: string; + /** The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. */ + "webhooks.onMemberAdded.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_channel_updated.url`. */ + "webhooks.onMemberAdded.method"?: string; + /** The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. */ + "webhooks.onMemberRemoved.url"?: string; + /** The HTTP method to use when calling the `webhooks.on_member_removed.url`. */ + "webhooks.onMemberRemoved.method"?: string; + /** The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. */ + "limits.channelMembers"?: number; + /** The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. */ + "limits.userChannels"?: number; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName": string; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + channels: ChannelListInstance; + roles: RoleListInstance; + users: UserListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _channels?: ChannelListInstance; + protected _roles?: RoleListInstance; + protected _users?: UserListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get channels(): ChannelListInstance { + this._channels = this._channels || ChannelListInstance(this._version, this._solution.sid); + return this._channels; + } + + get roles(): RoleListInstance { + this._roles = this._roles || RoleListInstance(this._version, this._solution.sid); + return this._roles; + } + + get users(): UserListInstance { + this._users = this._users || UserListInstance(this._version, this._solution.sid); + return this._users; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["defaultServiceRoleSid"] !== undefined) + data["DefaultServiceRoleSid"] = params["defaultServiceRoleSid"]; + if (params["defaultChannelRoleSid"] !== undefined) + data["DefaultChannelRoleSid"] = params["defaultChannelRoleSid"]; + if (params["defaultChannelCreatorRoleSid"] !== undefined) + data["DefaultChannelCreatorRoleSid"] = params["defaultChannelCreatorRoleSid"]; + if (params["readStatusEnabled"] !== undefined) + data["ReadStatusEnabled"] = serialize.bool(params["readStatusEnabled"]); + if (params["reachabilityEnabled"] !== undefined) + data["ReachabilityEnabled"] = serialize.bool(params["reachabilityEnabled"]); + if (params["typingIndicatorTimeout"] !== undefined) + data["TypingIndicatorTimeout"] = params["typingIndicatorTimeout"]; + if (params["consumptionReportInterval"] !== undefined) + data["ConsumptionReportInterval"] = params["consumptionReportInterval"]; + if (params["notifications.newMessage.enabled"] !== undefined) + data["Notifications.NewMessage.Enabled"] = serialize.bool(params["notifications.newMessage.enabled"]); + if (params["notifications.newMessage.template"] !== undefined) + data["Notifications.NewMessage.Template"] = params["notifications.newMessage.template"]; + if (params["notifications.addedToChannel.enabled"] !== undefined) + data["Notifications.AddedToChannel.Enabled"] = serialize.bool(params["notifications.addedToChannel.enabled"]); + if (params["notifications.addedToChannel.template"] !== undefined) + data["Notifications.AddedToChannel.Template"] = params["notifications.addedToChannel.template"]; + if (params["notifications.removedFromChannel.enabled"] !== undefined) + data["Notifications.RemovedFromChannel.Enabled"] = serialize.bool(params["notifications.removedFromChannel.enabled"]); + if (params["notifications.removedFromChannel.template"] !== undefined) + data["Notifications.RemovedFromChannel.Template"] = params["notifications.removedFromChannel.template"]; + if (params["notifications.invitedToChannel.enabled"] !== undefined) + data["Notifications.InvitedToChannel.Enabled"] = serialize.bool(params["notifications.invitedToChannel.enabled"]); + if (params["notifications.invitedToChannel.template"] !== undefined) + data["Notifications.InvitedToChannel.Template"] = params["notifications.invitedToChannel.template"]; + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + if (params["webhookFilters"] !== undefined) + data["WebhookFilters"] = serialize.map(params["webhookFilters"], (e: string) => (e)); + if (params["webhooks.onMessageSend.url"] !== undefined) + data["Webhooks.OnMessageSend.Url"] = params["webhooks.onMessageSend.url"]; + if (params["webhooks.onMessageSend.method"] !== undefined) + data["Webhooks.OnMessageSend.Method"] = params["webhooks.onMessageSend.method"]; + if (params["webhooks.onMessageUpdate.url"] !== undefined) + data["Webhooks.OnMessageUpdate.Url"] = params["webhooks.onMessageUpdate.url"]; + if (params["webhooks.onMessageUpdate.method"] !== undefined) + data["Webhooks.OnMessageUpdate.Method"] = params["webhooks.onMessageUpdate.method"]; + if (params["webhooks.onMessageRemove.url"] !== undefined) + data["Webhooks.OnMessageRemove.Url"] = params["webhooks.onMessageRemove.url"]; + if (params["webhooks.onMessageRemove.method"] !== undefined) + data["Webhooks.OnMessageRemove.Method"] = params["webhooks.onMessageRemove.method"]; + if (params["webhooks.onChannelAdd.url"] !== undefined) + data["Webhooks.OnChannelAdd.Url"] = params["webhooks.onChannelAdd.url"]; + if (params["webhooks.onChannelAdd.method"] !== undefined) + data["Webhooks.OnChannelAdd.Method"] = params["webhooks.onChannelAdd.method"]; + if (params["webhooks.onChannelDestroy.url"] !== undefined) + data["Webhooks.OnChannelDestroy.Url"] = params["webhooks.onChannelDestroy.url"]; + if (params["webhooks.onChannelDestroy.method"] !== undefined) + data["Webhooks.OnChannelDestroy.Method"] = params["webhooks.onChannelDestroy.method"]; + if (params["webhooks.onChannelUpdate.url"] !== undefined) + data["Webhooks.OnChannelUpdate.Url"] = params["webhooks.onChannelUpdate.url"]; + if (params["webhooks.onChannelUpdate.method"] !== undefined) + data["Webhooks.OnChannelUpdate.Method"] = params["webhooks.onChannelUpdate.method"]; + if (params["webhooks.onMemberAdd.url"] !== undefined) + data["Webhooks.OnMemberAdd.Url"] = params["webhooks.onMemberAdd.url"]; + if (params["webhooks.onMemberAdd.method"] !== undefined) + data["Webhooks.OnMemberAdd.Method"] = params["webhooks.onMemberAdd.method"]; + if (params["webhooks.onMemberRemove.url"] !== undefined) + data["Webhooks.OnMemberRemove.Url"] = params["webhooks.onMemberRemove.url"]; + if (params["webhooks.onMemberRemove.method"] !== undefined) + data["Webhooks.OnMemberRemove.Method"] = params["webhooks.onMemberRemove.method"]; + if (params["webhooks.onMessageSent.url"] !== undefined) + data["Webhooks.OnMessageSent.Url"] = params["webhooks.onMessageSent.url"]; + if (params["webhooks.onMessageSent.method"] !== undefined) + data["Webhooks.OnMessageSent.Method"] = params["webhooks.onMessageSent.method"]; + if (params["webhooks.onMessageUpdated.url"] !== undefined) + data["Webhooks.OnMessageUpdated.Url"] = params["webhooks.onMessageUpdated.url"]; + if (params["webhooks.onMessageUpdated.method"] !== undefined) + data["Webhooks.OnMessageUpdated.Method"] = params["webhooks.onMessageUpdated.method"]; + if (params["webhooks.onMessageRemoved.url"] !== undefined) + data["Webhooks.OnMessageRemoved.Url"] = params["webhooks.onMessageRemoved.url"]; + if (params["webhooks.onMessageRemoved.method"] !== undefined) + data["Webhooks.OnMessageRemoved.Method"] = params["webhooks.onMessageRemoved.method"]; + if (params["webhooks.onChannelAdded.url"] !== undefined) + data["Webhooks.OnChannelAdded.Url"] = params["webhooks.onChannelAdded.url"]; + if (params["webhooks.onChannelAdded.method"] !== undefined) + data["Webhooks.OnChannelAdded.Method"] = params["webhooks.onChannelAdded.method"]; + if (params["webhooks.onChannelDestroyed.url"] !== undefined) + data["Webhooks.OnChannelDestroyed.Url"] = params["webhooks.onChannelDestroyed.url"]; + if (params["webhooks.onChannelDestroyed.method"] !== undefined) + data["Webhooks.OnChannelDestroyed.Method"] = params["webhooks.onChannelDestroyed.method"]; + if (params["webhooks.onChannelUpdated.url"] !== undefined) + data["Webhooks.OnChannelUpdated.Url"] = params["webhooks.onChannelUpdated.url"]; + if (params["webhooks.onChannelUpdated.method"] !== undefined) + data["Webhooks.OnChannelUpdated.Method"] = params["webhooks.onChannelUpdated.method"]; + if (params["webhooks.onMemberAdded.url"] !== undefined) + data["Webhooks.OnMemberAdded.Url"] = params["webhooks.onMemberAdded.url"]; + if (params["webhooks.onMemberAdded.method"] !== undefined) + data["Webhooks.OnMemberAdded.Method"] = params["webhooks.onMemberAdded.method"]; + if (params["webhooks.onMemberRemoved.url"] !== undefined) + data["Webhooks.OnMemberRemoved.Url"] = params["webhooks.onMemberRemoved.url"]; + if (params["webhooks.onMemberRemoved.method"] !== undefined) + data["Webhooks.OnMemberRemoved.Method"] = params["webhooks.onMemberRemoved.method"]; + if (params["limits.channelMembers"] !== undefined) + data["Limits.ChannelMembers"] = params["limits.channelMembers"]; + if (params["limits.userChannels"] !== undefined) + data["Limits.UserChannels"] = params["limits.userChannels"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["defaultServiceRoleSid"] !== undefined) + data["DefaultServiceRoleSid"] = params["defaultServiceRoleSid"]; + if (params["defaultChannelRoleSid"] !== undefined) + data["DefaultChannelRoleSid"] = params["defaultChannelRoleSid"]; + if (params["defaultChannelCreatorRoleSid"] !== undefined) + data["DefaultChannelCreatorRoleSid"] = params["defaultChannelCreatorRoleSid"]; + if (params["readStatusEnabled"] !== undefined) + data["ReadStatusEnabled"] = serialize.bool(params["readStatusEnabled"]); + if (params["reachabilityEnabled"] !== undefined) + data["ReachabilityEnabled"] = serialize.bool(params["reachabilityEnabled"]); + if (params["typingIndicatorTimeout"] !== undefined) + data["TypingIndicatorTimeout"] = params["typingIndicatorTimeout"]; + if (params["consumptionReportInterval"] !== undefined) + data["ConsumptionReportInterval"] = params["consumptionReportInterval"]; + if (params["notifications.newMessage.enabled"] !== undefined) + data["Notifications.NewMessage.Enabled"] = serialize.bool(params["notifications.newMessage.enabled"]); + if (params["notifications.newMessage.template"] !== undefined) + data["Notifications.NewMessage.Template"] = params["notifications.newMessage.template"]; + if (params["notifications.addedToChannel.enabled"] !== undefined) + data["Notifications.AddedToChannel.Enabled"] = serialize.bool(params["notifications.addedToChannel.enabled"]); + if (params["notifications.addedToChannel.template"] !== undefined) + data["Notifications.AddedToChannel.Template"] = params["notifications.addedToChannel.template"]; + if (params["notifications.removedFromChannel.enabled"] !== undefined) + data["Notifications.RemovedFromChannel.Enabled"] = serialize.bool(params["notifications.removedFromChannel.enabled"]); + if (params["notifications.removedFromChannel.template"] !== undefined) + data["Notifications.RemovedFromChannel.Template"] = params["notifications.removedFromChannel.template"]; + if (params["notifications.invitedToChannel.enabled"] !== undefined) + data["Notifications.InvitedToChannel.Enabled"] = serialize.bool(params["notifications.invitedToChannel.enabled"]); + if (params["notifications.invitedToChannel.template"] !== undefined) + data["Notifications.InvitedToChannel.Template"] = params["notifications.invitedToChannel.template"]; + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + if (params["webhookFilters"] !== undefined) + data["WebhookFilters"] = serialize.map(params["webhookFilters"], (e: string) => (e)); + if (params["webhooks.onMessageSend.url"] !== undefined) + data["Webhooks.OnMessageSend.Url"] = params["webhooks.onMessageSend.url"]; + if (params["webhooks.onMessageSend.method"] !== undefined) + data["Webhooks.OnMessageSend.Method"] = params["webhooks.onMessageSend.method"]; + if (params["webhooks.onMessageUpdate.url"] !== undefined) + data["Webhooks.OnMessageUpdate.Url"] = params["webhooks.onMessageUpdate.url"]; + if (params["webhooks.onMessageUpdate.method"] !== undefined) + data["Webhooks.OnMessageUpdate.Method"] = params["webhooks.onMessageUpdate.method"]; + if (params["webhooks.onMessageRemove.url"] !== undefined) + data["Webhooks.OnMessageRemove.Url"] = params["webhooks.onMessageRemove.url"]; + if (params["webhooks.onMessageRemove.method"] !== undefined) + data["Webhooks.OnMessageRemove.Method"] = params["webhooks.onMessageRemove.method"]; + if (params["webhooks.onChannelAdd.url"] !== undefined) + data["Webhooks.OnChannelAdd.Url"] = params["webhooks.onChannelAdd.url"]; + if (params["webhooks.onChannelAdd.method"] !== undefined) + data["Webhooks.OnChannelAdd.Method"] = params["webhooks.onChannelAdd.method"]; + if (params["webhooks.onChannelDestroy.url"] !== undefined) + data["Webhooks.OnChannelDestroy.Url"] = params["webhooks.onChannelDestroy.url"]; + if (params["webhooks.onChannelDestroy.method"] !== undefined) + data["Webhooks.OnChannelDestroy.Method"] = params["webhooks.onChannelDestroy.method"]; + if (params["webhooks.onChannelUpdate.url"] !== undefined) + data["Webhooks.OnChannelUpdate.Url"] = params["webhooks.onChannelUpdate.url"]; + if (params["webhooks.onChannelUpdate.method"] !== undefined) + data["Webhooks.OnChannelUpdate.Method"] = params["webhooks.onChannelUpdate.method"]; + if (params["webhooks.onMemberAdd.url"] !== undefined) + data["Webhooks.OnMemberAdd.Url"] = params["webhooks.onMemberAdd.url"]; + if (params["webhooks.onMemberAdd.method"] !== undefined) + data["Webhooks.OnMemberAdd.Method"] = params["webhooks.onMemberAdd.method"]; + if (params["webhooks.onMemberRemove.url"] !== undefined) + data["Webhooks.OnMemberRemove.Url"] = params["webhooks.onMemberRemove.url"]; + if (params["webhooks.onMemberRemove.method"] !== undefined) + data["Webhooks.OnMemberRemove.Method"] = params["webhooks.onMemberRemove.method"]; + if (params["webhooks.onMessageSent.url"] !== undefined) + data["Webhooks.OnMessageSent.Url"] = params["webhooks.onMessageSent.url"]; + if (params["webhooks.onMessageSent.method"] !== undefined) + data["Webhooks.OnMessageSent.Method"] = params["webhooks.onMessageSent.method"]; + if (params["webhooks.onMessageUpdated.url"] !== undefined) + data["Webhooks.OnMessageUpdated.Url"] = params["webhooks.onMessageUpdated.url"]; + if (params["webhooks.onMessageUpdated.method"] !== undefined) + data["Webhooks.OnMessageUpdated.Method"] = params["webhooks.onMessageUpdated.method"]; + if (params["webhooks.onMessageRemoved.url"] !== undefined) + data["Webhooks.OnMessageRemoved.Url"] = params["webhooks.onMessageRemoved.url"]; + if (params["webhooks.onMessageRemoved.method"] !== undefined) + data["Webhooks.OnMessageRemoved.Method"] = params["webhooks.onMessageRemoved.method"]; + if (params["webhooks.onChannelAdded.url"] !== undefined) + data["Webhooks.OnChannelAdded.Url"] = params["webhooks.onChannelAdded.url"]; + if (params["webhooks.onChannelAdded.method"] !== undefined) + data["Webhooks.OnChannelAdded.Method"] = params["webhooks.onChannelAdded.method"]; + if (params["webhooks.onChannelDestroyed.url"] !== undefined) + data["Webhooks.OnChannelDestroyed.Url"] = params["webhooks.onChannelDestroyed.url"]; + if (params["webhooks.onChannelDestroyed.method"] !== undefined) + data["Webhooks.OnChannelDestroyed.Method"] = params["webhooks.onChannelDestroyed.method"]; + if (params["webhooks.onChannelUpdated.url"] !== undefined) + data["Webhooks.OnChannelUpdated.Url"] = params["webhooks.onChannelUpdated.url"]; + if (params["webhooks.onChannelUpdated.method"] !== undefined) + data["Webhooks.OnChannelUpdated.Method"] = params["webhooks.onChannelUpdated.method"]; + if (params["webhooks.onMemberAdded.url"] !== undefined) + data["Webhooks.OnMemberAdded.Url"] = params["webhooks.onMemberAdded.url"]; + if (params["webhooks.onMemberAdded.method"] !== undefined) + data["Webhooks.OnMemberAdded.Method"] = params["webhooks.onMemberAdded.method"]; + if (params["webhooks.onMemberRemoved.url"] !== undefined) + data["Webhooks.OnMemberRemoved.Url"] = params["webhooks.onMemberRemoved.url"]; + if (params["webhooks.onMemberRemoved.method"] !== undefined) + data["Webhooks.OnMemberRemoved.Method"] = params["webhooks.onMemberRemoved.method"]; + if (params["limits.channelMembers"] !== undefined) + data["Limits.ChannelMembers"] = params["limits.channelMembers"]; + if (params["limits.userChannels"] !== undefined) + data["Limits.UserChannels"] = params["limits.userChannels"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + sid: string; + account_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + default_service_role_sid: string; + default_channel_role_sid: string; + default_channel_creator_role_sid: string; + read_status_enabled: boolean; + reachability_enabled: boolean; + typing_indicator_timeout: number; + consumption_report_interval: number; + limits: any; + webhooks: any; + pre_webhook_url: string; + post_webhook_url: string; + webhook_method: string; + webhook_filters: Array; + notifications: any; + url: string; + links: Record; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V1, payload: ServiceResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.defaultServiceRoleSid = (payload.default_service_role_sid); + this.defaultChannelRoleSid = (payload.default_channel_role_sid); + this.defaultChannelCreatorRoleSid = (payload.default_channel_creator_role_sid); + this.readStatusEnabled = (payload.read_status_enabled); + this.reachabilityEnabled = (payload.reachability_enabled); + this.typingIndicatorTimeout = deserialize.integer(payload.typing_indicator_timeout); + this.consumptionReportInterval = deserialize.integer(payload.consumption_report_interval); + this.limits = (payload.limits); + this.webhooks = (payload.webhooks); + this.preWebhookUrl = (payload.pre_webhook_url); + this.postWebhookUrl = (payload.post_webhook_url); + this.webhookMethod = (payload.webhook_method); + this.webhookFilters = (payload.webhook_filters); + this.notifications = (payload.notifications); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Service resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Service resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + */ + defaultServiceRoleSid: string; + /** + * The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + */ + defaultChannelRoleSid: string; + /** + * The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + */ + defaultChannelCreatorRoleSid: string; + /** + * Whether the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature is enabled. The default is `true`. + */ + readStatusEnabled: boolean; + /** + * Whether the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) is enabled for this Service instance. The default is `false`. + */ + reachabilityEnabled: boolean; + /** + * How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + */ + typingIndicatorTimeout: number; + /** + * DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + */ + consumptionReportInterval: number; + /** + * An object that describes the limits of the service instance. The `limits` object contains `channel_members` to describe the members/channel limit and `user_channels` to describe the channels/user limit. `channel_members` can be 1,000 or less, with a default of 250. `user_channels` can be 1,000 or less, with a default value of 100. + */ + limits: any; + /** + * An object that contains information about the webhooks configured for this service. + */ + webhooks: any; + /** + * The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + */ + preWebhookUrl: string; + /** + * The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + */ + postWebhookUrl: string; + /** + * The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + */ + webhookMethod: string; + /** + * The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + */ + webhookFilters: Array; + /** + * The notification configuration for the Service instance. See [Push Notification Configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more information. + */ + notifications: any; + /** + * The absolute URL of the Service resource. + */ + url: string; + /** + * The absolute URLs of the Service\'s [Channels](https://www.twilio.com/docs/chat/api/channels), [Roles](https://www.twilio.com/docs/chat/api/roles), and [Users](https://www.twilio.com/docs/chat/api/users). + */ + links: Record; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the channels. + */ + channels(): ChannelListInstance { + return this._proxy.channels; + } + + /** + * Access the roles. + */ + roles(): RoleListInstance { + return this._proxy.roles; + } + + /** + * Access the users. + */ + users(): UserListInstance { + return this._proxy.users; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + defaultServiceRoleSid: this.defaultServiceRoleSid, + defaultChannelRoleSid: this.defaultChannelRoleSid, + defaultChannelCreatorRoleSid: this.defaultChannelCreatorRoleSid, + readStatusEnabled: this.readStatusEnabled, + reachabilityEnabled: this.reachabilityEnabled, + typingIndicatorTimeout: this.typingIndicatorTimeout, + consumptionReportInterval: this.consumptionReportInterval, + limits: this.limits, + webhooks: this.webhooks, + preWebhookUrl: this.preWebhookUrl, + postWebhookUrl: this.postWebhookUrl, + webhookMethod: this.webhookMethod, + webhookFilters: this.webhookFilters, + notifications: this.notifications, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V1; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V1): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ServiceInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v1/service/channel.ts b/rest/chat/v1/service/channel.ts new file mode 100644 index 000000000..90a1614b9 --- /dev/null +++ b/rest/chat/v1/service/channel.ts @@ -0,0 +1,1057 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { InviteListInstance } from "./channel/invite"; +import { MemberListInstance } from "./channel/member"; +import { MessageListInstance } from "./channel/message"; + + +/** + * The visibility of the channel. Can be: `public` or `private`. + */ +export type ChannelChannelType = 'public'|'private'; + + + + +/** + * Options to pass to update a ChannelInstance + */ +export interface ChannelContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\\\'s `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. */ + "uniqueName"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; +} + +/** + * Options to pass to create a ChannelInstance + */ +export interface ChannelListInstanceCreateOptions { + /** A descriptive string that you create to describe the new resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\\\'s `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. */ + "uniqueName"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; + /** */ + "type"?: ChannelChannelType; +} + +/** + * Options to pass to each + */ +export interface ChannelListInstanceEachOptions { + /** The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChannelListInstanceOptions { + /** The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChannelListInstancePageOptions { + /** The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ChannelContext { + invites: InviteListInstance; + members: MemberListInstance; + messages: MessageListInstance; + + /** + * Remove a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + + /** + * Fetch a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Update a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + /** + * Update a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ChannelContextSolution { + "serviceSid": string; + "sid": string; +} + +export class ChannelContextImpl implements ChannelContext { + protected _solution: ChannelContextSolution; + protected _uri: string; + + protected _invites?: InviteListInstance; + protected _members?: MemberListInstance; + protected _messages?: MessageListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${sid}`; + } + + get invites(): InviteListInstance { + this._invites = this._invites || InviteListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._invites; + } + + get members(): MemberListInstance { + this._members = this._members || MemberListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._members; + } + + get messages(): MessageListInstance { + this._messages = this._messages || MessageListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._messages; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ChannelContextUpdateOptions | ((error: Error | null, item?: ChannelInstance) => any),callback?: (error: Error | null, item?: ChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ChannelContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ChannelPayload extends TwilioResponsePayload { + channels: ChannelResource[]; +} + +interface ChannelResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + unique_name: string; + attributes: string; + type: ChannelChannelType; + date_created: Date; + date_updated: Date; + created_by: string; + members_count: number; + messages_count: number; + url: string; + links: Record; +} + +export class ChannelInstance { + protected _solution: ChannelContextSolution; + protected _context?: ChannelContext; + + constructor(protected _version: V1, payload: ChannelResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.attributes = (payload.attributes); + this.type = payload.type; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + this.membersCount = deserialize.integer(payload.members_count); + this.messagesCount = deserialize.integer(payload.messages_count); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Channel resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Channel resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + */ + serviceSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\'s `sid` in the URL. + */ + uniqueName: string; + /** + * The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it\'s only displayed in a FETCH action that returns a single resource; otherwise, it\'s null. If the attributes have not been set, `{}` is returned. + */ + attributes: string; + type: ChannelChannelType; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. + */ + createdBy: string; + /** + * The number of Members in the Channel. + */ + membersCount: number; + /** + * The number of Messages in the Channel. + */ + messagesCount: number; + /** + * The absolute URL of the Channel resource. + */ + url: string; + /** + * The absolute URLs of the [Members](https://www.twilio.com/docs/chat/api/members), [Messages](https://www.twilio.com/docs/chat/api/messages) , [Invites](https://www.twilio.com/docs/chat/api/invites) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/api/messages) for the Channel. + */ + links: Record; + + private get _proxy(): ChannelContext { + this._context = this._context || new ChannelContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Update a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the invites. + */ + invites(): InviteListInstance { + return this._proxy.invites; + } + + /** + * Access the members. + */ + members(): MemberListInstance { + return this._proxy.members; + } + + /** + * Access the messages. + */ + messages(): MessageListInstance { + return this._proxy.messages; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + attributes: this.attributes, + type: this.type, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + membersCount: this.membersCount, + messagesCount: this.messagesCount, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ChannelSolution { + serviceSid: string; +} + +export interface ChannelListInstance { + _version: V1; + _solution: ChannelSolution; + _uri: string; + + (sid: string, ): ChannelContext; + get(sid: string, ): ChannelContext; + + + + + + + + + /** + * Create a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + create(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Create a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + create(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + /** + * Create a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + createWithHttpInfo(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + each(params: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise; + /** + * Retrieve a single target page of ChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise; + list(params: ChannelListInstanceOptions, callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise; + /** + * Lists ChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ChannelPage) => any): Promise; + page(params: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ChannelPage) => any): Promise; + /** + * Retrieve a single page of ChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChannelListInstance(version: V1, serviceSid: string): ChannelListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ChannelListInstance; + + instance.get = function get(sid, ): ChannelContext { + return new ChannelContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Channels`; + + instance.create = function create(params?: ChannelListInstanceCreateOptions | ((error: Error | null, items: ChannelInstance) => any), callback?: (error: Error | null, items: ChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["type"] !== undefined) + data["Type"] = params["type"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ChannelListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["type"] !== undefined) + data["Type"] = params["type"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ChannelListInstancePageOptions | ((error: Error | null, items: ChannelPage) => any), callback?: (error: Error | null, items: ChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["type"] !== undefined) + data["Type"] = serialize.map(params["type"], (e: ChannelChannelType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["type"] !== undefined) + data["Type"] = serialize.map(params["type"], (e: ChannelChannelType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ChannelPage extends Page { +/** +* Initialize the ChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChannelResource): ChannelInstance { + + return new ChannelInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v1/service/channel/invite.ts b/rest/chat/v1/service/channel/invite.ts new file mode 100644 index 000000000..c6d1e13a8 --- /dev/null +++ b/rest/chat/v1/service/channel/invite.ts @@ -0,0 +1,794 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a InviteInstance + */ +export interface InviteListInstanceCreateOptions { + /** The `identity` value that uniquely identifies the new resource\\\'s [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. */ + "identity": string; + /** The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. */ + "roleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface InviteListInstanceEachOptions { + /** The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InviteInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InviteListInstanceOptions { + /** The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InviteListInstancePageOptions { + /** The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InviteContext { + + /** + * Remove a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise + + /** + * Fetch a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InviteContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class InviteContextImpl implements InviteContext { + protected _solution: InviteContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Invites/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InviteInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new InviteInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InvitePayload extends TwilioResponsePayload { + invites: InviteResource[]; +} + +interface InviteResource { + sid: string; + account_sid: string; + channel_sid: string; + service_sid: string; + identity: string; + date_created: Date; + date_updated: Date; + role_sid: string; + created_by: string; + url: string; +} + +export class InviteInstance { + protected _solution: InviteContextSolution; + protected _context?: InviteContext; + + constructor(protected _version: V1, payload: InviteResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.channelSid = (payload.channel_sid); + this.serviceSid = (payload.service_sid); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.roleSid = (payload.role_sid); + this.createdBy = (payload.created_by); + this.url = (payload.url); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Invite resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Invite resource. + */ + accountSid: string; + /** + * The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resource belongs to. + */ + channelSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + */ + serviceSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s [User](https://www.twilio.com/docs/api/chat/rest/users) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + */ + identity: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the resource. + */ + roleSid: string; + /** + * The `identity` of the User that created the invite. + */ + createdBy: string; + /** + * The absolute URL of the Invite resource. + */ + url: string; + + private get _proxy(): InviteContext { + this._context = this._context || new InviteContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + channelSid: this.channelSid, + serviceSid: this.serviceSid, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + roleSid: this.roleSid, + createdBy: this.createdBy, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InviteSolution { + serviceSid: string; + channelSid: string; +} + +export interface InviteListInstance { + _version: V1; + _solution: InviteSolution; + _uri: string; + + (sid: string, ): InviteContext; + get(sid: string, ): InviteContext; + + + + + + + /** + * Create a InviteInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + create(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, item?: InviteInstance) => any): Promise; + + /** + * Create a InviteInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + createWithHttpInfo(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams InviteInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + each(params: InviteListInstanceEachOptions, callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InviteInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InviteListInstanceEachOptions, callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InviteInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InvitePage) => any): Promise; + /** + * Retrieve a single target page of InviteInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InviteInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InviteInstance[]) => any): Promise; + list(params: InviteListInstanceOptions, callback?: (error: Error | null, items: InviteInstance[]) => any): Promise; + /** + * Lists InviteInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InviteListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InviteInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InvitePage) => any): Promise; + page(params: InviteListInstancePageOptions, callback?: (error: Error | null, items: InvitePage) => any): Promise; + /** + * Retrieve a single page of InviteInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InviteListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InviteListInstance(version: V1, serviceSid: string, channelSid: string): InviteListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as InviteListInstance; + + instance.get = function get(sid, ): InviteContext { + return new InviteContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Invites`; + + instance.create = function create(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, items: InviteInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InviteInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InviteInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InviteListInstancePageOptions | ((error: Error | null, items: InvitePage) => any), callback?: (error: Error | null, items: InvitePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InvitePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InvitePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InvitePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InviteListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InvitePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InvitePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InvitePage extends Page { +/** +* Initialize the InvitePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InviteSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InviteInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InviteResource): InviteInstance { + + return new InviteInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v1/service/channel/member.ts b/rest/chat/v1/service/channel/member.ts new file mode 100644 index 000000000..08dbc48ce --- /dev/null +++ b/rest/chat/v1/service/channel/member.ts @@ -0,0 +1,968 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a MemberInstance + */ +export interface MemberContextUpdateOptions { + /** The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). */ + "roleSid"?: string; + /** The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). */ + "lastConsumedMessageIndex"?: number; +} + +/** + * Options to pass to create a MemberInstance + */ +export interface MemberListInstanceCreateOptions { + /** The `identity` value that uniquely identifies the new resource\\\'s [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. */ + "identity": string; + /** The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). */ + "roleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface MemberListInstanceEachOptions { + /** The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MemberInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MemberListInstanceOptions { + /** The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MemberListInstancePageOptions { + /** The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MemberContext { + + /** + * Remove a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise + + /** + * Fetch a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + /** + * Update a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + /** + * Update a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MemberContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class MemberContextImpl implements MemberContext { + protected _solution: MemberContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Members/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MemberContextUpdateOptions | ((error: Error | null, item?: MemberInstance) => any),callback?: (error: Error | null, item?: MemberInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MemberContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MemberPayload extends TwilioResponsePayload { + members: MemberResource[]; +} + +interface MemberResource { + sid: string; + account_sid: string; + channel_sid: string; + service_sid: string; + identity: string; + date_created: Date; + date_updated: Date; + role_sid: string; + last_consumed_message_index: number; + last_consumption_timestamp: Date; + url: string; +} + +export class MemberInstance { + protected _solution: MemberContextSolution; + protected _context?: MemberContext; + + constructor(protected _version: V1, payload: MemberResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.channelSid = (payload.channel_sid); + this.serviceSid = (payload.service_sid); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.roleSid = (payload.role_sid); + this.lastConsumedMessageIndex = deserialize.integer(payload.last_consumed_message_index); + this.lastConsumptionTimestamp = deserialize.iso8601DateTime(payload.last_consumption_timestamp); + this.url = (payload.url); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Member resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Member resource. + */ + accountSid: string; + /** + * The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) for the member. + */ + channelSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + */ + serviceSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s [User](https://www.twilio.com/docs/api/chat/rest/users) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + */ + identity: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the member. + */ + roleSid: string; + /** + * The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) in the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) that the Member has read. + */ + lastConsumedMessageIndex: number; + /** + * The ISO 8601 timestamp string that represents the date-time of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) read event for the Member within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + */ + lastConsumptionTimestamp: Date; + /** + * The absolute URL of the Member resource. + */ + url: string; + + private get _proxy(): MemberContext { + this._context = this._context || new MemberContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + /** + * Update a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MemberInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + channelSid: this.channelSid, + serviceSid: this.serviceSid, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + roleSid: this.roleSid, + lastConsumedMessageIndex: this.lastConsumedMessageIndex, + lastConsumptionTimestamp: this.lastConsumptionTimestamp, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MemberSolution { + serviceSid: string; + channelSid: string; +} + +export interface MemberListInstance { + _version: V1; + _solution: MemberSolution; + _uri: string; + + (sid: string, ): MemberContext; + get(sid: string, ): MemberContext; + + + + + + + + + /** + * Create a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + create(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + /** + * Create a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + createWithHttpInfo(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MemberInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + each(params: MemberListInstanceEachOptions, callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MemberInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MemberListInstanceEachOptions, callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MemberInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MemberPage) => any): Promise; + /** + * Retrieve a single target page of MemberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MemberInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MemberInstance[]) => any): Promise; + list(params: MemberListInstanceOptions, callback?: (error: Error | null, items: MemberInstance[]) => any): Promise; + /** + * Lists MemberInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MemberListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MemberInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MemberPage) => any): Promise; + page(params: MemberListInstancePageOptions, callback?: (error: Error | null, items: MemberPage) => any): Promise; + /** + * Retrieve a single page of MemberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MemberListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MemberListInstance(version: V1, serviceSid: string, channelSid: string): MemberListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MemberListInstance; + + instance.get = function get(sid, ): MemberContext { + return new MemberContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Members`; + + instance.create = function create(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, items: MemberInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MemberListInstancePageOptions | ((error: Error | null, items: MemberPage) => any), callback?: (error: Error | null, items: MemberPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MemberPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MemberPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MemberPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MemberListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MemberPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MemberPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MemberPage extends Page { +/** +* Initialize the MemberPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: MemberSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MemberInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MemberResource): MemberInstance { + + return new MemberInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v1/service/channel/message.ts b/rest/chat/v1/service/channel/message.ts new file mode 100644 index 000000000..ac5bbbed0 --- /dev/null +++ b/rest/chat/v1/service/channel/message.ts @@ -0,0 +1,990 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type MessageOrderType = 'asc'|'desc'; + + + + +/** + * Options to pass to update a MessageInstance + */ +export interface MessageContextUpdateOptions { + /** The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. */ + "body"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; +} + +/** + * Options to pass to create a MessageInstance + */ +export interface MessageListInstanceCreateOptions { + /** The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. */ + "body": string; + /** The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message\\\'s author. The default value is `system`. */ + "from"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; +} + +/** + * Options to pass to each + */ +export interface MessageListInstanceEachOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MessageInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MessageListInstanceOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MessageListInstancePageOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MessageContext { + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MessageContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class MessageContextImpl implements MessageContext { + protected _solution: MessageContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Messages/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MessageContextUpdateOptions | ((error: Error | null, item?: MessageInstance) => any),callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MessageContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MessagePayload extends TwilioResponsePayload { + messages: MessageResource[]; +} + +interface MessageResource { + sid: string; + account_sid: string; + attributes: string; + service_sid: string; + to: string; + channel_sid: string; + date_created: Date; + date_updated: Date; + was_edited: boolean; + from: string; + body: string; + index: number; + url: string; +} + +export class MessageInstance { + protected _solution: MessageContextSolution; + protected _context?: MessageContext; + + constructor(protected _version: V1, payload: MessageResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.attributes = (payload.attributes); + this.serviceSid = (payload.service_sid); + this.to = (payload.to); + this.channelSid = (payload.channel_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.wasEdited = (payload.was_edited); + this.from = (payload.from); + this.body = (payload.body); + this.index = deserialize.integer(payload.index); + this.url = (payload.url); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Message resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Message resource. + */ + accountSid: string; + /** + * The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it\'s only displayed in a FETCH action that returns a single resource; otherwise, it\'s null. If the attributes have not been set, `{}` is returned. + */ + attributes: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the [Channel](https://www.twilio.com/docs/chat/api/channels) that the message was sent to. + */ + to: string; + /** + * The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the Message resource belongs to. + */ + channelSid: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * Whether the message has been edited since it was created. + */ + wasEdited: boolean; + /** + * The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the message\'s author. The default value is `system`. + */ + from: string; + /** + * The content of the message. + */ + body: string; + /** + * The index of the message within the [Channel](https://www.twilio.com/docs/chat/api/channels). + */ + index: number; + /** + * The absolute URL of the Message resource. + */ + url: string; + + private get _proxy(): MessageContext { + this._context = this._context || new MessageContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MessageInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + attributes: this.attributes, + serviceSid: this.serviceSid, + to: this.to, + channelSid: this.channelSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + wasEdited: this.wasEdited, + from: this.from, + body: this.body, + index: this.index, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MessageSolution { + serviceSid: string; + channelSid: string; +} + +export interface MessageListInstance { + _version: V1; + _solution: MessageSolution; + _uri: string; + + (sid: string, ): MessageContext; + get(sid: string, ): MessageContext; + + + + + + + + + /** + * Create a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Create a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MessageInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + each(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MessageInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single target page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MessageInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + list(params: MessageListInstanceOptions, callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + /** + * Lists MessageInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MessageListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MessagePage) => any): Promise; + page(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessageListInstance(version: V1, serviceSid: string, channelSid: string): MessageListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MessageListInstance; + + instance.get = function get(sid, ): MessageContext { + return new MessageContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Messages`; + + instance.create = function create(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, items: MessageInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["body"] === null || params["body"] === undefined) { + throw new Error('Required parameter "params[\'body\']" missing.'); + } + + let data: any = {}; + + + + data["Body"] = params["body"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["body"] === null || params["body"] === undefined) { + throw new Error('Required parameter "params[\'body\']" missing.'); + } + + let data: any = {}; + + + + data["Body"] = params["body"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MessageListInstancePageOptions | ((error: Error | null, items: MessagePage) => any), callback?: (error: Error | null, items: MessagePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MessagePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MessagePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MessageListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MessagePage extends Page { +/** +* Initialize the MessagePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: MessageSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MessageInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MessageResource): MessageInstance { + + return new MessageInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v1/service/role.ts b/rest/chat/v1/service/role.ts new file mode 100644 index 000000000..033c40e6e --- /dev/null +++ b/rest/chat/v1/service/role.ts @@ -0,0 +1,921 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The type of role. Can be: `channel` for [Channel](https://www.twilio.com/docs/chat/api/channels) roles or `deployment` for [Service](https://www.twilio.com/docs/chat/api/services) roles. + */ +export type RoleRoleType = 'channel'|'deployment'; + + + + +/** + * Options to pass to update a RoleInstance + */ +export interface RoleContextUpdateOptions { + /** A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role\\\'s `type` and are described in the documentation. */ + "permission": Array; +} + +/** + * Options to pass to create a RoleInstance + */ +export interface RoleListInstanceCreateOptions { + /** A descriptive string that you create to describe the new resource. It can be up to 64 characters long. */ + "friendlyName": string; + /** */ + "type": RoleRoleType; + /** A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role\\\'s `type` and are described in the documentation. */ + "permission": Array; +} + +/** + * Options to pass to each + */ +export interface RoleListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoleInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoleListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoleListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoleContext { + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoleContextSolution { + "serviceSid": string; + "sid": string; +} + +export class RoleContextImpl implements RoleContext { + protected _solution: RoleContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Roles/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RolePayload extends TwilioResponsePayload { + roles: RoleResource[]; +} + +interface RoleResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + type: RoleRoleType; + permissions: Array; + date_created: Date; + date_updated: Date; + url: string; +} + +export class RoleInstance { + protected _solution: RoleContextSolution; + protected _context?: RoleContext; + + constructor(protected _version: V1, payload: RoleResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.permissions = (payload.permissions); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Role resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Role resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + */ + serviceSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + type: RoleRoleType; + /** + * An array of the permissions the role has been granted, formatted as a JSON string. + */ + permissions: Array; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Role resource. + */ + url: string; + + private get _proxy(): RoleContext { + this._context = this._context || new RoleContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: RoleInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + type: this.type, + permissions: this.permissions, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoleSolution { + serviceSid: string; +} + +export interface RoleListInstance { + _version: V1; + _solution: RoleSolution; + _uri: string; + + (sid: string, ): RoleContext; + get(sid: string, ): RoleContext; + + + + + + + + + /** + * Create a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Create a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams RoleInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + each(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoleInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single target page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RoleInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + list(params: RoleListInstanceOptions, callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + /** + * Lists RoleInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RoleListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RolePage) => any): Promise; + page(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoleListInstance(version: V1, serviceSid: string): RoleListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RoleListInstance; + + instance.get = function get(sid, ): RoleContext { + return new RoleContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Roles`; + + instance.create = function create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RoleListInstancePageOptions | ((error: Error | null, items: RolePage) => any), callback?: (error: Error | null, items: RolePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RolePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RolePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoleListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RolePage extends Page { +/** +* Initialize the RolePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: RoleSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoleInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoleResource): RoleInstance { + + return new RoleInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v1/service/user.ts b/rest/chat/v1/service/user.ts new file mode 100644 index 000000000..209459ebb --- /dev/null +++ b/rest/chat/v1/service/user.ts @@ -0,0 +1,1001 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { UserChannelListInstance } from "./user/userChannel"; + + + + + +/** + * Options to pass to update a UserInstance + */ +export interface UserContextUpdateOptions { + /** The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. */ + "roleSid"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; + /** A descriptive string that you create to describe the resource. It is often used for display purposes. */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a UserInstance + */ +export interface UserListInstanceCreateOptions { + /** The `identity` value that uniquely identifies the new resource\\\'s [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. */ + "identity": string; + /** The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. */ + "roleSid"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; + /** A descriptive string that you create to describe the new resource. This value is often used for display purposes. */ + "friendlyName"?: string; +} + +/** + * Options to pass to each + */ +export interface UserListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserContext { + userChannels: UserChannelListInstance; + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserContextSolution { + "serviceSid": string; + "sid": string; +} + +export class UserContextImpl implements UserContext { + protected _solution: UserContextSolution; + protected _uri: string; + + protected _userChannels?: UserChannelListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Users/${sid}`; + } + + get userChannels(): UserChannelListInstance { + this._userChannels = this._userChannels || UserChannelListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._userChannels; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserContextUpdateOptions | ((error: Error | null, item?: UserInstance) => any),callback?: (error: Error | null, item?: UserInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserPayload extends TwilioResponsePayload { + users: UserResource[]; +} + +interface UserResource { + sid: string; + account_sid: string; + service_sid: string; + attributes: string; + friendly_name: string; + role_sid: string; + identity: string; + is_online: boolean; + is_notifiable: boolean; + date_created: Date; + date_updated: Date; + joined_channels_count: number; + links: Record; + url: string; +} + +export class UserInstance { + protected _solution: UserContextSolution; + protected _context?: UserContext; + + constructor(protected _version: V1, payload: UserResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.attributes = (payload.attributes); + this.friendlyName = (payload.friendly_name); + this.roleSid = (payload.role_sid); + this.identity = (payload.identity); + this.isOnline = (payload.is_online); + this.isNotifiable = (payload.is_notifiable); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.joinedChannelsCount = deserialize.integer(payload.joined_channels_count); + this.links = (payload.links); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the User resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the User resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + */ + serviceSid: string; + /** + * The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it\'s only displayed in a FETCH action that returns a single resource; otherwise, it\'s null. If the attributes have not been set, `{}` is returned. + */ + attributes: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the user. + */ + roleSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s User within the [Service](https://www.twilio.com/docs/api/chat/rest/services). This value is often a username or an email address. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + */ + identity: string; + /** + * Whether the User is actively connected to the Service instance and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service\'s `reachability_enabled` is `false`, if the User has never been online for the Service instance, even if the Service\'s `reachability_enabled` is `true`. + */ + isOnline: boolean; + /** + * Whether the User has a potentially valid Push Notification registration (APN or GCM) for the Service instance. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service\'s `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service\'s `reachability_enabled` is `true`. + */ + isNotifiable: boolean; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The number of Channels this User is a Member of. + */ + joinedChannelsCount: number; + /** + * The absolute URLs of the [Channel](https://www.twilio.com/docs/chat/api/channels) and [Binding](https://www.twilio.com/docs/chat/rest/bindings-resource) resources related to the user. + */ + links: Record; + /** + * The absolute URL of the User resource. + */ + url: string; + + private get _proxy(): UserContext { + this._context = this._context || new UserContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the userChannels. + */ + userChannels(): UserChannelListInstance { + return this._proxy.userChannels; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + attributes: this.attributes, + friendlyName: this.friendlyName, + roleSid: this.roleSid, + identity: this.identity, + isOnline: this.isOnline, + isNotifiable: this.isNotifiable, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + joinedChannelsCount: this.joinedChannelsCount, + links: this.links, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserSolution { + serviceSid: string; +} + +export interface UserListInstance { + _version: V1; + _solution: UserSolution; + _uri: string; + + (sid: string, ): UserContext; + get(sid: string, ): UserContext; + + + + + + + + + /** + * Create a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Create a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams UserInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + each(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single target page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + list(params: UserListInstanceOptions, callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + /** + * Lists UserInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserPage) => any): Promise; + page(params: UserListInstancePageOptions, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserListInstance(version: V1, serviceSid: string): UserListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as UserListInstance; + + instance.get = function get(sid, ): UserContext { + return new UserContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Users`; + + instance.create = function create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: UserInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: UserListInstancePageOptions | ((error: Error | null, items: UserPage) => any), callback?: (error: Error | null, items: UserPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserPage extends Page { +/** +* Initialize the UserPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: UserSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserResource): UserInstance { + + return new UserInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v1/service/user/userChannel.ts b/rest/chat/v1/service/user/userChannel.ts new file mode 100644 index 000000000..da4baeecd --- /dev/null +++ b/rest/chat/v1/service/user/userChannel.ts @@ -0,0 +1,441 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The status of the User on the Channel. Can be: `joined`, `invited`, or `not_participating`. + */ +export type UserChannelChannelStatus = 'joined'|'invited'|'not_participating'; + + +/** + * Options to pass to each + */ +export interface UserChannelListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserChannelListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserChannelListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface UserChannelSolution { + serviceSid: string; + userSid: string; +} + +export interface UserChannelListInstance { + _version: V1; + _solution: UserChannelSolution; + _uri: string; + + + + + /** + * Streams UserChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + each(params: UserChannelListInstanceEachOptions, callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserChannelListInstanceEachOptions, callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + /** + * Retrieve a single target page of UserChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserChannelInstance[]) => any): Promise; + list(params: UserChannelListInstanceOptions, callback?: (error: Error | null, items: UserChannelInstance[]) => any): Promise; + /** + * Lists UserChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + page(params: UserChannelListInstancePageOptions, callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + /** + * Retrieve a single page of UserChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserChannelListInstance(version: V1, serviceSid: string, userSid: string): UserChannelListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + const instance = {} as UserChannelListInstance; + + instance._version = version; + instance._solution = { serviceSid, userSid, }; + instance._uri = `/Services/${serviceSid}/Users/${userSid}/Channels`; + + instance.page = function page(params?: UserChannelListInstancePageOptions | ((error: Error | null, items: UserChannelPage) => any), callback?: (error: Error | null, items: UserChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface UserChannelPayload extends TwilioResponsePayload { + channels: UserChannelResource[]; +} + +interface UserChannelResource { + account_sid: string; + service_sid: string; + channel_sid: string; + member_sid: string; + status: UserChannelChannelStatus; + last_consumed_message_index: number; + unread_messages_count: number; + links: Record; +} + +export class UserChannelInstance { + + constructor(protected _version: V1, payload: UserChannelResource, serviceSid: string, userSid: string) { + + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.channelSid = (payload.channel_sid); + this.memberSid = (payload.member_sid); + this.status = payload.status; + this.lastConsumedMessageIndex = deserialize.integer(payload.last_consumed_message_index); + this.unreadMessagesCount = deserialize.integer(payload.unread_messages_count); + this.links = (payload.links); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the User Channel resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resource belongs to. + */ + channelSid: string; + /** + * The SID of a [Member](https://www.twilio.com/docs/api/chat/rest/members) that represents the User on the Channel. + */ + memberSid: string; + status: UserChannelChannelStatus; + /** + * The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) in the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) that the Member has read. + */ + lastConsumedMessageIndex: number; + /** + * The number of unread Messages in the Channel for the User. Note that retrieving messages on a client endpoint does not mean that messages are consumed or read. See [Consumption Horizon feature](/docs/api/chat/guides/consumption-horizon) to learn how to mark messages as consumed. + */ + unreadMessagesCount: number; + /** + * The absolute URLs of the [Members](https://www.twilio.com/docs/chat/api/members), [Messages](https://www.twilio.com/docs/chat/api/messages) , [Invites](https://www.twilio.com/docs/chat/api/invites) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/api/messages) for the Channel. + */ + links: Record; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + serviceSid: this.serviceSid, + channelSid: this.channelSid, + memberSid: this.memberSid, + status: this.status, + lastConsumedMessageIndex: this.lastConsumedMessageIndex, + unreadMessagesCount: this.unreadMessagesCount, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class UserChannelPage extends Page { +/** +* Initialize the UserChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: UserChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserChannelResource): UserChannelInstance { + + return new UserChannelInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.userSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/credential.ts b/rest/chat/v2/credential.ts new file mode 100644 index 000000000..e591362ed --- /dev/null +++ b/rest/chat/v2/credential.ts @@ -0,0 +1,971 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The type of push-notification service the credential is for. Can be: `gcm`, `fcm`, or `apn`. + */ +export type CredentialPushService = 'gcm'|'apn'|'fcm'; + + + + +/** + * Options to pass to update a CredentialInstance + */ +export interface CredentialContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` */ + "certificate"?: string; + /** [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` */ + "privateKey"?: string; + /** [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. */ + "sandbox"?: boolean; + /** [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. */ + "apiKey"?: string; + /** [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. */ + "secret"?: string; +} + +/** + * Options to pass to create a CredentialInstance + */ +export interface CredentialListInstanceCreateOptions { + /** */ + "type": CredentialPushService; + /** A descriptive string that you create to describe the new resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` */ + "certificate"?: string; + /** [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` */ + "privateKey"?: string; + /** [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. */ + "sandbox"?: boolean; + /** [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. */ + "apiKey"?: string; + /** [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. */ + "secret"?: string; +} + +/** + * Options to pass to each + */ +export interface CredentialListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CredentialInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CredentialListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CredentialListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CredentialContext { + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CredentialContextSolution { + "sid": string; +} + +export class CredentialContextImpl implements CredentialContext { + protected _solution: CredentialContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Credentials/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: CredentialInstance) => any),callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CredentialPayload extends TwilioResponsePayload { + credentials: CredentialResource[]; +} + +interface CredentialResource { + sid: string; + account_sid: string; + friendly_name: string; + type: CredentialPushService; + sandbox: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CredentialInstance { + protected _solution: CredentialContextSolution; + protected _context?: CredentialContext; + + constructor(protected _version: V2, payload: CredentialResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.sandbox = (payload.sandbox); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Credential resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + type: CredentialPushService; + /** + * [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + */ + sandbox: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Credential resource. + */ + url: string; + + private get _proxy(): CredentialContext { + this._context = this._context || new CredentialContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + type: this.type, + sandbox: this.sandbox, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CredentialSolution { +} + +export interface CredentialListInstance { + _version: V2; + _solution: CredentialSolution; + _uri: string; + + (sid: string, ): CredentialContext; + get(sid: string, ): CredentialContext; + + + + + + + + + /** + * Create a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Create a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CredentialInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + each(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CredentialInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single target page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CredentialInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + list(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + /** + * Lists CredentialInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CredentialPage) => any): Promise; + page(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CredentialListInstance(version: V2): CredentialListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CredentialListInstance; + + instance.get = function get(sid, ): CredentialContext { + return new CredentialContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Credentials`; + + instance.create = function create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: CredentialInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CredentialListInstancePageOptions | ((error: Error | null, items: CredentialPage) => any), callback?: (error: Error | null, items: CredentialPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CredentialPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CredentialPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CredentialListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CredentialPage extends Page { +/** +* Initialize the CredentialPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: CredentialSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CredentialInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CredentialResource): CredentialInstance { + + return new CredentialInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service.ts b/rest/chat/v2/service.ts new file mode 100644 index 000000000..34f93a4dd --- /dev/null +++ b/rest/chat/v2/service.ts @@ -0,0 +1,1248 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { BindingListInstance } from "./service/binding"; +import { ChannelListInstance } from "./service/channel"; +import { RoleListInstance } from "./service/role"; +import { UserListInstance } from "./service/user"; + + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** A descriptive string that you create to describe the resource. */ + "friendlyName"?: string; + /** The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. */ + "defaultServiceRoleSid"?: string; + /** The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. */ + "defaultChannelRoleSid"?: string; + /** The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. */ + "defaultChannelCreatorRoleSid"?: string; + /** Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. */ + "readStatusEnabled"?: boolean; + /** Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. */ + "reachabilityEnabled"?: boolean; + /** How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. */ + "typingIndicatorTimeout"?: number; + /** DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. */ + "consumptionReportInterval"?: number; + /** Whether to send a notification when a new message is added to a channel. The default is `false`. */ + "notifications.newMessage.enabled"?: boolean; + /** The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. */ + "notifications.newMessage.template"?: string; + /** The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. */ + "notifications.newMessage.sound"?: string; + /** Whether the new message badge is enabled. The default is `false`. */ + "notifications.newMessage.badgeCountEnabled"?: boolean; + /** Whether to send a notification when a member is added to a channel. The default is `false`. */ + "notifications.addedToChannel.enabled"?: boolean; + /** The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. */ + "notifications.addedToChannel.template"?: string; + /** The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. */ + "notifications.addedToChannel.sound"?: string; + /** Whether to send a notification to a user when they are removed from a channel. The default is `false`. */ + "notifications.removedFromChannel.enabled"?: boolean; + /** The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. */ + "notifications.removedFromChannel.template"?: string; + /** The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. */ + "notifications.removedFromChannel.sound"?: string; + /** Whether to send a notification when a user is invited to a channel. The default is `false`. */ + "notifications.invitedToChannel.enabled"?: boolean; + /** The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. */ + "notifications.invitedToChannel.template"?: string; + /** The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. */ + "notifications.invitedToChannel.sound"?: string; + /** The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. */ + "preWebhookUrl"?: string; + /** The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. */ + "postWebhookUrl"?: string; + /** The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. */ + "webhookMethod"?: string; + /** The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. */ + "webhookFilters"?: Array; + /** The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. */ + "limits.channelMembers"?: number; + /** The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. */ + "limits.userChannels"?: number; + /** The message to send when a media message has no text. Can be used as placeholder message. */ + "media.compatibilityMessage"?: string; + /** The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won\\\'t be retried. */ + "preWebhookRetryCount"?: number; + /** The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won\\\'t be retried. */ + "postWebhookRetryCount"?: number; + /** Whether to log notifications. The default is `false`. */ + "notifications.logEnabled"?: boolean; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** A descriptive string that you create to describe the new resource. */ + "friendlyName": string; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + bindings: BindingListInstance; + channels: ChannelListInstance; + roles: RoleListInstance; + users: UserListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _bindings?: BindingListInstance; + protected _channels?: ChannelListInstance; + protected _roles?: RoleListInstance; + protected _users?: UserListInstance; + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get bindings(): BindingListInstance { + this._bindings = this._bindings || BindingListInstance(this._version, this._solution.sid); + return this._bindings; + } + + get channels(): ChannelListInstance { + this._channels = this._channels || ChannelListInstance(this._version, this._solution.sid); + return this._channels; + } + + get roles(): RoleListInstance { + this._roles = this._roles || RoleListInstance(this._version, this._solution.sid); + return this._roles; + } + + get users(): UserListInstance { + this._users = this._users || UserListInstance(this._version, this._solution.sid); + return this._users; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["defaultServiceRoleSid"] !== undefined) + data["DefaultServiceRoleSid"] = params["defaultServiceRoleSid"]; + if (params["defaultChannelRoleSid"] !== undefined) + data["DefaultChannelRoleSid"] = params["defaultChannelRoleSid"]; + if (params["defaultChannelCreatorRoleSid"] !== undefined) + data["DefaultChannelCreatorRoleSid"] = params["defaultChannelCreatorRoleSid"]; + if (params["readStatusEnabled"] !== undefined) + data["ReadStatusEnabled"] = serialize.bool(params["readStatusEnabled"]); + if (params["reachabilityEnabled"] !== undefined) + data["ReachabilityEnabled"] = serialize.bool(params["reachabilityEnabled"]); + if (params["typingIndicatorTimeout"] !== undefined) + data["TypingIndicatorTimeout"] = params["typingIndicatorTimeout"]; + if (params["consumptionReportInterval"] !== undefined) + data["ConsumptionReportInterval"] = params["consumptionReportInterval"]; + if (params["notifications.newMessage.enabled"] !== undefined) + data["Notifications.NewMessage.Enabled"] = serialize.bool(params["notifications.newMessage.enabled"]); + if (params["notifications.newMessage.template"] !== undefined) + data["Notifications.NewMessage.Template"] = params["notifications.newMessage.template"]; + if (params["notifications.newMessage.sound"] !== undefined) + data["Notifications.NewMessage.Sound"] = params["notifications.newMessage.sound"]; + if (params["notifications.newMessage.badgeCountEnabled"] !== undefined) + data["Notifications.NewMessage.BadgeCountEnabled"] = serialize.bool(params["notifications.newMessage.badgeCountEnabled"]); + if (params["notifications.addedToChannel.enabled"] !== undefined) + data["Notifications.AddedToChannel.Enabled"] = serialize.bool(params["notifications.addedToChannel.enabled"]); + if (params["notifications.addedToChannel.template"] !== undefined) + data["Notifications.AddedToChannel.Template"] = params["notifications.addedToChannel.template"]; + if (params["notifications.addedToChannel.sound"] !== undefined) + data["Notifications.AddedToChannel.Sound"] = params["notifications.addedToChannel.sound"]; + if (params["notifications.removedFromChannel.enabled"] !== undefined) + data["Notifications.RemovedFromChannel.Enabled"] = serialize.bool(params["notifications.removedFromChannel.enabled"]); + if (params["notifications.removedFromChannel.template"] !== undefined) + data["Notifications.RemovedFromChannel.Template"] = params["notifications.removedFromChannel.template"]; + if (params["notifications.removedFromChannel.sound"] !== undefined) + data["Notifications.RemovedFromChannel.Sound"] = params["notifications.removedFromChannel.sound"]; + if (params["notifications.invitedToChannel.enabled"] !== undefined) + data["Notifications.InvitedToChannel.Enabled"] = serialize.bool(params["notifications.invitedToChannel.enabled"]); + if (params["notifications.invitedToChannel.template"] !== undefined) + data["Notifications.InvitedToChannel.Template"] = params["notifications.invitedToChannel.template"]; + if (params["notifications.invitedToChannel.sound"] !== undefined) + data["Notifications.InvitedToChannel.Sound"] = params["notifications.invitedToChannel.sound"]; + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + if (params["webhookFilters"] !== undefined) + data["WebhookFilters"] = serialize.map(params["webhookFilters"], (e: string) => (e)); + if (params["limits.channelMembers"] !== undefined) + data["Limits.ChannelMembers"] = params["limits.channelMembers"]; + if (params["limits.userChannels"] !== undefined) + data["Limits.UserChannels"] = params["limits.userChannels"]; + if (params["media.compatibilityMessage"] !== undefined) + data["Media.CompatibilityMessage"] = params["media.compatibilityMessage"]; + if (params["preWebhookRetryCount"] !== undefined) + data["PreWebhookRetryCount"] = params["preWebhookRetryCount"]; + if (params["postWebhookRetryCount"] !== undefined) + data["PostWebhookRetryCount"] = params["postWebhookRetryCount"]; + if (params["notifications.logEnabled"] !== undefined) + data["Notifications.LogEnabled"] = serialize.bool(params["notifications.logEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["defaultServiceRoleSid"] !== undefined) + data["DefaultServiceRoleSid"] = params["defaultServiceRoleSid"]; + if (params["defaultChannelRoleSid"] !== undefined) + data["DefaultChannelRoleSid"] = params["defaultChannelRoleSid"]; + if (params["defaultChannelCreatorRoleSid"] !== undefined) + data["DefaultChannelCreatorRoleSid"] = params["defaultChannelCreatorRoleSid"]; + if (params["readStatusEnabled"] !== undefined) + data["ReadStatusEnabled"] = serialize.bool(params["readStatusEnabled"]); + if (params["reachabilityEnabled"] !== undefined) + data["ReachabilityEnabled"] = serialize.bool(params["reachabilityEnabled"]); + if (params["typingIndicatorTimeout"] !== undefined) + data["TypingIndicatorTimeout"] = params["typingIndicatorTimeout"]; + if (params["consumptionReportInterval"] !== undefined) + data["ConsumptionReportInterval"] = params["consumptionReportInterval"]; + if (params["notifications.newMessage.enabled"] !== undefined) + data["Notifications.NewMessage.Enabled"] = serialize.bool(params["notifications.newMessage.enabled"]); + if (params["notifications.newMessage.template"] !== undefined) + data["Notifications.NewMessage.Template"] = params["notifications.newMessage.template"]; + if (params["notifications.newMessage.sound"] !== undefined) + data["Notifications.NewMessage.Sound"] = params["notifications.newMessage.sound"]; + if (params["notifications.newMessage.badgeCountEnabled"] !== undefined) + data["Notifications.NewMessage.BadgeCountEnabled"] = serialize.bool(params["notifications.newMessage.badgeCountEnabled"]); + if (params["notifications.addedToChannel.enabled"] !== undefined) + data["Notifications.AddedToChannel.Enabled"] = serialize.bool(params["notifications.addedToChannel.enabled"]); + if (params["notifications.addedToChannel.template"] !== undefined) + data["Notifications.AddedToChannel.Template"] = params["notifications.addedToChannel.template"]; + if (params["notifications.addedToChannel.sound"] !== undefined) + data["Notifications.AddedToChannel.Sound"] = params["notifications.addedToChannel.sound"]; + if (params["notifications.removedFromChannel.enabled"] !== undefined) + data["Notifications.RemovedFromChannel.Enabled"] = serialize.bool(params["notifications.removedFromChannel.enabled"]); + if (params["notifications.removedFromChannel.template"] !== undefined) + data["Notifications.RemovedFromChannel.Template"] = params["notifications.removedFromChannel.template"]; + if (params["notifications.removedFromChannel.sound"] !== undefined) + data["Notifications.RemovedFromChannel.Sound"] = params["notifications.removedFromChannel.sound"]; + if (params["notifications.invitedToChannel.enabled"] !== undefined) + data["Notifications.InvitedToChannel.Enabled"] = serialize.bool(params["notifications.invitedToChannel.enabled"]); + if (params["notifications.invitedToChannel.template"] !== undefined) + data["Notifications.InvitedToChannel.Template"] = params["notifications.invitedToChannel.template"]; + if (params["notifications.invitedToChannel.sound"] !== undefined) + data["Notifications.InvitedToChannel.Sound"] = params["notifications.invitedToChannel.sound"]; + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + if (params["webhookFilters"] !== undefined) + data["WebhookFilters"] = serialize.map(params["webhookFilters"], (e: string) => (e)); + if (params["limits.channelMembers"] !== undefined) + data["Limits.ChannelMembers"] = params["limits.channelMembers"]; + if (params["limits.userChannels"] !== undefined) + data["Limits.UserChannels"] = params["limits.userChannels"]; + if (params["media.compatibilityMessage"] !== undefined) + data["Media.CompatibilityMessage"] = params["media.compatibilityMessage"]; + if (params["preWebhookRetryCount"] !== undefined) + data["PreWebhookRetryCount"] = params["preWebhookRetryCount"]; + if (params["postWebhookRetryCount"] !== undefined) + data["PostWebhookRetryCount"] = params["postWebhookRetryCount"]; + if (params["notifications.logEnabled"] !== undefined) + data["Notifications.LogEnabled"] = serialize.bool(params["notifications.logEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + sid: string; + account_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + default_service_role_sid: string; + default_channel_role_sid: string; + default_channel_creator_role_sid: string; + read_status_enabled: boolean; + reachability_enabled: boolean; + typing_indicator_timeout: number; + consumption_report_interval: number; + limits: any; + pre_webhook_url: string; + post_webhook_url: string; + webhook_method: string; + webhook_filters: Array; + pre_webhook_retry_count: number; + post_webhook_retry_count: number; + notifications: any; + media: any; + url: string; + links: Record; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V2, payload: ServiceResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.defaultServiceRoleSid = (payload.default_service_role_sid); + this.defaultChannelRoleSid = (payload.default_channel_role_sid); + this.defaultChannelCreatorRoleSid = (payload.default_channel_creator_role_sid); + this.readStatusEnabled = (payload.read_status_enabled); + this.reachabilityEnabled = (payload.reachability_enabled); + this.typingIndicatorTimeout = deserialize.integer(payload.typing_indicator_timeout); + this.consumptionReportInterval = deserialize.integer(payload.consumption_report_interval); + this.limits = (payload.limits); + this.preWebhookUrl = (payload.pre_webhook_url); + this.postWebhookUrl = (payload.post_webhook_url); + this.webhookMethod = (payload.webhook_method); + this.webhookFilters = (payload.webhook_filters); + this.preWebhookRetryCount = deserialize.integer(payload.pre_webhook_retry_count); + this.postWebhookRetryCount = deserialize.integer(payload.post_webhook_retry_count); + this.notifications = (payload.notifications); + this.media = (payload.media); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Service resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + */ + defaultServiceRoleSid: string; + /** + * The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + */ + defaultChannelRoleSid: string; + /** + * The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + */ + defaultChannelCreatorRoleSid: string; + /** + * Whether the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature is enabled. The default is `true`. + */ + readStatusEnabled: boolean; + /** + * Whether the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) is enabled for this Service instance. The default is `false`. + */ + reachabilityEnabled: boolean; + /** + * How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + */ + typingIndicatorTimeout: number; + /** + * DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + */ + consumptionReportInterval: number; + /** + * An object that describes the limits of the service instance. The `limits` object contains `channel_members` to describe the members/channel limit and `user_channels` to describe the channels/user limit. `channel_members` can be 1,000 or less, with a default of 250. `user_channels` can be 1,000 or less, with a default value of 100. + */ + limits: any; + /** + * The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + */ + preWebhookUrl: string; + /** + * The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + */ + postWebhookUrl: string; + /** + * The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + */ + webhookMethod: string; + /** + * The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + */ + webhookFilters: Array; + /** + * The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won\'t be retried. + */ + preWebhookRetryCount: number; + /** + * The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won\'t be retried. + */ + postWebhookRetryCount: number; + /** + * The notification configuration for the Service instance. See [Push Notification Configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + */ + notifications: any; + /** + * An object that describes the properties of media that the service supports. The object contains the `size_limit_mb` property, which describes the size of the largest media file in MB; and the `compatibility_message` property, which contains the message text to send when a media message does not have any text. + */ + media: any; + /** + * The absolute URL of the Service resource. + */ + url: string; + /** + * The absolute URLs of the Service\'s [Channels](https://www.twilio.com/docs/chat/channels), [Roles](https://www.twilio.com/docs/chat/rest/role-resource), [Bindings](https://www.twilio.com/docs/chat/rest/binding-resource), and [Users](https://www.twilio.com/docs/chat/rest/user-resource). + */ + links: Record; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the bindings. + */ + bindings(): BindingListInstance { + return this._proxy.bindings; + } + + /** + * Access the channels. + */ + channels(): ChannelListInstance { + return this._proxy.channels; + } + + /** + * Access the roles. + */ + roles(): RoleListInstance { + return this._proxy.roles; + } + + /** + * Access the users. + */ + users(): UserListInstance { + return this._proxy.users; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + defaultServiceRoleSid: this.defaultServiceRoleSid, + defaultChannelRoleSid: this.defaultChannelRoleSid, + defaultChannelCreatorRoleSid: this.defaultChannelCreatorRoleSid, + readStatusEnabled: this.readStatusEnabled, + reachabilityEnabled: this.reachabilityEnabled, + typingIndicatorTimeout: this.typingIndicatorTimeout, + consumptionReportInterval: this.consumptionReportInterval, + limits: this.limits, + preWebhookUrl: this.preWebhookUrl, + postWebhookUrl: this.postWebhookUrl, + webhookMethod: this.webhookMethod, + webhookFilters: this.webhookFilters, + preWebhookRetryCount: this.preWebhookRetryCount, + postWebhookRetryCount: this.postWebhookRetryCount, + notifications: this.notifications, + media: this.media, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V2; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V2): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ServiceInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service/binding.ts b/rest/chat/v2/service/binding.ts new file mode 100644 index 000000000..96c377304 --- /dev/null +++ b/rest/chat/v2/service/binding.ts @@ -0,0 +1,704 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The push technology to use for the Binding. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + */ +export type BindingBindingType = 'gcm'|'apn'|'fcm'; + + + + +/** + * Options to pass to each + */ +export interface BindingListInstanceEachOptions { + /** The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. */ + "bindingType"?: Array; + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BindingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BindingListInstanceOptions { + /** The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. */ + "bindingType"?: Array; + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BindingListInstancePageOptions { + /** The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. */ + "bindingType"?: Array; + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface BindingContext { + + /** + * Remove a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance + */ + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise + + /** + * Fetch a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BindingContextSolution { + "serviceSid": string; + "sid": string; +} + +export class BindingContextImpl implements BindingContext { + protected _solution: BindingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Bindings/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BindingInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new BindingInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BindingPayload extends TwilioResponsePayload { + bindings: BindingResource[]; +} + +interface BindingResource { + sid: string; + account_sid: string; + service_sid: string; + date_created: Date; + date_updated: Date; + endpoint: string; + identity: string; + credential_sid: string; + binding_type: BindingBindingType; + message_types: Array; + url: string; + links: Record; +} + +export class BindingInstance { + protected _solution: BindingContextSolution; + protected _context?: BindingContext; + + constructor(protected _version: V2, payload: BindingResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.endpoint = (payload.endpoint); + this.identity = (payload.identity); + this.credentialSid = (payload.credential_sid); + this.bindingType = payload.binding_type; + this.messageTypes = (payload.message_types); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Binding resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Binding resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Binding resource is associated with. + */ + serviceSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The unique endpoint identifier for the Binding. The format of this value depends on the `binding_type`. + */ + endpoint: string; + /** + * The application-defined string that uniquely identifies the resource\'s [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + */ + identity: string; + /** + * The SID of the [Credential](https://www.twilio.com/docs/chat/rest/credential-resource) for the binding. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + */ + credentialSid: string; + bindingType: BindingBindingType; + /** + * The [Programmable Chat message types](https://www.twilio.com/docs/chat/push-notification-configuration#push-types) the binding is subscribed to. + */ + messageTypes: Array; + /** + * The absolute URL of the Binding resource. + */ + url: string; + /** + * The absolute URLs of the Binding\'s [User](https://www.twilio.com/docs/chat/rest/user-resource). + */ + links: Record; + + private get _proxy(): BindingContext { + this._context = this._context || new BindingContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance + */ + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + endpoint: this.endpoint, + identity: this.identity, + credentialSid: this.credentialSid, + bindingType: this.bindingType, + messageTypes: this.messageTypes, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BindingSolution { + serviceSid: string; +} + +export interface BindingListInstance { + _version: V2; + _solution: BindingSolution; + _uri: string; + + (sid: string, ): BindingContext; + get(sid: string, ): BindingContext; + + + + + + + + /** + * Streams BindingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + each(params: BindingListInstanceEachOptions, callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BindingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BindingListInstanceEachOptions, callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BindingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BindingPage) => any): Promise; + /** + * Retrieve a single target page of BindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists BindingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BindingInstance[]) => any): Promise; + list(params: BindingListInstanceOptions, callback?: (error: Error | null, items: BindingInstance[]) => any): Promise; + /** + * Lists BindingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: BindingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of BindingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BindingPage) => any): Promise; + page(params: BindingListInstancePageOptions, callback?: (error: Error | null, items: BindingPage) => any): Promise; + /** + * Retrieve a single page of BindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: BindingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BindingListInstance(version: V2, serviceSid: string): BindingListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as BindingListInstance; + + instance.get = function get(sid, ): BindingContext { + return new BindingContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Bindings`; + + instance.page = function page(params?: BindingListInstancePageOptions | ((error: Error | null, items: BindingPage) => any), callback?: (error: Error | null, items: BindingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["bindingType"] !== undefined) + data["BindingType"] = serialize.map(params["bindingType"], (e: BindingBindingType) => (e)); + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BindingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BindingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BindingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BindingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["bindingType"] !== undefined) + data["BindingType"] = serialize.map(params["bindingType"], (e: BindingBindingType) => (e)); + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BindingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BindingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class BindingPage extends Page { +/** +* Initialize the BindingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: BindingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of BindingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BindingResource): BindingInstance { + + return new BindingInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service/channel.ts b/rest/chat/v2/service/channel.ts new file mode 100644 index 000000000..bba115e68 --- /dev/null +++ b/rest/chat/v2/service/channel.ts @@ -0,0 +1,1193 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { InviteListInstance } from "./channel/invite"; +import { MemberListInstance } from "./channel/member"; +import { MessageListInstance } from "./channel/message"; +import { WebhookListInstance } from "./channel/webhook"; + + +/** + * The visibility of the channel. Can be: `public` or `private`. + */ +export type ChannelChannelType = 'public'|'private'; + +export type ChannelWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a ChannelInstance + */ +export interface ChannelContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ChannelWebhookEnabledType; +} + + +/** + * Options to pass to update a ChannelInstance + */ +export interface ChannelContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ChannelWebhookEnabledType; + /** A descriptive string that you create to describe the resource. It can be up to 256 characters long. */ + "friendlyName"?: string; + /** An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\\\'s `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. */ + "uniqueName"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. */ + "dateCreated"?: Date; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. */ + "dateUpdated"?: Date; + /** The `identity` of the User that created the channel. Default is: `system`. */ + "createdBy"?: string; +} + +/** + * Options to pass to create a ChannelInstance + */ +export interface ChannelListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ChannelWebhookEnabledType; + /** A descriptive string that you create to describe the new resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource\\\'s `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. */ + "uniqueName"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; + /** */ + "type"?: ChannelChannelType; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. */ + "dateCreated"?: Date; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. */ + "dateUpdated"?: Date; + /** The `identity` of the User that created the channel. Default is: `system`. */ + "createdBy"?: string; +} + +/** + * Options to pass to each + */ +export interface ChannelListInstanceEachOptions { + /** The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChannelListInstanceOptions { + /** The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChannelListInstancePageOptions { + /** The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ChannelContext { + invites: InviteListInstance; + members: MemberListInstance; + messages: MessageListInstance; + webhooks: WebhookListInstance; + + /** + * Remove a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + remove(params: ChannelContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + removeWithHttpInfo(params: ChannelContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + + /** + * Fetch a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Update a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + /** + * Update a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ChannelContextSolution { + "serviceSid": string; + "sid": string; +} + +export class ChannelContextImpl implements ChannelContext { + protected _solution: ChannelContextSolution; + protected _uri: string; + + protected _invites?: InviteListInstance; + protected _members?: MemberListInstance; + protected _messages?: MessageListInstance; + protected _webhooks?: WebhookListInstance; + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${sid}`; + } + + get invites(): InviteListInstance { + this._invites = this._invites || InviteListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._invites; + } + + get members(): MemberListInstance { + this._members = this._members || MemberListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._members; + } + + get messages(): MessageListInstance { + this._messages = this._messages || MessageListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._messages; + } + + get webhooks(): WebhookListInstance { + this._webhooks = this._webhooks || WebhookListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._webhooks; + } + + remove(params?: ChannelContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: ChannelContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ChannelContextUpdateOptions | ((error: Error | null, item?: ChannelInstance) => any),callback?: (error: Error | null, item?: ChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["createdBy"] !== undefined) + data["CreatedBy"] = params["createdBy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ChannelContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["createdBy"] !== undefined) + data["CreatedBy"] = params["createdBy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ChannelPayload extends TwilioResponsePayload { + channels: ChannelResource[]; +} + +interface ChannelResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + unique_name: string; + attributes: string; + type: ChannelChannelType; + date_created: Date; + date_updated: Date; + created_by: string; + members_count: number; + messages_count: number; + url: string; + links: Record; +} + +export class ChannelInstance { + protected _solution: ChannelContextSolution; + protected _context?: ChannelContext; + + constructor(protected _version: V2, payload: ChannelResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.attributes = (payload.attributes); + this.type = payload.type; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + this.membersCount = deserialize.integer(payload.members_count); + this.messagesCount = deserialize.integer(payload.messages_count); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Channel resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Channel resource is associated with. + */ + serviceSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\'s `sid` in the URL. + */ + uniqueName: string; + /** + * The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + */ + attributes: string; + type: ChannelChannelType; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. + */ + createdBy: string; + /** + * The number of Members in the Channel. + */ + membersCount: number; + /** + * The number of Messages that have been passed in the Channel. + */ + messagesCount: number; + /** + * The absolute URL of the Channel resource. + */ + url: string; + /** + * The absolute URLs of the [Members](https://www.twilio.com/docs/chat/rest/member-resource), [Messages](https://www.twilio.com/docs/chat/rest/message-resource), [Invites](https://www.twilio.com/docs/chat/rest/invite-resource), Webhooks and, if it exists, the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) for the Channel. + */ + links: Record; + + private get _proxy(): ChannelContext { + this._context = this._context || new ChannelContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + remove(params: ChannelContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + removeWithHttpInfo(params: ChannelContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Update a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the invites. + */ + invites(): InviteListInstance { + return this._proxy.invites; + } + + /** + * Access the members. + */ + members(): MemberListInstance { + return this._proxy.members; + } + + /** + * Access the messages. + */ + messages(): MessageListInstance { + return this._proxy.messages; + } + + /** + * Access the webhooks. + */ + webhooks(): WebhookListInstance { + return this._proxy.webhooks; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + attributes: this.attributes, + type: this.type, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + membersCount: this.membersCount, + messagesCount: this.messagesCount, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ChannelSolution { + serviceSid: string; +} + +export interface ChannelListInstance { + _version: V2; + _solution: ChannelSolution; + _uri: string; + + (sid: string, ): ChannelContext; + get(sid: string, ): ChannelContext; + + + + + + + + + /** + * Create a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + create(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Create a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + create(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + /** + * Create a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + createWithHttpInfo(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + each(params: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise; + /** + * Retrieve a single target page of ChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise; + list(params: ChannelListInstanceOptions, callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise; + /** + * Lists ChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ChannelPage) => any): Promise; + page(params: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ChannelPage) => any): Promise; + /** + * Retrieve a single page of ChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChannelListInstance(version: V2, serviceSid: string): ChannelListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ChannelListInstance; + + instance.get = function get(sid, ): ChannelContext { + return new ChannelContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Channels`; + + instance.create = function create(params?: ChannelListInstanceCreateOptions | ((error: Error | null, items: ChannelInstance) => any), callback?: (error: Error | null, items: ChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["createdBy"] !== undefined) + data["CreatedBy"] = params["createdBy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ChannelListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["createdBy"] !== undefined) + data["CreatedBy"] = params["createdBy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ChannelListInstancePageOptions | ((error: Error | null, items: ChannelPage) => any), callback?: (error: Error | null, items: ChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["type"] !== undefined) + data["Type"] = serialize.map(params["type"], (e: ChannelChannelType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["type"] !== undefined) + data["Type"] = serialize.map(params["type"], (e: ChannelChannelType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ChannelPage extends Page { +/** +* Initialize the ChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: ChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChannelResource): ChannelInstance { + + return new ChannelInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service/channel/invite.ts b/rest/chat/v2/service/channel/invite.ts new file mode 100644 index 000000000..0fdd27a04 --- /dev/null +++ b/rest/chat/v2/service/channel/invite.ts @@ -0,0 +1,794 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a InviteInstance + */ +export interface InviteListInstanceCreateOptions { + /** The `identity` value that uniquely identifies the new resource\\\'s [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. */ + "identity": string; + /** The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. */ + "roleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface InviteListInstanceEachOptions { + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InviteInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InviteListInstanceOptions { + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InviteListInstancePageOptions { + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InviteContext { + + /** + * Remove a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise + + /** + * Fetch a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InviteContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class InviteContextImpl implements InviteContext { + protected _solution: InviteContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Invites/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InviteInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new InviteInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InvitePayload extends TwilioResponsePayload { + invites: InviteResource[]; +} + +interface InviteResource { + sid: string; + account_sid: string; + channel_sid: string; + service_sid: string; + identity: string; + date_created: Date; + date_updated: Date; + role_sid: string; + created_by: string; + url: string; +} + +export class InviteInstance { + protected _solution: InviteContextSolution; + protected _context?: InviteContext; + + constructor(protected _version: V2, payload: InviteResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.channelSid = (payload.channel_sid); + this.serviceSid = (payload.service_sid); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.roleSid = (payload.role_sid); + this.createdBy = (payload.created_by); + this.url = (payload.url); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Invite resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Invite resource. + */ + accountSid: string; + /** + * The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Invite resource belongs to. + */ + channelSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Invite resource is associated with. + */ + serviceSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + */ + identity: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the resource. + */ + roleSid: string; + /** + * The `identity` of the User that created the invite. + */ + createdBy: string; + /** + * The absolute URL of the Invite resource. + */ + url: string; + + private get _proxy(): InviteContext { + this._context = this._context || new InviteContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + channelSid: this.channelSid, + serviceSid: this.serviceSid, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + roleSid: this.roleSid, + createdBy: this.createdBy, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InviteSolution { + serviceSid: string; + channelSid: string; +} + +export interface InviteListInstance { + _version: V2; + _solution: InviteSolution; + _uri: string; + + (sid: string, ): InviteContext; + get(sid: string, ): InviteContext; + + + + + + + /** + * Create a InviteInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + create(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, item?: InviteInstance) => any): Promise; + + /** + * Create a InviteInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + createWithHttpInfo(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams InviteInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + each(params: InviteListInstanceEachOptions, callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InviteInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InviteListInstanceEachOptions, callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InviteInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InvitePage) => any): Promise; + /** + * Retrieve a single target page of InviteInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InviteInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InviteInstance[]) => any): Promise; + list(params: InviteListInstanceOptions, callback?: (error: Error | null, items: InviteInstance[]) => any): Promise; + /** + * Lists InviteInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InviteListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InviteInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InvitePage) => any): Promise; + page(params: InviteListInstancePageOptions, callback?: (error: Error | null, items: InvitePage) => any): Promise; + /** + * Retrieve a single page of InviteInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InviteListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InviteListInstance(version: V2, serviceSid: string, channelSid: string): InviteListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as InviteListInstance; + + instance.get = function get(sid, ): InviteContext { + return new InviteContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Invites`; + + instance.create = function create(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, items: InviteInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InviteInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InviteInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InviteListInstancePageOptions | ((error: Error | null, items: InvitePage) => any), callback?: (error: Error | null, items: InvitePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InvitePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InvitePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InvitePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InviteListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InvitePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InvitePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InvitePage extends Page { +/** +* Initialize the InvitePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: InviteSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InviteInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InviteResource): InviteInstance { + + return new InviteInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service/channel/member.ts b/rest/chat/v2/service/channel/member.ts new file mode 100644 index 000000000..37486b78c --- /dev/null +++ b/rest/chat/v2/service/channel/member.ts @@ -0,0 +1,1114 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type MemberWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a MemberInstance + */ +export interface MemberContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MemberWebhookEnabledType; +} + + +/** + * Options to pass to update a MemberInstance + */ +export interface MemberContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MemberWebhookEnabledType; + /** The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). */ + "roleSid"?: string; + /** The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). */ + "lastConsumedMessageIndex"?: number; + /** The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). */ + "lastConsumptionTimestamp"?: Date; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. */ + "dateCreated"?: Date; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. */ + "dateUpdated"?: Date; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; +} + +/** + * Options to pass to create a MemberInstance + */ +export interface MemberListInstanceCreateOptions { + /** The `identity` value that uniquely identifies the new resource\\\'s [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. */ + "identity": string; + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MemberWebhookEnabledType; + /** The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). */ + "roleSid"?: string; + /** The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. This parameter should only be used when recreating a Member from a backup/separate source. */ + "lastConsumedMessageIndex"?: number; + /** The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). */ + "lastConsumptionTimestamp"?: Date; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. */ + "dateCreated"?: Date; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. */ + "dateUpdated"?: Date; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; +} + +/** + * Options to pass to each + */ +export interface MemberListInstanceEachOptions { + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MemberInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MemberListInstanceOptions { + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MemberListInstancePageOptions { + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MemberContext { + + /** + * Remove a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + remove(params: MemberContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + removeWithHttpInfo(params: MemberContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise + + /** + * Fetch a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + /** + * Update a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + /** + * Update a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MemberContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class MemberContextImpl implements MemberContext { + protected _solution: MemberContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Members/${sid}`; + } + + remove(params?: MemberContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: MemberContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MemberContextUpdateOptions | ((error: Error | null, item?: MemberInstance) => any),callback?: (error: Error | null, item?: MemberInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MemberContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MemberPayload extends TwilioResponsePayload { + members: MemberResource[]; +} + +interface MemberResource { + sid: string; + account_sid: string; + channel_sid: string; + service_sid: string; + identity: string; + date_created: Date; + date_updated: Date; + role_sid: string; + last_consumed_message_index: number; + last_consumption_timestamp: Date; + url: string; + attributes: string; +} + +export class MemberInstance { + protected _solution: MemberContextSolution; + protected _context?: MemberContext; + + constructor(protected _version: V2, payload: MemberResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.channelSid = (payload.channel_sid); + this.serviceSid = (payload.service_sid); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.roleSid = (payload.role_sid); + this.lastConsumedMessageIndex = deserialize.integer(payload.last_consumed_message_index); + this.lastConsumptionTimestamp = deserialize.iso8601DateTime(payload.last_consumption_timestamp); + this.url = (payload.url); + this.attributes = (payload.attributes); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Member resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Member resource. + */ + accountSid: string; + /** + * The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Member resource belongs to. + */ + channelSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Member resource is associated with. + */ + serviceSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + */ + identity: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the member. + */ + roleSid: string; + /** + * The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + */ + lastConsumedMessageIndex: number; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + */ + lastConsumptionTimestamp: Date; + /** + * The absolute URL of the Member resource. + */ + url: string; + /** + * The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + */ + attributes: string; + + private get _proxy(): MemberContext { + this._context = this._context || new MemberContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + remove(params: MemberContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + removeWithHttpInfo(params: MemberContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + /** + * Update a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MemberInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + channelSid: this.channelSid, + serviceSid: this.serviceSid, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + roleSid: this.roleSid, + lastConsumedMessageIndex: this.lastConsumedMessageIndex, + lastConsumptionTimestamp: this.lastConsumptionTimestamp, + url: this.url, + attributes: this.attributes, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MemberSolution { + serviceSid: string; + channelSid: string; +} + +export interface MemberListInstance { + _version: V2; + _solution: MemberSolution; + _uri: string; + + (sid: string, ): MemberContext; + get(sid: string, ): MemberContext; + + + + + + + + + /** + * Create a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + create(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + /** + * Create a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + createWithHttpInfo(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MemberInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + each(params: MemberListInstanceEachOptions, callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MemberInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MemberListInstanceEachOptions, callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MemberInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MemberPage) => any): Promise; + /** + * Retrieve a single target page of MemberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MemberInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MemberInstance[]) => any): Promise; + list(params: MemberListInstanceOptions, callback?: (error: Error | null, items: MemberInstance[]) => any): Promise; + /** + * Lists MemberInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MemberListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MemberInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MemberPage) => any): Promise; + page(params: MemberListInstancePageOptions, callback?: (error: Error | null, items: MemberPage) => any): Promise; + /** + * Retrieve a single page of MemberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MemberListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MemberListInstance(version: V2, serviceSid: string, channelSid: string): MemberListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MemberListInstance; + + instance.get = function get(sid, ): MemberContext { + return new MemberContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Members`; + + instance.create = function create(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, items: MemberInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MemberListInstancePageOptions | ((error: Error | null, items: MemberPage) => any), callback?: (error: Error | null, items: MemberPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MemberPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MemberPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MemberPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MemberListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MemberPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MemberPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MemberPage extends Page { +/** +* Initialize the MemberPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: MemberSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MemberInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MemberResource): MemberInstance { + + return new MemberInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service/channel/message.ts b/rest/chat/v2/service/channel/message.ts new file mode 100644 index 000000000..56bffc2c7 --- /dev/null +++ b/rest/chat/v2/service/channel/message.ts @@ -0,0 +1,1158 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type MessageOrderType = 'asc'|'desc'; + +export type MessageWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a MessageInstance + */ +export interface MessageContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; +} + + +/** + * Options to pass to update a MessageInstance + */ +export interface MessageContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; + /** The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. */ + "body"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat\\\'s history is being recreated from a backup/separate source. */ + "dateCreated"?: Date; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. */ + "dateUpdated"?: Date; + /** The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. */ + "lastUpdatedBy"?: string; + /** The [Identity](https://www.twilio.com/docs/chat/identity) of the message\\\'s author. */ + "from"?: string; +} + +/** + * Options to pass to create a MessageInstance + */ +export interface MessageListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; + /** The [Identity](https://www.twilio.com/docs/chat/identity) of the new message\\\'s author. The default value is `system`. */ + "from"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat\\\'s history is being recreated from a backup/separate source. */ + "dateCreated"?: Date; + /** The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. */ + "dateUpdated"?: Date; + /** The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. */ + "lastUpdatedBy"?: string; + /** The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. */ + "body"?: string; + /** The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. */ + "mediaSid"?: string; +} + +/** + * Options to pass to each + */ +export interface MessageListInstanceEachOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MessageInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MessageListInstanceOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MessageListInstancePageOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MessageContext { + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + remove(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + removeWithHttpInfo(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MessageContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class MessageContextImpl implements MessageContext { + protected _solution: MessageContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Messages/${sid}`; + } + + remove(params?: MessageContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: MessageContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MessageContextUpdateOptions | ((error: Error | null, item?: MessageInstance) => any),callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["lastUpdatedBy"] !== undefined) + data["LastUpdatedBy"] = params["lastUpdatedBy"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MessageContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["lastUpdatedBy"] !== undefined) + data["LastUpdatedBy"] = params["lastUpdatedBy"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MessagePayload extends TwilioResponsePayload { + messages: MessageResource[]; +} + +interface MessageResource { + sid: string; + account_sid: string; + attributes: string; + service_sid: string; + to: string; + channel_sid: string; + date_created: Date; + date_updated: Date; + last_updated_by: string; + was_edited: boolean; + from: string; + body: string; + index: number; + type: string; + media: any; + url: string; +} + +export class MessageInstance { + protected _solution: MessageContextSolution; + protected _context?: MessageContext; + + constructor(protected _version: V2, payload: MessageResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.attributes = (payload.attributes); + this.serviceSid = (payload.service_sid); + this.to = (payload.to); + this.channelSid = (payload.channel_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.lastUpdatedBy = (payload.last_updated_by); + this.wasEdited = (payload.was_edited); + this.from = (payload.from); + this.body = (payload.body); + this.index = deserialize.integer(payload.index); + this.type = (payload.type); + this.media = (payload.media); + this.url = (payload.url); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Message resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Message resource. + */ + accountSid: string; + /** + * The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + */ + attributes: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Message resource is associated with. + */ + serviceSid: string; + /** + * The SID of the [Channel](https://www.twilio.com/docs/chat/channels) that the message was sent to. + */ + to: string; + /** + * The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Message resource belongs to. + */ + channelSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + */ + lastUpdatedBy: string; + /** + * Whether the message has been edited since it was created. + */ + wasEdited: boolean; + /** + * The [Identity](https://www.twilio.com/docs/chat/identity) of the message\'s author. The default value is `system`. + */ + from: string; + /** + * The content of the message. + */ + body: string; + /** + * The index of the message within the [Channel](https://www.twilio.com/docs/chat/channels). Indices may skip numbers, but will always be in order of when the message was received. + */ + index: number; + /** + * The Message type. Can be: `text` or `media`. + */ + type: string; + /** + * An object that describes the Message\'s media, if the message contains media. The object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object\'s file size in bytes. If the Message has no media, this value is `null`. + */ + media: any; + /** + * The absolute URL of the Message resource. + */ + url: string; + + private get _proxy(): MessageContext { + this._context = this._context || new MessageContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + remove(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + removeWithHttpInfo(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MessageInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + attributes: this.attributes, + serviceSid: this.serviceSid, + to: this.to, + channelSid: this.channelSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + lastUpdatedBy: this.lastUpdatedBy, + wasEdited: this.wasEdited, + from: this.from, + body: this.body, + index: this.index, + type: this.type, + media: this.media, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MessageSolution { + serviceSid: string; + channelSid: string; +} + +export interface MessageListInstance { + _version: V2; + _solution: MessageSolution; + _uri: string; + + (sid: string, ): MessageContext; + get(sid: string, ): MessageContext; + + + + + + + + + /** + * Create a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Create a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Create a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MessageInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + each(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MessageInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single target page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MessageInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + list(params: MessageListInstanceOptions, callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + /** + * Lists MessageInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MessageListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MessagePage) => any): Promise; + page(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessageListInstance(version: V2, serviceSid: string, channelSid: string): MessageListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MessageListInstance; + + instance.get = function get(sid, ): MessageContext { + return new MessageContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Messages`; + + instance.create = function create(params?: MessageListInstanceCreateOptions | ((error: Error | null, items: MessageInstance) => any), callback?: (error: Error | null, items: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["lastUpdatedBy"] !== undefined) + data["LastUpdatedBy"] = params["lastUpdatedBy"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["mediaSid"] !== undefined) + data["MediaSid"] = params["mediaSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: MessageListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["lastUpdatedBy"] !== undefined) + data["LastUpdatedBy"] = params["lastUpdatedBy"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["mediaSid"] !== undefined) + data["MediaSid"] = params["mediaSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MessageListInstancePageOptions | ((error: Error | null, items: MessagePage) => any), callback?: (error: Error | null, items: MessagePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MessagePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MessagePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MessageListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MessagePage extends Page { +/** +* Initialize the MessagePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: MessageSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MessageInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MessageResource): MessageInstance { + + return new MessageInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service/channel/webhook.ts b/rest/chat/v2/service/channel/webhook.ts new file mode 100644 index 000000000..9449fbdcd --- /dev/null +++ b/rest/chat/v2/service/channel/webhook.ts @@ -0,0 +1,1005 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type WebhookMethod = 'GET'|'POST'; + +/** + * The type of webhook. Can be: `webhook`, `studio`, or `trigger`. + */ +export type WebhookType = 'webhook'|'trigger'|'studio'; + + + + +/** + * Options to pass to update a WebhookInstance + */ +export interface WebhookContextUpdateOptions { + /** The URL of the webhook to call using the `configuration.method`. */ + "configuration.url"?: string; + /** */ + "configuration.method"?: WebhookMethod; + /** The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). */ + "configuration.filters"?: Array; + /** A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. */ + "configuration.triggers"?: Array; + /** The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. */ + "configuration.flowSid"?: string; + /** The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. */ + "configuration.retryCount"?: number; +} + +/** + * Options to pass to create a WebhookInstance + */ +export interface WebhookListInstanceCreateOptions { + /** */ + "type": WebhookType; + /** The URL of the webhook to call using the `configuration.method`. */ + "configuration.url"?: string; + /** */ + "configuration.method"?: WebhookMethod; + /** The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). */ + "configuration.filters"?: Array; + /** A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. */ + "configuration.triggers"?: Array; + /** The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. */ + "configuration.flowSid"?: string; + /** The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. */ + "configuration.retryCount"?: number; +} + +/** + * Options to pass to each + */ +export interface WebhookListInstanceEachOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: WebhookInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface WebhookListInstanceOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface WebhookListInstancePageOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface WebhookContext { + + /** + * Remove a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WebhookContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class WebhookContextImpl implements WebhookContext { + protected _solution: WebhookContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Webhooks/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: WebhookInstance) => any),callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.retryCount"] !== undefined) + data["Configuration.RetryCount"] = params["configuration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.retryCount"] !== undefined) + data["Configuration.RetryCount"] = params["configuration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WebhookPayload extends TwilioResponsePayload { + webhooks: WebhookResource[]; +} + +interface WebhookResource { + sid: string; + account_sid: string; + service_sid: string; + channel_sid: string; + type: string; + url: string; + configuration: any; + date_created: Date; + date_updated: Date; +} + +export class WebhookInstance { + protected _solution: WebhookContextSolution; + protected _context?: WebhookContext; + + constructor(protected _version: V2, payload: WebhookResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.channelSid = (payload.channel_sid); + this.type = (payload.type); + this.url = (payload.url); + this.configuration = (payload.configuration); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Channel Webhook resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel Webhook resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Channel Webhook resource is associated with. + */ + serviceSid: string; + /** + * The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Channel Webhook resource belongs to. + */ + channelSid: string; + /** + * The type of webhook. Can be: `webhook`, `studio`, or `trigger`. + */ + type: string; + /** + * The absolute URL of the Channel Webhook resource. + */ + url: string; + /** + * The JSON string that describes how the channel webhook is configured. The configuration object contains the `url`, `method`, `filters`, and `retry_count` values that are configured by the create and update actions. + */ + configuration: any; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + private get _proxy(): WebhookContext { + this._context = this._context || new WebhookContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + channelSid: this.channelSid, + type: this.type, + url: this.url, + configuration: this.configuration, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WebhookSolution { + serviceSid: string; + channelSid: string; +} + +export interface WebhookListInstance { + _version: V2; + _solution: WebhookSolution; + _uri: string; + + (sid: string, ): WebhookContext; + get(sid: string, ): WebhookContext; + + + + + + + + + /** + * Create a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + create(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + /** + * Create a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + createWithHttpInfo(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams WebhookInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + each(params: WebhookListInstanceEachOptions, callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + /** + * Streams WebhookInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: WebhookListInstanceEachOptions, callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of WebhookInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: WebhookPage) => any): Promise; + /** + * Retrieve a single target page of WebhookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists WebhookInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: WebhookInstance[]) => any): Promise; + list(params: WebhookListInstanceOptions, callback?: (error: Error | null, items: WebhookInstance[]) => any): Promise; + /** + * Lists WebhookInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: WebhookListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of WebhookInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: WebhookPage) => any): Promise; + page(params: WebhookListInstancePageOptions, callback?: (error: Error | null, items: WebhookPage) => any): Promise; + /** + * Retrieve a single page of WebhookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: WebhookListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WebhookListInstance(version: V2, serviceSid: string, channelSid: string): WebhookListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as WebhookListInstance; + + instance.get = function get(sid, ): WebhookContext { + return new WebhookContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Webhooks`; + + instance.create = function create(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, items: WebhookInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.retryCount"] !== undefined) + data["Configuration.RetryCount"] = params["configuration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.retryCount"] !== undefined) + data["Configuration.RetryCount"] = params["configuration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: WebhookListInstancePageOptions | ((error: Error | null, items: WebhookPage) => any), callback?: (error: Error | null, items: WebhookPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new WebhookPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: WebhookPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new WebhookPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: WebhookListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebhookPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebhookPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class WebhookPage extends Page { +/** +* Initialize the WebhookPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: WebhookSolution) { + super(version, response, solution); + } + + /** + * Build an instance of WebhookInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: WebhookResource): WebhookInstance { + + return new WebhookInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service/role.ts b/rest/chat/v2/service/role.ts new file mode 100644 index 000000000..f5cfde492 --- /dev/null +++ b/rest/chat/v2/service/role.ts @@ -0,0 +1,921 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The type of role. Can be: `channel` for [Channel](https://www.twilio.com/docs/chat/channels) roles or `deployment` for [Service](https://www.twilio.com/docs/chat/rest/service-resource) roles. + */ +export type RoleRoleType = 'channel'|'deployment'; + + + + +/** + * Options to pass to update a RoleInstance + */ +export interface RoleContextUpdateOptions { + /** A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role\\\'s `type`. */ + "permission": Array; +} + +/** + * Options to pass to create a RoleInstance + */ +export interface RoleListInstanceCreateOptions { + /** A descriptive string that you create to describe the new resource. It can be up to 64 characters long. */ + "friendlyName": string; + /** */ + "type": RoleRoleType; + /** A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role\\\'s `type`. */ + "permission": Array; +} + +/** + * Options to pass to each + */ +export interface RoleListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoleInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoleListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoleListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoleContext { + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoleContextSolution { + "serviceSid": string; + "sid": string; +} + +export class RoleContextImpl implements RoleContext { + protected _solution: RoleContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Roles/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RolePayload extends TwilioResponsePayload { + roles: RoleResource[]; +} + +interface RoleResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + type: RoleRoleType; + permissions: Array; + date_created: Date; + date_updated: Date; + url: string; +} + +export class RoleInstance { + protected _solution: RoleContextSolution; + protected _context?: RoleContext; + + constructor(protected _version: V2, payload: RoleResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.permissions = (payload.permissions); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Role resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Role resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Role resource is associated with. + */ + serviceSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + type: RoleRoleType; + /** + * An array of the permissions the role has been granted. + */ + permissions: Array; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Role resource. + */ + url: string; + + private get _proxy(): RoleContext { + this._context = this._context || new RoleContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: RoleInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + type: this.type, + permissions: this.permissions, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoleSolution { + serviceSid: string; +} + +export interface RoleListInstance { + _version: V2; + _solution: RoleSolution; + _uri: string; + + (sid: string, ): RoleContext; + get(sid: string, ): RoleContext; + + + + + + + + + /** + * Create a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Create a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams RoleInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + each(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoleInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single target page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RoleInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + list(params: RoleListInstanceOptions, callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + /** + * Lists RoleInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RoleListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RolePage) => any): Promise; + page(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoleListInstance(version: V2, serviceSid: string): RoleListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RoleListInstance; + + instance.get = function get(sid, ): RoleContext { + return new RoleContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Roles`; + + instance.create = function create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RoleListInstancePageOptions | ((error: Error | null, items: RolePage) => any), callback?: (error: Error | null, items: RolePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RolePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RolePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoleListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RolePage extends Page { +/** +* Initialize the RolePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: RoleSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoleInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoleResource): RoleInstance { + + return new RoleInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service/user.ts b/rest/chat/v2/service/user.ts new file mode 100644 index 000000000..80596f91e --- /dev/null +++ b/rest/chat/v2/service/user.ts @@ -0,0 +1,1026 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { UserBindingListInstance } from "./user/userBinding"; +import { UserChannelListInstance } from "./user/userChannel"; + + +export type UserWebhookEnabledType = 'true'|'false'; + + + + +/** + * Options to pass to update a UserInstance + */ +export interface UserContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserWebhookEnabledType; + /** The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. */ + "roleSid"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; + /** A descriptive string that you create to describe the resource. It is often used for display purposes. */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a UserInstance + */ +export interface UserListInstanceCreateOptions { + /** The `identity` value that uniquely identifies the new resource\\\'s [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. */ + "identity": string; + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserWebhookEnabledType; + /** The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the new User. */ + "roleSid"?: string; + /** A valid JSON string that contains application-specific data. */ + "attributes"?: string; + /** A descriptive string that you create to describe the new resource. This value is often used for display purposes. */ + "friendlyName"?: string; +} + +/** + * Options to pass to each + */ +export interface UserListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserContext { + userBindings: UserBindingListInstance; + userChannels: UserChannelListInstance; + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserContextSolution { + "serviceSid": string; + "sid": string; +} + +export class UserContextImpl implements UserContext { + protected _solution: UserContextSolution; + protected _uri: string; + + protected _userBindings?: UserBindingListInstance; + protected _userChannels?: UserChannelListInstance; + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Users/${sid}`; + } + + get userBindings(): UserBindingListInstance { + this._userBindings = this._userBindings || UserBindingListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._userBindings; + } + + get userChannels(): UserChannelListInstance { + this._userChannels = this._userChannels || UserChannelListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._userChannels; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserContextUpdateOptions | ((error: Error | null, item?: UserInstance) => any),callback?: (error: Error | null, item?: UserInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserPayload extends TwilioResponsePayload { + users: UserResource[]; +} + +interface UserResource { + sid: string; + account_sid: string; + service_sid: string; + attributes: string; + friendly_name: string; + role_sid: string; + identity: string; + is_online: boolean; + is_notifiable: boolean; + date_created: Date; + date_updated: Date; + joined_channels_count: number; + links: Record; + url: string; +} + +export class UserInstance { + protected _solution: UserContextSolution; + protected _context?: UserContext; + + constructor(protected _version: V2, payload: UserResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.attributes = (payload.attributes); + this.friendlyName = (payload.friendly_name); + this.roleSid = (payload.role_sid); + this.identity = (payload.identity); + this.isOnline = (payload.is_online); + this.isNotifiable = (payload.is_notifiable); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.joinedChannelsCount = deserialize.integer(payload.joined_channels_count); + this.links = (payload.links); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the User resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User resource is associated with. + */ + serviceSid: string; + /** + * The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + */ + attributes: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the user. + */ + roleSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s User within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or an email address, and is case-sensitive. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + */ + identity: string; + /** + * Whether the User is actively connected to the Service instance and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service\'s `reachability_enabled` is `false`, if the User has never been online for the Service instance, even if the Service\'s `reachability_enabled` is `true`. + */ + isOnline: boolean; + /** + * Whether the User has a potentially valid Push Notification registration (APN or GCM) for the Service instance. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service\'s `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service\'s `reachability_enabled` is `true`. + */ + isNotifiable: boolean; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The number of Channels the User is a Member of. + */ + joinedChannelsCount: number; + /** + * The absolute URLs of the [Channel](https://www.twilio.com/docs/chat/channels) and [Binding](https://www.twilio.com/docs/chat/rest/binding-resource) resources related to the user. + */ + links: Record; + /** + * The absolute URL of the User resource. + */ + url: string; + + private get _proxy(): UserContext { + this._context = this._context || new UserContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the userBindings. + */ + userBindings(): UserBindingListInstance { + return this._proxy.userBindings; + } + + /** + * Access the userChannels. + */ + userChannels(): UserChannelListInstance { + return this._proxy.userChannels; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + attributes: this.attributes, + friendlyName: this.friendlyName, + roleSid: this.roleSid, + identity: this.identity, + isOnline: this.isOnline, + isNotifiable: this.isNotifiable, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + joinedChannelsCount: this.joinedChannelsCount, + links: this.links, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserSolution { + serviceSid: string; +} + +export interface UserListInstance { + _version: V2; + _solution: UserSolution; + _uri: string; + + (sid: string, ): UserContext; + get(sid: string, ): UserContext; + + + + + + + + + /** + * Create a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Create a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams UserInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + each(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single target page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + list(params: UserListInstanceOptions, callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + /** + * Lists UserInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserPage) => any): Promise; + page(params: UserListInstancePageOptions, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserListInstance(version: V2, serviceSid: string): UserListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as UserListInstance; + + instance.get = function get(sid, ): UserContext { + return new UserContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Users`; + + instance.create = function create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: UserInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: UserListInstancePageOptions | ((error: Error | null, items: UserPage) => any), callback?: (error: Error | null, items: UserPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserPage extends Page { +/** +* Initialize the UserPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: UserSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserResource): UserInstance { + + return new UserInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service/user/userBinding.ts b/rest/chat/v2/service/user/userBinding.ts new file mode 100644 index 000000000..a2e35b65c --- /dev/null +++ b/rest/chat/v2/service/user/userBinding.ts @@ -0,0 +1,705 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The push technology to use for the User Binding. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + */ +export type UserBindingBindingType = 'gcm'|'apn'|'fcm'; + + + + +/** + * Options to pass to each + */ +export interface UserBindingListInstanceEachOptions { + /** The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. */ + "bindingType"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserBindingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserBindingListInstanceOptions { + /** The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. */ + "bindingType"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserBindingListInstancePageOptions { + /** The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. */ + "bindingType"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserBindingContext { + + /** + * Remove a UserBindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a UserBindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a UserBindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserBindingInstance + */ + fetch(callback?: (error: Error | null, item?: UserBindingInstance) => any): Promise + + /** + * Fetch a UserBindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserBindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserBindingContextSolution { + "serviceSid": string; + "userSid": string; + "sid": string; +} + +export class UserBindingContextImpl implements UserBindingContext { + protected _solution: UserBindingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, userSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, userSid, sid, }; + this._uri = `/Services/${serviceSid}/Users/${userSid}/Bindings/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserBindingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserBindingInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.userSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserBindingInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.userSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserBindingPayload extends TwilioResponsePayload { + bindings: UserBindingResource[]; +} + +interface UserBindingResource { + sid: string; + account_sid: string; + service_sid: string; + date_created: Date; + date_updated: Date; + endpoint: string; + identity: string; + user_sid: string; + credential_sid: string; + binding_type: UserBindingBindingType; + message_types: Array; + url: string; +} + +export class UserBindingInstance { + protected _solution: UserBindingContextSolution; + protected _context?: UserBindingContext; + + constructor(protected _version: V2, payload: UserBindingResource, serviceSid: string, userSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.endpoint = (payload.endpoint); + this.identity = (payload.identity); + this.userSid = (payload.user_sid); + this.credentialSid = (payload.credential_sid); + this.bindingType = payload.binding_type; + this.messageTypes = (payload.message_types); + this.url = (payload.url); + + this._solution = { serviceSid, userSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the User Binding resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User Binding resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User Binding resource is associated with. + */ + serviceSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The unique endpoint identifier for the User Binding. The format of the value depends on the `binding_type`. + */ + endpoint: string; + /** + * The application-defined string that uniquely identifies the resource\'s [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + */ + identity: string; + /** + * The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) with the User Binding resource. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + */ + userSid: string; + /** + * The SID of the [Credential](https://www.twilio.com/docs/chat/rest/credential-resource) for the binding. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + */ + credentialSid: string; + bindingType: UserBindingBindingType; + /** + * The [Programmable Chat message types](https://www.twilio.com/docs/chat/push-notification-configuration#push-types) the binding is subscribed to. + */ + messageTypes: Array; + /** + * The absolute URL of the User Binding resource. + */ + url: string; + + private get _proxy(): UserBindingContext { + this._context = this._context || new UserBindingContextImpl(this._version, this._solution.serviceSid, this._solution.userSid, this._solution.sid); + return this._context; + } + + /** + * Remove a UserBindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserBindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserBindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserBindingInstance + */ + fetch(callback?: (error: Error | null, item?: UserBindingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserBindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserBindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + endpoint: this.endpoint, + identity: this.identity, + userSid: this.userSid, + credentialSid: this.credentialSid, + bindingType: this.bindingType, + messageTypes: this.messageTypes, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserBindingSolution { + serviceSid: string; + userSid: string; +} + +export interface UserBindingListInstance { + _version: V2; + _solution: UserBindingSolution; + _uri: string; + + (sid: string, ): UserBindingContext; + get(sid: string, ): UserBindingContext; + + + + + + + + /** + * Streams UserBindingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserBindingInstance, done: (err?: Error) => void) => void): void; + each(params: UserBindingListInstanceEachOptions, callback?: (item: UserBindingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserBindingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserBindingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserBindingListInstanceEachOptions, callback?: (item: UserBindingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserBindingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserBindingPage) => any): Promise; + /** + * Retrieve a single target page of UserBindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserBindingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserBindingInstance[]) => any): Promise; + list(params: UserBindingListInstanceOptions, callback?: (error: Error | null, items: UserBindingInstance[]) => any): Promise; + /** + * Lists UserBindingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserBindingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserBindingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserBindingPage) => any): Promise; + page(params: UserBindingListInstancePageOptions, callback?: (error: Error | null, items: UserBindingPage) => any): Promise; + /** + * Retrieve a single page of UserBindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserBindingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserBindingListInstance(version: V2, serviceSid: string, userSid: string): UserBindingListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as UserBindingListInstance; + + instance.get = function get(sid, ): UserBindingContext { + return new UserBindingContextImpl(version, serviceSid, userSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, userSid, }; + instance._uri = `/Services/${serviceSid}/Users/${userSid}/Bindings`; + + instance.page = function page(params?: UserBindingListInstancePageOptions | ((error: Error | null, items: UserBindingPage) => any), callback?: (error: Error | null, items: UserBindingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["bindingType"] !== undefined) + data["BindingType"] = serialize.map(params["bindingType"], (e: UserBindingBindingType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserBindingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserBindingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserBindingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserBindingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["bindingType"] !== undefined) + data["BindingType"] = serialize.map(params["bindingType"], (e: UserBindingBindingType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserBindingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserBindingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserBindingPage extends Page { +/** +* Initialize the UserBindingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: UserBindingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserBindingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserBindingResource): UserBindingInstance { + + return new UserBindingInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.userSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v2/service/user/userChannel.ts b/rest/chat/v2/service/user/userChannel.ts new file mode 100644 index 000000000..6a9b4aa12 --- /dev/null +++ b/rest/chat/v2/service/user/userChannel.ts @@ -0,0 +1,940 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The status of the User on the Channel. Can be: `joined`, `invited`, or `notParticipating`. + */ +export type UserChannelChannelStatus = 'joined'|'invited'|'notParticipating'; + +/** + * The push notification level of the User for the Channel. Can be: `default` or `muted`. + */ +export type UserChannelNotificationLevel = 'default'|'muted'; + +export type UserChannelWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a UserChannelInstance + */ +export interface UserChannelContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserChannelWebhookEnabledType; +} + + +/** + * Options to pass to update a UserChannelInstance + */ +export interface UserChannelContextUpdateOptions { + /** */ + "notificationLevel"?: UserChannelNotificationLevel; + /** The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. */ + "lastConsumedMessageIndex"?: number; + /** The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). */ + "lastConsumptionTimestamp"?: Date; +} + +/** + * Options to pass to each + */ +export interface UserChannelListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserChannelListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserChannelListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserChannelContext { + + /** + * Remove a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a UserChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + remove(params: UserChannelContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a UserChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + removeWithHttpInfo(params: UserChannelContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + fetch(callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise + + /** + * Fetch a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + update(callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise; + /** + * Update a UserChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + update(params: UserChannelContextUpdateOptions, callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise; + + /** + * Update a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserChannelContextSolution { + "serviceSid": string; + "userSid": string; + "channelSid": string; +} + +export class UserChannelContextImpl implements UserChannelContext { + protected _solution: UserChannelContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, userSid: string, channelSid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + this._solution = { serviceSid, userSid, channelSid, }; + this._uri = `/Services/${serviceSid}/Users/${userSid}/Channels/${channelSid}`; + } + + remove(params?: UserChannelContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: UserChannelContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.userSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.userSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserChannelContextUpdateOptions | ((error: Error | null, item?: UserChannelInstance) => any),callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["notificationLevel"] !== undefined) + data["NotificationLevel"] = params["notificationLevel"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.userSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserChannelContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["notificationLevel"] !== undefined) + data["NotificationLevel"] = params["notificationLevel"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.userSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserChannelPayload extends TwilioResponsePayload { + channels: UserChannelResource[]; +} + +interface UserChannelResource { + account_sid: string; + service_sid: string; + channel_sid: string; + user_sid: string; + member_sid: string; + status: UserChannelChannelStatus; + last_consumed_message_index: number; + unread_messages_count: number; + links: Record; + url: string; + notification_level: UserChannelNotificationLevel; +} + +export class UserChannelInstance { + protected _solution: UserChannelContextSolution; + protected _context?: UserChannelContext; + + constructor(protected _version: V2, payload: UserChannelResource, serviceSid: string, userSid: string, channelSid?: string) { + + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.channelSid = (payload.channel_sid); + this.userSid = (payload.user_sid); + this.memberSid = (payload.member_sid); + this.status = payload.status; + this.lastConsumedMessageIndex = deserialize.integer(payload.last_consumed_message_index); + this.unreadMessagesCount = deserialize.integer(payload.unread_messages_count); + this.links = (payload.links); + this.url = (payload.url); + this.notificationLevel = payload.notification_level; + + this._solution = { serviceSid, userSid, channelSid: channelSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User Channel resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User Channel resource is associated with. + */ + serviceSid: string; + /** + * The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the User Channel resource belongs to. + */ + channelSid: string; + /** + * The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) the User Channel belongs to. + */ + userSid: string; + /** + * The SID of a [Member](https://www.twilio.com/docs/chat/rest/member-resource) that represents the User on the Channel. + */ + memberSid: string; + status: UserChannelChannelStatus; + /** + * The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + */ + lastConsumedMessageIndex: number; + /** + * The number of unread Messages in the Channel for the User. Note that retrieving messages on a client endpoint does not mean that messages are consumed or read. See [Consumption Horizon feature](https://www.twilio.com/docs/chat/consumption-horizon) to learn how to mark messages as consumed. + */ + unreadMessagesCount: number; + /** + * The absolute URLs of the [Members](https://www.twilio.com/docs/chat/rest/member-resource), [Messages](https://www.twilio.com/docs/chat/rest/message-resource) , [Invites](https://www.twilio.com/docs/chat/rest/invite-resource) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) for the Channel. + */ + links: Record; + /** + * The absolute URL of the User Channel resource. + */ + url: string; + notificationLevel: UserChannelNotificationLevel; + + private get _proxy(): UserChannelContext { + this._context = this._context || new UserChannelContextImpl(this._version, this._solution.serviceSid, this._solution.userSid, this._solution.channelSid); + return this._context; + } + + /** + * Remove a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a UserChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + remove(params: UserChannelContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a UserChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + removeWithHttpInfo(params: UserChannelContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + fetch(callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + update(callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise; + /** + * Update a UserChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + update(params: UserChannelContextUpdateOptions, callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + serviceSid: this.serviceSid, + channelSid: this.channelSid, + userSid: this.userSid, + memberSid: this.memberSid, + status: this.status, + lastConsumedMessageIndex: this.lastConsumedMessageIndex, + unreadMessagesCount: this.unreadMessagesCount, + links: this.links, + url: this.url, + notificationLevel: this.notificationLevel, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserChannelSolution { + serviceSid: string; + userSid: string; +} + +export interface UserChannelListInstance { + _version: V2; + _solution: UserChannelSolution; + _uri: string; + + (channelSid: string, ): UserChannelContext; + get(channelSid: string, ): UserChannelContext; + + + + + + + + + + /** + * Streams UserChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + each(params: UserChannelListInstanceEachOptions, callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserChannelListInstanceEachOptions, callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + /** + * Retrieve a single target page of UserChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserChannelInstance[]) => any): Promise; + list(params: UserChannelListInstanceOptions, callback?: (error: Error | null, items: UserChannelInstance[]) => any): Promise; + /** + * Lists UserChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + page(params: UserChannelListInstancePageOptions, callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + /** + * Retrieve a single page of UserChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserChannelListInstance(version: V2, serviceSid: string, userSid: string): UserChannelListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + const instance = ((channelSid, ) => instance.get(channelSid, )) as UserChannelListInstance; + + instance.get = function get(channelSid, ): UserChannelContext { + return new UserChannelContextImpl(version, serviceSid, userSid, channelSid); + } + + instance._version = version; + instance._solution = { serviceSid, userSid, }; + instance._uri = `/Services/${serviceSid}/Users/${userSid}/Channels`; + + instance.page = function page(params?: UserChannelListInstancePageOptions | ((error: Error | null, items: UserChannelPage) => any), callback?: (error: Error | null, items: UserChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserChannelPage extends Page { +/** +* Initialize the UserChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: UserChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserChannelResource): UserChannelInstance { + + return new UserChannelInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.userSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/chat/v3/channel.ts b/rest/chat/v3/channel.ts new file mode 100644 index 000000000..47f70b35f --- /dev/null +++ b/rest/chat/v3/channel.ts @@ -0,0 +1,423 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Chat + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The visibility of the channel. Can be: `public` or `private`. + */ +export type ChannelChannelType = 'public'|'private'; + +export type ChannelWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to update a ChannelInstance + */ +export interface ChannelContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ChannelWebhookEnabledType; + /** */ + "type"?: ChannelChannelType; + /** The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. */ + "messagingServiceSid"?: string; +} + +export interface ChannelContext { + + /** + * Update a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Update a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + /** + * Update a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ChannelContextSolution { + "serviceSid": string; + "sid": string; +} + +export class ChannelContextImpl implements ChannelContext { + protected _solution: ChannelContextSolution; + protected _uri: string; + + + constructor(protected _version: V3, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${sid}`; + } + + update(params?: ChannelContextUpdateOptions | ((error: Error | null, item?: ChannelInstance) => any),callback?: (error: Error | null, item?: ChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ChannelContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ChannelPayload extends ChannelResource {} + +interface ChannelResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + unique_name: string; + attributes: string; + type: ChannelChannelType; + date_created: Date; + date_updated: Date; + created_by: string; + members_count: number; + messages_count: number; + messaging_service_sid: string; + url: string; +} + +export class ChannelInstance { + protected _solution: ChannelContextSolution; + protected _context?: ChannelContext; + + constructor(protected _version: V3, payload: ChannelResource, serviceSid?: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.attributes = (payload.attributes); + this.type = payload.type; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + this.membersCount = deserialize.integer(payload.members_count); + this.messagesCount = deserialize.integer(payload.messages_count); + this.messagingServiceSid = (payload.messaging_service_sid); + this.url = (payload.url); + + this._solution = { serviceSid: serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Channel resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Channel resource is associated with. + */ + serviceSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\'s `sid` in the URL. + */ + uniqueName: string; + /** + * The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + */ + attributes: string; + type: ChannelChannelType; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. + */ + createdBy: string; + /** + * The number of Members in the Channel. + */ + membersCount: number; + /** + * The number of Messages that have been passed in the Channel. + */ + messagesCount: number; + /** + * The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + */ + messagingServiceSid: string; + /** + * The absolute URL of the Channel resource. + */ + url: string; + + private get _proxy(): ChannelContext { + this._context = this._context || new ChannelContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Update a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Update a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + attributes: this.attributes, + type: this.type, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + membersCount: this.membersCount, + messagesCount: this.messagesCount, + messagingServiceSid: this.messagingServiceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ChannelSolution { +} + +export interface ChannelListInstance { + _version: V3; + _solution: ChannelSolution; + _uri: string; + + (serviceSid: string, sid: string, ): ChannelContext; + get(serviceSid: string, sid: string, ): ChannelContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChannelListInstance(version: V3): ChannelListInstance { + const instance = ((serviceSid, sid, ) => instance.get(serviceSid, sid, )) as ChannelListInstance; + + instance.get = function get(serviceSid, sid, ): ChannelContext { + return new ChannelContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/content/V1.ts b/rest/content/V1.ts new file mode 100644 index 000000000..8bfc11d22 --- /dev/null +++ b/rest/content/V1.ts @@ -0,0 +1,56 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Content + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import ContentBase from "../ContentBase"; +import Version from "../../base/Version"; +import { ContentListInstance } from "./v1/content"; +import { ContentAndApprovalsListInstance } from "./v1/contentAndApprovals"; +import { LegacyContentListInstance } from "./v1/legacyContent"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Content + * + * @param domain - The Twilio (Twilio.Content) domain + */ + constructor(domain: ContentBase) { + super(domain, "v1"); + } + + /** contents - { Twilio.Content.V1.ContentListInstance } resource */ + protected _contents?: ContentListInstance; + /** contentAndApprovals - { Twilio.Content.V1.ContentAndApprovalsListInstance } resource */ + protected _contentAndApprovals?: ContentAndApprovalsListInstance; + /** legacyContents - { Twilio.Content.V1.LegacyContentListInstance } resource */ + protected _legacyContents?: LegacyContentListInstance; + + /** Getter for contents resource */ + get contents(): ContentListInstance { + this._contents = this._contents || ContentListInstance(this); + return this._contents; + } + + /** Getter for contentAndApprovals resource */ + get contentAndApprovals(): ContentAndApprovalsListInstance { + this._contentAndApprovals = this._contentAndApprovals || ContentAndApprovalsListInstance(this); + return this._contentAndApprovals; + } + + /** Getter for legacyContents resource */ + get legacyContents(): LegacyContentListInstance { + this._legacyContents = this._legacyContents || LegacyContentListInstance(this); + return this._legacyContents; + } + +} diff --git a/rest/content/V2.ts b/rest/content/V2.ts new file mode 100644 index 000000000..5f636d775 --- /dev/null +++ b/rest/content/V2.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Content + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import ContentBase from "../ContentBase"; +import Version from "../../base/Version"; +import { ContentListInstance } from "./v2/content"; +import { ContentAndApprovalsListInstance } from "./v2/contentAndApprovals"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Content + * + * @param domain - The Twilio (Twilio.Content) domain + */ + constructor(domain: ContentBase) { + super(domain, "v2"); + } + + /** contents - { Twilio.Content.V2.ContentListInstance } resource */ + protected _contents?: ContentListInstance; + /** contentAndApprovals - { Twilio.Content.V2.ContentAndApprovalsListInstance } resource */ + protected _contentAndApprovals?: ContentAndApprovalsListInstance; + + /** Getter for contents resource */ + get contents(): ContentListInstance { + this._contents = this._contents || ContentListInstance(this); + return this._contents; + } + + /** Getter for contentAndApprovals resource */ + get contentAndApprovals(): ContentAndApprovalsListInstance { + this._contentAndApprovals = this._contentAndApprovals || ContentAndApprovalsListInstance(this); + return this._contentAndApprovals; + } + +} diff --git a/rest/content/v1/content.ts b/rest/content/v1/content.ts new file mode 100644 index 000000000..399a9f2f7 --- /dev/null +++ b/rest/content/v1/content.ts @@ -0,0 +1,1411 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Content + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ApprovalCreateListInstance } from "./content/approvalCreate"; +import { ApprovalFetchListInstance } from "./content/approvalFetch"; + + +export class AuthenticationAction { + "type": AuthenticationActionType; + "copyCodeText": string; + + constructor(payload) { + this.type = payload["type"]; + this.copyCodeText = payload["copy_code_text"]; + } +} + + +export type AuthenticationActionType = 'COPY_CODE'; + +export class CallToActionAction { + "type": CallToActionActionType; + "title"?: string; + "url"?: string; + "phone"?: string; + "code"?: string; + "id"?: string; + + constructor(payload) { + this.type = payload["type"]; + this.title = payload["title"]; + this.url = payload["url"]; + this.phone = payload["phone"]; + this.code = payload["code"]; + this.id = payload["id"]; + } +} + + +export type CallToActionActionType = 'URL'|'PHONE_NUMBER'|'COPY_CODE'|'VOICE_CALL'|'VOICE_CALL_REQUEST'|'REQUEST_CONTACT_INFO'; + +export class CardAction { + "type": CardActionType; + "title": string; + "url"?: string; + "phone"?: string; + "id"?: string; + "code"?: string; + "webviewSize"?: WebviewSizeType; + + constructor(payload) { + this.type = payload["type"]; + this.title = payload["title"]; + this.url = payload["url"]; + this.phone = payload["phone"]; + this.id = payload["id"]; + this.code = payload["code"]; + this.webviewSize = payload["webview_size"]; + } +} + + +export type CardActionType = 'URL'|'PHONE_NUMBER'|'QUICK_REPLY'|'COPY_CODE'|'VOICE_CALL'; + +export class CarouselAction { + "type": CarouselActionType; + "title": string; + "url"?: string; + "phone"?: string; + "id"?: string; + + constructor(payload) { + this.type = payload["type"]; + this.title = payload["title"]; + this.url = payload["url"]; + this.phone = payload["phone"]; + this.id = payload["id"]; + } +} + + +export type CarouselActionType = 'URL'|'PHONE_NUMBER'|'QUICK_REPLY'; + +export class CarouselCard { + "title"?: string; + "body": string; + "media": string; + "actions": Array; + + constructor(payload) { + this.title = payload["title"]; + this.body = payload["body"]; + this.media = payload["media"]; + this.actions = payload["actions"]; + } +} + + +export class CatalogItem { + "id"?: string; + "sectionTitle"?: string; + "name"?: string; + "mediaUrl"?: string; + "price"?: number; + "description"?: string; + + constructor(payload) { + this.id = payload["id"]; + this.sectionTitle = payload["section_title"]; + this.name = payload["name"]; + this.mediaUrl = payload["media_url"]; + this.price = payload["price"]; + this.description = payload["description"]; + } +} + + +/** + * Content creation request body + */ +export class ContentCreateRequest { + /** + * User defined name of the content + */ + "friendlyName"?: string; + /** + * Key value pairs of variable name to value + */ + "variables"?: { [key: string]: string; }; + /** + * Language code for the content + */ + "language": string; + "types": Types; + + constructor(payload) { + this.friendlyName = payload["friendly_name"]; + this.variables = payload["variables"]; + this.language = payload["language"]; + this.types = payload["types"]; + } +} + + +/** + * Content update request body + */ +export class ContentUpdateRequest { + /** + * User defined name of the content + */ + "friendlyName"?: string; + /** + * Key value pairs of variable name to value + */ + "variables"?: { [key: string]: string; }; + /** + * Language code for the content + */ + "language"?: string; + "types": Types; + + constructor(payload) { + this.friendlyName = payload["friendly_name"]; + this.variables = payload["variables"]; + this.language = payload["language"]; + this.types = payload["types"]; + } +} + + +export class FlowsPage { + "id": string; + "nextPageId"?: string; + "title": string; + "subtitle"?: string; + "layout": Array; + + constructor(payload) { + this.id = payload["id"]; + this.nextPageId = payload["next_page_id"]; + this.title = payload["title"]; + this.subtitle = payload["subtitle"]; + this.layout = payload["layout"]; + } +} + + +export class FlowsPageComponent { + "label"?: string; + "type": string; + + constructor(payload) { + this.label = payload["label"]; + this.type = payload["type"]; + } +} + + +export class ListItem { + "id": string; + "item": string; + "description"?: string; + + constructor(payload) { + this.id = payload["id"]; + this.item = payload["item"]; + this.description = payload["description"]; + } +} + + +export class QuickReplyAction { + "type"?: QuickReplyActionType; + "title": string; + "id"?: string; + + constructor(payload) { + this.type = payload["type"]; + this.title = payload["title"]; + this.id = payload["id"]; + } +} + + +export type QuickReplyActionType = 'QUICK_REPLY'; + +/** + * twilio/call-to-action buttons let recipients tap to trigger actions such as launching a website or making a phone call. + */ +export class TwilioCallToAction { + "body": string; + "actions": Array; + + constructor(payload) { + this.body = payload["body"]; + this.actions = payload["actions"]; + } +} + + +/** + * twilio/card is a structured template which can be used to send a series of related information. It must include a title and at least one additional field. + */ +export class TwilioCard { + "title"?: string; + "subtitle"?: string; + "media"?: Array; + "actions"?: Array; + + constructor(payload) { + this.title = payload["title"]; + this.subtitle = payload["subtitle"]; + this.media = payload["media"]; + this.actions = payload["actions"]; + } +} + + +/** + * twilio/carousel templates allow you to send a single text message accompanied by a set of up to 10 carousel cards in a horizontally scrollable view + */ +export class TwilioCarousel { + "body": string; + "cards": Array; + + constructor(payload) { + this.body = payload["body"]; + this.cards = payload["cards"]; + } +} + + +/** + * twilio/catalog type lets recipients view list of catalog products, ask questions about products, order products. + */ +export class TwilioCatalog { + "title"?: string; + "body": string; + "subtitle"?: string; + "id"?: string; + "items"?: Array; + "dynamicItems"?: string; + + constructor(payload) { + this.title = payload["title"]; + this.body = payload["body"]; + this.subtitle = payload["subtitle"]; + this.id = payload["id"]; + this.items = payload["items"]; + this.dynamicItems = payload["dynamic_items"]; + } +} + + +/** + * twilio/flows templates allow you to send multiple messages in a set order with text or select options + */ +export class TwilioFlows { + "body": string; + "buttonText": string; + "subtitle"?: string; + "mediaUrl"?: string; + "pages": Array; + "type": string; + + constructor(payload) { + this.body = payload["body"]; + this.buttonText = payload["button_text"]; + this.subtitle = payload["subtitle"]; + this.mediaUrl = payload["media_url"]; + this.pages = payload["pages"]; + this.type = payload["type"]; + } +} + + +/** + * twilio/list-picker includes a menu of up to 10 options, which offers a simple way for users to make a selection. + */ +export class TwilioListPicker { + "body": string; + "button": string; + "items": Array; + + constructor(payload) { + this.body = payload["body"]; + this.button = payload["button"]; + this.items = payload["items"]; + } +} + + +/** + * twilio/location type contains a location pin and an optional label, which can be used to enhance delivery notifications or connect recipients to physical experiences you offer. + */ +export class TwilioLocation { + "latitude": number; + "longitude": number; + "label"?: string; + "id"?: string; + "address"?: string; + + constructor(payload) { + this.latitude = payload["latitude"]; + this.longitude = payload["longitude"]; + this.label = payload["label"]; + this.id = payload["id"]; + this.address = payload["address"]; + } +} + + +/** + * twilio/media is used to send file attachments, or to send long text via MMS in the US and Canada. As such, the twilio/media type must contain at least ONE of text or media content. + */ +export class TwilioMedia { + "body"?: string; + "media": Array; + + constructor(payload) { + this.body = payload["body"]; + this.media = payload["media"]; + } +} + + +/** + * twilio/quick-reply templates let recipients tap, rather than type, to respond to the message. + */ +export class TwilioQuickReply { + "body": string; + "actions": Array; + + constructor(payload) { + this.body = payload["body"]; + this.actions = payload["actions"]; + } +} + + +/** + * twilio/schedule templates allow us to send a message with a schedule with different time slots + */ +export class TwilioSchedule { + "id": string; + "title": string; + "timeSlots": string; + + constructor(payload) { + this.id = payload["id"]; + this.title = payload["title"]; + this.timeSlots = payload["timeSlots"]; + } +} + + +/** + * Type containing only plain text-based content + */ +export class TwilioText { + "body": string; + + constructor(payload) { + this.body = payload["body"]; + } +} + + +/** + * Content types + */ +export class Types { + "twilioText"?: TwilioText | null; + "twilioMedia"?: TwilioMedia | null; + "twilioLocation"?: TwilioLocation | null; + "twilioListPicker"?: TwilioListPicker | null; + "twilioCallToAction"?: TwilioCallToAction | null; + "twilioQuickReply"?: TwilioQuickReply | null; + "twilioCard"?: TwilioCard | null; + "twilioCatalog"?: TwilioCatalog | null; + "twilioCarousel"?: TwilioCarousel | null; + "twilioFlows"?: TwilioFlows | null; + "twilioSchedule"?: TwilioSchedule | null; + "whatsappCard"?: WhatsappCard | null; + "whatsappAuthentication"?: WhatsappAuthentication | null; + "whatsappFlows"?: WhatsappFlows | null; + + constructor(payload) { + this.twilioText = payload["twilio/text"]; + this.twilioMedia = payload["twilio/media"]; + this.twilioLocation = payload["twilio/location"]; + this.twilioListPicker = payload["twilio/list-picker"]; + this.twilioCallToAction = payload["twilio/call-to-action"]; + this.twilioQuickReply = payload["twilio/quick-reply"]; + this.twilioCard = payload["twilio/card"]; + this.twilioCatalog = payload["twilio/catalog"]; + this.twilioCarousel = payload["twilio/carousel"]; + this.twilioFlows = payload["twilio/flows"]; + this.twilioSchedule = payload["twilio/schedule"]; + this.whatsappCard = payload["whatsapp/card"]; + this.whatsappAuthentication = payload["whatsapp/authentication"]; + this.whatsappFlows = payload["whatsapp/flows"]; + } +} + + +export type WebviewSizeType = 'TALL'|'FULL'|'HALF'|'NONE'; + +/** + * whatsApp/authentication templates let companies deliver WA approved one-time-password button. + */ +export class WhatsappAuthentication { + "addSecurityRecommendation"?: boolean; + "codeExpirationMinutes"?: number; + "actions": Array; + + constructor(payload) { + this.addSecurityRecommendation = payload["add_security_recommendation"]; + this.codeExpirationMinutes = payload["code_expiration_minutes"]; + this.actions = payload["actions"]; + } +} + + +/** + * whatsapp/card is a structured template which can be used to send a series of related information. It must include a body and at least one additional field. + */ +export class WhatsappCard { + "body": string; + "footer"?: string; + "media"?: Array; + "headerText"?: string; + "actions"?: Array; + + constructor(payload) { + this.body = payload["body"]; + this.footer = payload["footer"]; + this.media = payload["media"]; + this.headerText = payload["header_text"]; + this.actions = payload["actions"]; + } +} + + +/** + * whatsapp/flows templates allow you to send multiple messages in a set order with text or select options + */ +export class WhatsappFlows { + "body": string; + "buttonText": string; + "subtitle"?: string; + "mediaUrl"?: string; + "flowId": string; + "flowToken"?: string; + "flowFirstPageId"?: string; + "isFlowFirstPageEndpoint"?: boolean; + + constructor(payload) { + this.body = payload["body"]; + this.buttonText = payload["button_text"]; + this.subtitle = payload["subtitle"]; + this.mediaUrl = payload["media_url"]; + this.flowId = payload["flow_id"]; + this.flowToken = payload["flow_token"]; + this.flowFirstPageId = payload["flow_first_page_id"]; + this.isFlowFirstPageEndpoint = payload["is_flow_first_page_endpoint"]; + } +} + + + + + +/** + * Options to pass to update a ContentInstance + */ +export interface ContentContextUpdateOptions { + /** */ + "contentUpdateRequest": ContentUpdateRequest; +} + +/** + * Options to pass to create a ContentInstance + */ +export interface ContentListInstanceCreateOptions { + /** */ + "contentCreateRequest": ContentCreateRequest; +} + +/** + * Options to pass to each + */ +export interface ContentListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ContentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ContentListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ContentListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ContentContext { + approvalCreate: ApprovalCreateListInstance; + approvalFetch: ApprovalFetchListInstance; + + /** + * Remove a ContentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ContentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ContentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ContentInstance + */ + fetch(callback?: (error: Error | null, item?: ContentInstance) => any): Promise + + /** + * Fetch a ContentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ContentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ContentInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ContentInstance + */ + update(params: ContentUpdateRequest, headers?: any, callback?: (error: Error | null, item?: ContentInstance) => any): Promise; + + /** + * Update a ContentInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ContentInstance with HTTP metadata + */ + updateWithHttpInfo(params: ContentUpdateRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ContentContextSolution { + "sid": string; +} + +export class ContentContextImpl implements ContentContext { + protected _solution: ContentContextSolution; + protected _uri: string; + + protected _approvalCreate?: ApprovalCreateListInstance; + protected _approvalFetch?: ApprovalFetchListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Content/${sid}`; + } + + get approvalCreate(): ApprovalCreateListInstance { + this._approvalCreate = this._approvalCreate || ApprovalCreateListInstance(this._version, this._solution.sid); + return this._approvalCreate; + } + + get approvalFetch(): ApprovalFetchListInstance { + this._approvalFetch = this._approvalFetch || ApprovalFetchListInstance(this._version, this._solution.sid); + return this._approvalFetch; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ContentInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ContentInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ContentInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: ContentUpdateRequest, headers?: any,callback?: (error: Error | null, item?: ContentInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new ContentInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: ContentUpdateRequest, headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ContentInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ContentPayload extends TwilioResponsePayload { + contents: ContentResource[]; +} + +interface ContentResource { + date_created: Date; + date_updated: Date; + sid: string; + account_sid: string; + friendly_name: string; + language: string; + variables: Record; + types: Record; + url: string; + links: Record; +} + +export class ContentInstance { + protected _solution: ContentContextSolution; + protected _context?: ContentContext; + + constructor(protected _version: V1, payload: ContentResource, sid?: string) { + + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.language = (payload.language); + this.variables = (payload.variables); + this.types = (payload.types); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The unique string that that we created to identify the Content resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + */ + accountSid: string; + /** + * A string name used to describe the Content resource. Not visible to the end recipient. + */ + friendlyName: string; + /** + * Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + */ + language: string; + /** + * Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + */ + variables: Record; + /** + * The [Content types](https://www.twilio.com/docs/content-api/content-types-overview) (e.g. twilio/text) for this Content resource. + */ + types: Record; + /** + * The URL of the resource, relative to `https://content.twilio.com`. + */ + url: string; + /** + * A list of links related to the Content resource, such as approval_fetch and approval_create + */ + links: Record; + + private get _proxy(): ContentContext { + this._context = this._context || new ContentContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ContentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ContentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ContentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ContentInstance + */ + fetch(callback?: (error: Error | null, item?: ContentInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ContentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ContentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ContentInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ContentInstance + */ + update(params: ContentUpdateRequest, headers?: any, callback?: (error: Error | null, item?: ContentInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ContentInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ContentInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ContentInstance with HTTP metadata + */ + updateWithHttpInfo(params: ContentUpdateRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the approvalCreate. + */ + approvalCreate(): ApprovalCreateListInstance { + return this._proxy.approvalCreate; + } + + /** + * Access the approvalFetch. + */ + approvalFetch(): ApprovalFetchListInstance { + return this._proxy.approvalFetch; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + language: this.language, + variables: this.variables, + types: this.types, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ContentSolution { +} + +export interface ContentListInstance { + _version: V1; + _solution: ContentSolution; + _uri: string; + + (sid: string, ): ContentContext; + get(sid: string, ): ContentContext; + + + + + + + + + /** + * Create a ContentInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ContentInstance + */ + create(params: ContentCreateRequest, headers?: any, callback?: (error: Error | null, item?: ContentInstance) => any): Promise; + + /** + * Create a ContentInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ContentInstance with HTTP metadata + */ + createWithHttpInfo(params: ContentCreateRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ContentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ContentInstance, done: (err?: Error) => void) => void): void; + each(params: ContentListInstanceEachOptions, callback?: (item: ContentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ContentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ContentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ContentListInstanceEachOptions, callback?: (item: ContentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ContentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ContentPage) => any): Promise; + /** + * Retrieve a single target page of ContentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ContentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ContentInstance[]) => any): Promise; + list(params: ContentListInstanceOptions, callback?: (error: Error | null, items: ContentInstance[]) => any): Promise; + /** + * Lists ContentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ContentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ContentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ContentPage) => any): Promise; + page(params: ContentListInstancePageOptions, callback?: (error: Error | null, items: ContentPage) => any): Promise; + /** + * Retrieve a single page of ContentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ContentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ContentListInstance(version: V1): ContentListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ContentListInstance; + + instance.get = function get(sid, ): ContentContext { + return new ContentContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Content`; + + instance.create = function create(params: ContentCreateRequest, headers?: any, callback?: (error: Error | null, items: ContentInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ContentInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ContentCreateRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ContentInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ContentListInstancePageOptions | ((error: Error | null, items: ContentPage) => any), callback?: (error: Error | null, items: ContentPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ContentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ContentPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ContentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ContentListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ContentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ContentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ContentPage extends Page { +/** +* Initialize the ContentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ContentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ContentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ContentResource): ContentInstance { + + return new ContentInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/content/v1/content/approvalCreate.ts b/rest/content/v1/content/approvalCreate.ts new file mode 100644 index 000000000..e6403e205 --- /dev/null +++ b/rest/content/v1/content/approvalCreate.ts @@ -0,0 +1,231 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Content + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * Content approval request body + */ +export class ContentApprovalRequest { + /** + * Name of the template. + */ + "name": string; + /** + * A WhatsApp recognized template category. + */ + "category": string; + + constructor(payload) { + this.name = payload["name"]; + this.category = payload["category"]; + } +} + + + +/** + * Options to pass to create a ApprovalCreateInstance + */ +export interface ApprovalCreateListInstanceCreateOptions { + /** */ + "contentApprovalRequest": ContentApprovalRequest; +} + + +export interface ApprovalCreateSolution { + contentSid: string; +} + +export interface ApprovalCreateListInstance { + _version: V1; + _solution: ApprovalCreateSolution; + _uri: string; + + + + /** + * Create a ApprovalCreateInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApprovalCreateInstance + */ + create(params: ContentApprovalRequest, headers?: any, callback?: (error: Error | null, item?: ApprovalCreateInstance) => any): Promise; + + /** + * Create a ApprovalCreateInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApprovalCreateInstance with HTTP metadata + */ + createWithHttpInfo(params: ContentApprovalRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ApprovalCreateListInstance(version: V1, contentSid: string): ApprovalCreateListInstance { + if (!isValidPathParam(contentSid)) { + throw new Error('Parameter \'contentSid\' is not valid.'); + } + + const instance = {} as ApprovalCreateListInstance; + + instance._version = version; + instance._solution = { contentSid, }; + instance._uri = `/Content/${contentSid}/ApprovalRequests/whatsapp`; + + instance.create = function create(params: ContentApprovalRequest, headers?: any, callback?: (error: Error | null, items: ApprovalCreateInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ApprovalCreateInstance(operationVersion, payload, instance._solution.contentSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ContentApprovalRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ApprovalCreateInstance(operationVersion, response.body, instance._solution.contentSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ApprovalCreatePayload extends ApprovalCreateResource {} + +interface ApprovalCreateResource { + name: string; + category: string; + content_type: string; + status: string; + rejection_reason: string; + allow_category_change: boolean; +} + +export class ApprovalCreateInstance { + + constructor(protected _version: V1, payload: ApprovalCreateResource, contentSid: string) { + + this.name = (payload.name); + this.category = (payload.category); + this.contentType = (payload.content_type); + this.status = (payload.status); + this.rejectionReason = (payload.rejection_reason); + this.allowCategoryChange = (payload.allow_category_change); + + } + + name: string; + category: string; + contentType: string; + status: string; + rejectionReason: string; + allowCategoryChange: boolean; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + name: this.name, + category: this.category, + contentType: this.contentType, + status: this.status, + rejectionReason: this.rejectionReason, + allowCategoryChange: this.allowCategoryChange, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/content/v1/content/approvalFetch.ts b/rest/content/v1/content/approvalFetch.ts new file mode 100644 index 000000000..c6852626a --- /dev/null +++ b/rest/content/v1/content/approvalFetch.ts @@ -0,0 +1,260 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Content + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +export interface ApprovalFetchContext { + + /** + * Fetch a ApprovalFetchInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApprovalFetchInstance + */ + fetch(callback?: (error: Error | null, item?: ApprovalFetchInstance) => any): Promise + + /** + * Fetch a ApprovalFetchInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApprovalFetchInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ApprovalFetchContextSolution { + "sid": string; +} + +export class ApprovalFetchContextImpl implements ApprovalFetchContext { + protected _solution: ApprovalFetchContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Content/${sid}/ApprovalRequests`; + } + + fetch(callback?: (error: Error | null, item?: ApprovalFetchInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ApprovalFetchInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ApprovalFetchInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ApprovalFetchPayload extends ApprovalFetchResource {} + +interface ApprovalFetchResource { + sid: string; + account_sid: string; + whatsapp: Record; + url: string; +} + +export class ApprovalFetchInstance { + protected _solution: ApprovalFetchContextSolution; + protected _context?: ApprovalFetchContext; + + constructor(protected _version: V1, payload: ApprovalFetchResource, sid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.whatsapp = (payload.whatsapp); + this.url = (payload.url); + + this._solution = { sid, }; + } + + /** + * The unique string that that we created to identify the Content resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + */ + accountSid: string; + /** + * Contains the whatsapp approval information for the Content resource, with fields such as approval status, rejection reason, and category, amongst others. + */ + whatsapp: Record; + /** + * The URL of the resource, relative to `https://content.twilio.com`. + */ + url: string; + + private get _proxy(): ApprovalFetchContext { + this._context = this._context || new ApprovalFetchContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a ApprovalFetchInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApprovalFetchInstance + */ + fetch(callback?: (error: Error | null, item?: ApprovalFetchInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ApprovalFetchInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApprovalFetchInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + whatsapp: this.whatsapp, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ApprovalFetchSolution { + sid: string; +} + +export interface ApprovalFetchListInstance { + _version: V1; + _solution: ApprovalFetchSolution; + _uri: string; + + (): ApprovalFetchContext; + get(): ApprovalFetchContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ApprovalFetchListInstance(version: V1, sid: string): ApprovalFetchListInstance { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + const instance = (() => instance.get()) as ApprovalFetchListInstance; + + instance.get = function get(): ApprovalFetchContext { + return new ApprovalFetchContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { sid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/content/v1/contentAndApprovals.ts b/rest/content/v1/contentAndApprovals.ts new file mode 100644 index 000000000..49e599c2b --- /dev/null +++ b/rest/content/v1/contentAndApprovals.ts @@ -0,0 +1,434 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Content + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface ContentAndApprovalsListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ContentAndApprovalsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ContentAndApprovalsListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ContentAndApprovalsListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface ContentAndApprovalsSolution { +} + +export interface ContentAndApprovalsListInstance { + _version: V1; + _solution: ContentAndApprovalsSolution; + _uri: string; + + + + + /** + * Streams ContentAndApprovalsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ContentAndApprovalsInstance, done: (err?: Error) => void) => void): void; + each(params: ContentAndApprovalsListInstanceEachOptions, callback?: (item: ContentAndApprovalsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ContentAndApprovalsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ContentAndApprovalsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ContentAndApprovalsListInstanceEachOptions, callback?: (item: ContentAndApprovalsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ContentAndApprovalsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ContentAndApprovalsPage) => any): Promise; + /** + * Retrieve a single target page of ContentAndApprovalsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ContentAndApprovalsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ContentAndApprovalsInstance[]) => any): Promise; + list(params: ContentAndApprovalsListInstanceOptions, callback?: (error: Error | null, items: ContentAndApprovalsInstance[]) => any): Promise; + /** + * Lists ContentAndApprovalsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ContentAndApprovalsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ContentAndApprovalsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ContentAndApprovalsPage) => any): Promise; + page(params: ContentAndApprovalsListInstancePageOptions, callback?: (error: Error | null, items: ContentAndApprovalsPage) => any): Promise; + /** + * Retrieve a single page of ContentAndApprovalsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ContentAndApprovalsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ContentAndApprovalsListInstance(version: V1): ContentAndApprovalsListInstance { + const instance = {} as ContentAndApprovalsListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/ContentAndApprovals`; + + instance.page = function page(params?: ContentAndApprovalsListInstancePageOptions | ((error: Error | null, items: ContentAndApprovalsPage) => any), callback?: (error: Error | null, items: ContentAndApprovalsPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ContentAndApprovalsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ContentAndApprovalsPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ContentAndApprovalsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ContentAndApprovalsListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ContentAndApprovalsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ContentAndApprovalsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ContentAndApprovalsPayload extends TwilioResponsePayload { + contents: ContentAndApprovalsResource[]; +} + +interface ContentAndApprovalsResource { + date_created: Date; + date_updated: Date; + sid: string; + account_sid: string; + friendly_name: string; + language: string; + variables: Record; + types: Record; + approval_requests: Record; +} + +export class ContentAndApprovalsInstance { + + constructor(protected _version: V1, payload: ContentAndApprovalsResource) { + + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.language = (payload.language); + this.variables = (payload.variables); + this.types = (payload.types); + this.approvalRequests = (payload.approval_requests); + + } + + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The unique string that that we created to identify the Content resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + */ + accountSid: string; + /** + * A string name used to describe the Content resource. Not visible to the end recipient. + */ + friendlyName: string; + /** + * Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + */ + language: string; + /** + * Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + */ + variables: Record; + /** + * The [Content types](https://www.twilio.com/docs/content-api/content-types-overview) (e.g. twilio/text) for this Content resource. + */ + types: Record; + /** + * The submitted information and approval request status of the Content resource. + */ + approvalRequests: Record; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + language: this.language, + variables: this.variables, + types: this.types, + approvalRequests: this.approvalRequests, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class ContentAndApprovalsPage extends Page { +/** +* Initialize the ContentAndApprovalsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ContentAndApprovalsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ContentAndApprovalsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ContentAndApprovalsResource): ContentAndApprovalsInstance { + + return new ContentAndApprovalsInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/content/v1/legacyContent.ts b/rest/content/v1/legacyContent.ts new file mode 100644 index 000000000..1ec24d3fe --- /dev/null +++ b/rest/content/v1/legacyContent.ts @@ -0,0 +1,448 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Content + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface LegacyContentListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: LegacyContentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface LegacyContentListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface LegacyContentListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface LegacyContentSolution { +} + +export interface LegacyContentListInstance { + _version: V1; + _solution: LegacyContentSolution; + _uri: string; + + + + + /** + * Streams LegacyContentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LegacyContentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: LegacyContentInstance, done: (err?: Error) => void) => void): void; + each(params: LegacyContentListInstanceEachOptions, callback?: (item: LegacyContentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams LegacyContentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LegacyContentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: LegacyContentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: LegacyContentListInstanceEachOptions, callback?: (item: LegacyContentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of LegacyContentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: LegacyContentPage) => any): Promise; + /** + * Retrieve a single target page of LegacyContentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists LegacyContentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LegacyContentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: LegacyContentInstance[]) => any): Promise; + list(params: LegacyContentListInstanceOptions, callback?: (error: Error | null, items: LegacyContentInstance[]) => any): Promise; + /** + * Lists LegacyContentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LegacyContentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: LegacyContentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of LegacyContentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LegacyContentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: LegacyContentPage) => any): Promise; + page(params: LegacyContentListInstancePageOptions, callback?: (error: Error | null, items: LegacyContentPage) => any): Promise; + /** + * Retrieve a single page of LegacyContentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LegacyContentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: LegacyContentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function LegacyContentListInstance(version: V1): LegacyContentListInstance { + const instance = {} as LegacyContentListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/LegacyContent`; + + instance.page = function page(params?: LegacyContentListInstancePageOptions | ((error: Error | null, items: LegacyContentPage) => any), callback?: (error: Error | null, items: LegacyContentPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new LegacyContentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: LegacyContentPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new LegacyContentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: LegacyContentListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new LegacyContentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new LegacyContentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface LegacyContentPayload extends TwilioResponsePayload { + contents: LegacyContentResource[]; +} + +interface LegacyContentResource { + date_created: Date; + date_updated: Date; + sid: string; + account_sid: string; + friendly_name: string; + language: string; + variables: Record; + types: Record; + legacy_template_name: string; + legacy_body: string; + url: string; +} + +export class LegacyContentInstance { + + constructor(protected _version: V1, payload: LegacyContentResource) { + + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.language = (payload.language); + this.variables = (payload.variables); + this.types = (payload.types); + this.legacyTemplateName = (payload.legacy_template_name); + this.legacyBody = (payload.legacy_body); + this.url = (payload.url); + + } + + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The unique string that that we created to identify the Content resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + */ + accountSid: string; + /** + * A string name used to describe the Content resource. Not visible to the end recipient. + */ + friendlyName: string; + /** + * Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + */ + language: string; + /** + * Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + */ + variables: Record; + /** + * The [Content types](https://www.twilio.com/docs/content-api/content-types-overview) (e.g. twilio/text) for this Content resource. + */ + types: Record; + /** + * The string name of the legacy content template associated with this Content resource, unique across all template names for its account. Only lowercase letters, numbers and underscores are allowed + */ + legacyTemplateName: string; + /** + * The string body field of the legacy content template associated with this Content resource + */ + legacyBody: string; + /** + * The URL of the resource, relative to `https://content.twilio.com`. + */ + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + language: this.language, + variables: this.variables, + types: this.types, + legacyTemplateName: this.legacyTemplateName, + legacyBody: this.legacyBody, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class LegacyContentPage extends Page { +/** +* Initialize the LegacyContentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: LegacyContentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of LegacyContentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: LegacyContentResource): LegacyContentInstance { + + return new LegacyContentInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/content/v2/content.ts b/rest/content/v2/content.ts new file mode 100644 index 000000000..61d07e33f --- /dev/null +++ b/rest/content/v2/content.ts @@ -0,0 +1,531 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Content + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface ContentListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Whether to sort by ascending or descending date updated */ + "sortByDate"?: string; + /** Whether to sort by ascending or descending content name */ + "sortByContentName"?: string; + /** Filter by >=[date-time] */ + "dateCreatedAfter"?: Date; + /** Filter by <=[date-time] */ + "dateCreatedBefore"?: Date; + /** Filter by Regex Pattern in content name */ + "contentName"?: string; + /** Filter by Regex Pattern in template content */ + "content"?: string; + /** Filter by array of valid language(s) */ + "language"?: Array; + /** Filter by array of contentType(s) */ + "contentType"?: Array; + /** Filter by array of ChannelEligibility(s), where ChannelEligibility=: */ + "channelEligibility"?: Array; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ContentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ContentListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Whether to sort by ascending or descending date updated */ + "sortByDate"?: string; + /** Whether to sort by ascending or descending content name */ + "sortByContentName"?: string; + /** Filter by >=[date-time] */ + "dateCreatedAfter"?: Date; + /** Filter by <=[date-time] */ + "dateCreatedBefore"?: Date; + /** Filter by Regex Pattern in content name */ + "contentName"?: string; + /** Filter by Regex Pattern in template content */ + "content"?: string; + /** Filter by array of valid language(s) */ + "language"?: Array; + /** Filter by array of contentType(s) */ + "contentType"?: Array; + /** Filter by array of ChannelEligibility(s), where ChannelEligibility=: */ + "channelEligibility"?: Array; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ContentListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Whether to sort by ascending or descending date updated */ + "sortByDate"?: string; + /** Whether to sort by ascending or descending content name */ + "sortByContentName"?: string; + /** Filter by >=[date-time] */ + "dateCreatedAfter"?: Date; + /** Filter by <=[date-time] */ + "dateCreatedBefore"?: Date; + /** Filter by Regex Pattern in content name */ + "contentName"?: string; + /** Filter by Regex Pattern in template content */ + "content"?: string; + /** Filter by array of valid language(s) */ + "language"?: Array; + /** Filter by array of contentType(s) */ + "contentType"?: Array; + /** Filter by array of ChannelEligibility(s), where ChannelEligibility=: */ + "channelEligibility"?: Array; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface ContentSolution { +} + +export interface ContentListInstance { + _version: V2; + _solution: ContentSolution; + _uri: string; + + + + + /** + * Streams ContentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ContentInstance, done: (err?: Error) => void) => void): void; + each(params: ContentListInstanceEachOptions, callback?: (item: ContentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ContentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ContentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ContentListInstanceEachOptions, callback?: (item: ContentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ContentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ContentPage) => any): Promise; + /** + * Retrieve a single target page of ContentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ContentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ContentInstance[]) => any): Promise; + list(params: ContentListInstanceOptions, callback?: (error: Error | null, items: ContentInstance[]) => any): Promise; + /** + * Lists ContentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ContentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ContentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ContentPage) => any): Promise; + page(params: ContentListInstancePageOptions, callback?: (error: Error | null, items: ContentPage) => any): Promise; + /** + * Retrieve a single page of ContentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ContentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ContentListInstance(version: V2): ContentListInstance { + const instance = {} as ContentListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Content`; + + instance.page = function page(params?: ContentListInstancePageOptions | ((error: Error | null, items: ContentPage) => any), callback?: (error: Error | null, items: ContentPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["sortByDate"] !== undefined) + data["SortByDate"] = params["sortByDate"]; + if (params["sortByContentName"] !== undefined) + data["SortByContentName"] = params["sortByContentName"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["contentName"] !== undefined) + data["ContentName"] = params["contentName"]; + if (params["content"] !== undefined) + data["Content"] = params["content"]; + if (params["language"] !== undefined) + data["Language"] = serialize.map(params["language"], (e: string) => (e)); + if (params["contentType"] !== undefined) + data["ContentType"] = serialize.map(params["contentType"], (e: string) => (e)); + if (params["channelEligibility"] !== undefined) + data["ChannelEligibility"] = serialize.map(params["channelEligibility"], (e: string) => (e)); + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ContentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ContentPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ContentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ContentListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["sortByDate"] !== undefined) + data["SortByDate"] = params["sortByDate"]; + if (params["sortByContentName"] !== undefined) + data["SortByContentName"] = params["sortByContentName"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["contentName"] !== undefined) + data["ContentName"] = params["contentName"]; + if (params["content"] !== undefined) + data["Content"] = params["content"]; + if (params["language"] !== undefined) + data["Language"] = serialize.map(params["language"], (e: string) => (e)); + if (params["contentType"] !== undefined) + data["ContentType"] = serialize.map(params["contentType"], (e: string) => (e)); + if (params["channelEligibility"] !== undefined) + data["ChannelEligibility"] = serialize.map(params["channelEligibility"], (e: string) => (e)); + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ContentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ContentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ContentPayload extends TwilioResponsePayload { + contents: ContentResource[]; +} + +interface ContentResource { + date_created: Date; + date_updated: Date; + sid: string; + account_sid: string; + friendly_name: string; + language: string; + variables: Record; + types: Record; + url: string; + links: Record; +} + +export class ContentInstance { + + constructor(protected _version: V2, payload: ContentResource) { + + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.language = (payload.language); + this.variables = (payload.variables); + this.types = (payload.types); + this.url = (payload.url); + this.links = (payload.links); + + } + + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The unique string that that we created to identify the Content resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + */ + accountSid: string; + /** + * A string name used to describe the Content resource. Not visible to the end recipient. + */ + friendlyName: string; + /** + * Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + */ + language: string; + /** + * Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + */ + variables: Record; + /** + * The [Content types](https://www.twilio.com/docs/content/content-types-overview) (e.g. twilio/text) for this Content resource. + */ + types: Record; + /** + * The URL of the resource, relative to `https://content.twilio.com`. + */ + url: string; + /** + * A list of links related to the Content resource, such as approval_fetch and approval_create + */ + links: Record; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + language: this.language, + variables: this.variables, + types: this.types, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class ContentPage extends Page { +/** +* Initialize the ContentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: ContentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ContentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ContentResource): ContentInstance { + + return new ContentInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/content/v2/contentAndApprovals.ts b/rest/content/v2/contentAndApprovals.ts new file mode 100644 index 000000000..2a5d45281 --- /dev/null +++ b/rest/content/v2/contentAndApprovals.ts @@ -0,0 +1,524 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Content + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface ContentAndApprovalsListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Whether to sort by ascending or descending date updated */ + "sortByDate"?: string; + /** Whether to sort by ascending or descending content name */ + "sortByContentName"?: string; + /** Filter by >=[date-time] */ + "dateCreatedAfter"?: Date; + /** Filter by <=[date-time] */ + "dateCreatedBefore"?: Date; + /** Filter by Regex Pattern in content name */ + "contentName"?: string; + /** Filter by Regex Pattern in template content */ + "content"?: string; + /** Filter by array of valid language(s) */ + "language"?: Array; + /** Filter by array of contentType(s) */ + "contentType"?: Array; + /** Filter by array of ChannelEligibility(s), where ChannelEligibility=: */ + "channelEligibility"?: Array; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ContentAndApprovalsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ContentAndApprovalsListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Whether to sort by ascending or descending date updated */ + "sortByDate"?: string; + /** Whether to sort by ascending or descending content name */ + "sortByContentName"?: string; + /** Filter by >=[date-time] */ + "dateCreatedAfter"?: Date; + /** Filter by <=[date-time] */ + "dateCreatedBefore"?: Date; + /** Filter by Regex Pattern in content name */ + "contentName"?: string; + /** Filter by Regex Pattern in template content */ + "content"?: string; + /** Filter by array of valid language(s) */ + "language"?: Array; + /** Filter by array of contentType(s) */ + "contentType"?: Array; + /** Filter by array of ChannelEligibility(s), where ChannelEligibility=: */ + "channelEligibility"?: Array; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ContentAndApprovalsListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Whether to sort by ascending or descending date updated */ + "sortByDate"?: string; + /** Whether to sort by ascending or descending content name */ + "sortByContentName"?: string; + /** Filter by >=[date-time] */ + "dateCreatedAfter"?: Date; + /** Filter by <=[date-time] */ + "dateCreatedBefore"?: Date; + /** Filter by Regex Pattern in content name */ + "contentName"?: string; + /** Filter by Regex Pattern in template content */ + "content"?: string; + /** Filter by array of valid language(s) */ + "language"?: Array; + /** Filter by array of contentType(s) */ + "contentType"?: Array; + /** Filter by array of ChannelEligibility(s), where ChannelEligibility=: */ + "channelEligibility"?: Array; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface ContentAndApprovalsSolution { +} + +export interface ContentAndApprovalsListInstance { + _version: V2; + _solution: ContentAndApprovalsSolution; + _uri: string; + + + + + /** + * Streams ContentAndApprovalsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ContentAndApprovalsInstance, done: (err?: Error) => void) => void): void; + each(params: ContentAndApprovalsListInstanceEachOptions, callback?: (item: ContentAndApprovalsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ContentAndApprovalsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ContentAndApprovalsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ContentAndApprovalsListInstanceEachOptions, callback?: (item: ContentAndApprovalsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ContentAndApprovalsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ContentAndApprovalsPage) => any): Promise; + /** + * Retrieve a single target page of ContentAndApprovalsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ContentAndApprovalsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ContentAndApprovalsInstance[]) => any): Promise; + list(params: ContentAndApprovalsListInstanceOptions, callback?: (error: Error | null, items: ContentAndApprovalsInstance[]) => any): Promise; + /** + * Lists ContentAndApprovalsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ContentAndApprovalsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ContentAndApprovalsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ContentAndApprovalsPage) => any): Promise; + page(params: ContentAndApprovalsListInstancePageOptions, callback?: (error: Error | null, items: ContentAndApprovalsPage) => any): Promise; + /** + * Retrieve a single page of ContentAndApprovalsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ContentAndApprovalsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ContentAndApprovalsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ContentAndApprovalsListInstance(version: V2): ContentAndApprovalsListInstance { + const instance = {} as ContentAndApprovalsListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/ContentAndApprovals`; + + instance.page = function page(params?: ContentAndApprovalsListInstancePageOptions | ((error: Error | null, items: ContentAndApprovalsPage) => any), callback?: (error: Error | null, items: ContentAndApprovalsPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["sortByDate"] !== undefined) + data["SortByDate"] = params["sortByDate"]; + if (params["sortByContentName"] !== undefined) + data["SortByContentName"] = params["sortByContentName"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["contentName"] !== undefined) + data["ContentName"] = params["contentName"]; + if (params["content"] !== undefined) + data["Content"] = params["content"]; + if (params["language"] !== undefined) + data["Language"] = serialize.map(params["language"], (e: string) => (e)); + if (params["contentType"] !== undefined) + data["ContentType"] = serialize.map(params["contentType"], (e: string) => (e)); + if (params["channelEligibility"] !== undefined) + data["ChannelEligibility"] = serialize.map(params["channelEligibility"], (e: string) => (e)); + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ContentAndApprovalsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ContentAndApprovalsPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ContentAndApprovalsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ContentAndApprovalsListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["sortByDate"] !== undefined) + data["SortByDate"] = params["sortByDate"]; + if (params["sortByContentName"] !== undefined) + data["SortByContentName"] = params["sortByContentName"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["contentName"] !== undefined) + data["ContentName"] = params["contentName"]; + if (params["content"] !== undefined) + data["Content"] = params["content"]; + if (params["language"] !== undefined) + data["Language"] = serialize.map(params["language"], (e: string) => (e)); + if (params["contentType"] !== undefined) + data["ContentType"] = serialize.map(params["contentType"], (e: string) => (e)); + if (params["channelEligibility"] !== undefined) + data["ChannelEligibility"] = serialize.map(params["channelEligibility"], (e: string) => (e)); + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ContentAndApprovalsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ContentAndApprovalsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ContentAndApprovalsPayload extends TwilioResponsePayload { + contents: ContentAndApprovalsResource[]; +} + +interface ContentAndApprovalsResource { + date_created: Date; + date_updated: Date; + sid: string; + account_sid: string; + friendly_name: string; + language: string; + variables: Record; + types: Record; + approval_requests: Record; +} + +export class ContentAndApprovalsInstance { + + constructor(protected _version: V2, payload: ContentAndApprovalsResource) { + + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.language = (payload.language); + this.variables = (payload.variables); + this.types = (payload.types); + this.approvalRequests = (payload.approval_requests); + + } + + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The unique string that that we created to identify the Content resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + */ + accountSid: string; + /** + * A string name used to describe the Content resource. Not visible to the end recipient. + */ + friendlyName: string; + /** + * Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + */ + language: string; + /** + * Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + */ + variables: Record; + /** + * The [Content types](https://www.twilio.com/docs/content/content-types-overview) (e.g. twilio/text) for this Content resource. + */ + types: Record; + /** + * The submitted information and approval request status of the Content resource. + */ + approvalRequests: Record; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + language: this.language, + variables: this.variables, + types: this.types, + approvalRequests: this.approvalRequests, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class ContentAndApprovalsPage extends Page { +/** +* Initialize the ContentAndApprovalsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: ContentAndApprovalsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ContentAndApprovalsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ContentAndApprovalsResource): ContentAndApprovalsInstance { + + return new ContentAndApprovalsInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/V1.ts b/rest/conversations/V1.ts new file mode 100644 index 000000000..b57f627bc --- /dev/null +++ b/rest/conversations/V1.ts @@ -0,0 +1,110 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import ConversationsBase from "../ConversationsBase"; +import Version from "../../base/Version"; +import { AddressConfigurationListInstance } from "./v1/addressConfiguration"; +import { ConfigurationListInstance } from "./v1/configuration"; +import { ConversationListInstance } from "./v1/conversation"; +import { ConversationWithParticipantsListInstance } from "./v1/conversationWithParticipants"; +import { CredentialListInstance } from "./v1/credential"; +import { ParticipantConversationListInstance } from "./v1/participantConversation"; +import { RoleListInstance } from "./v1/role"; +import { ServiceListInstance } from "./v1/service"; +import { UserListInstance } from "./v1/user"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Conversations + * + * @param domain - The Twilio (Twilio.Conversations) domain + */ + constructor(domain: ConversationsBase) { + super(domain, "v1"); + } + + /** addressConfigurations - { Twilio.Conversations.V1.AddressConfigurationListInstance } resource */ + protected _addressConfigurations?: AddressConfigurationListInstance; + /** configuration - { Twilio.Conversations.V1.ConfigurationListInstance } resource */ + protected _configuration?: ConfigurationListInstance; + /** conversations - { Twilio.Conversations.V1.ConversationListInstance } resource */ + protected _conversations?: ConversationListInstance; + /** conversationWithParticipants - { Twilio.Conversations.V1.ConversationWithParticipantsListInstance } resource */ + protected _conversationWithParticipants?: ConversationWithParticipantsListInstance; + /** credentials - { Twilio.Conversations.V1.CredentialListInstance } resource */ + protected _credentials?: CredentialListInstance; + /** participantConversations - { Twilio.Conversations.V1.ParticipantConversationListInstance } resource */ + protected _participantConversations?: ParticipantConversationListInstance; + /** roles - { Twilio.Conversations.V1.RoleListInstance } resource */ + protected _roles?: RoleListInstance; + /** services - { Twilio.Conversations.V1.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + /** users - { Twilio.Conversations.V1.UserListInstance } resource */ + protected _users?: UserListInstance; + + /** Getter for addressConfigurations resource */ + get addressConfigurations(): AddressConfigurationListInstance { + this._addressConfigurations = this._addressConfigurations || AddressConfigurationListInstance(this); + return this._addressConfigurations; + } + + /** Getter for configuration resource */ + get configuration(): ConfigurationListInstance { + this._configuration = this._configuration || ConfigurationListInstance(this); + return this._configuration; + } + + /** Getter for conversations resource */ + get conversations(): ConversationListInstance { + this._conversations = this._conversations || ConversationListInstance(this); + return this._conversations; + } + + /** Getter for conversationWithParticipants resource */ + get conversationWithParticipants(): ConversationWithParticipantsListInstance { + this._conversationWithParticipants = this._conversationWithParticipants || ConversationWithParticipantsListInstance(this); + return this._conversationWithParticipants; + } + + /** Getter for credentials resource */ + get credentials(): CredentialListInstance { + this._credentials = this._credentials || CredentialListInstance(this); + return this._credentials; + } + + /** Getter for participantConversations resource */ + get participantConversations(): ParticipantConversationListInstance { + this._participantConversations = this._participantConversations || ParticipantConversationListInstance(this); + return this._participantConversations; + } + + /** Getter for roles resource */ + get roles(): RoleListInstance { + this._roles = this._roles || RoleListInstance(this); + return this._roles; + } + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + + /** Getter for users resource */ + get users(): UserListInstance { + this._users = this._users || UserListInstance(this); + return this._users; + } + +} diff --git a/rest/conversations/V2.ts b/rest/conversations/V2.ts new file mode 100644 index 000000000..4eb2d2b33 --- /dev/null +++ b/rest/conversations/V2.ts @@ -0,0 +1,90 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Conversation Orchestrator + * Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import ConversationsBase from "../ConversationsBase"; +import Version from "../../base/Version"; +import { ActionListInstance } from "./v2/action"; +import { CommunicationListInstance, CommunicationContext } from "./v2/communication"; +import { ConfigurationListInstance } from "./v2/configuration"; +import { ConversationListInstance } from "./v2/conversation"; +import { OperationListInstance } from "./v2/operation"; +import { ParticipantListInstance, ParticipantContext } from "./v2/participant"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Conversations + * + * @param domain - The Twilio (Twilio.Conversations) domain + */ + constructor(domain: ConversationsBase) { + super(domain, "v2"); + } + + /** configurations - { Twilio.Conversations.V2.ConfigurationListInstance } resource */ + protected _configurations?: ConfigurationListInstance; + /** conversations - { Twilio.Conversations.V2.ConversationListInstance } resource */ + protected _conversations?: ConversationListInstance; + /** operations - { Twilio.Conversations.V2.OperationListInstance } resource */ + protected _operations?: OperationListInstance; + + /** Accessor for actions resource */ + actions(ConversationId: string): ActionListInstance { + return ActionListInstance(this, ConversationId); + } + + /** Accessor for communications resource - list operations */ + communications(ConversationId: string): CommunicationListInstance; + /** Accessor for communications resource - instance operations */ + communications(ConversationId: string, id: string): CommunicationContext; + /** Implementation */ + communications(ConversationId: string, id?: string): CommunicationListInstance | CommunicationContext { + const listInstance = CommunicationListInstance(this, ConversationId); + if (id !== undefined) { + return listInstance.get(id); + } + return listInstance; + } + + /** Getter for configurations resource */ + get configurations(): ConfigurationListInstance { + this._configurations = this._configurations || ConfigurationListInstance(this); + return this._configurations; + } + + /** Getter for conversations resource */ + get conversations(): ConversationListInstance { + this._conversations = this._conversations || ConversationListInstance(this); + return this._conversations; + } + + /** Getter for operations resource */ + get operations(): OperationListInstance { + this._operations = this._operations || OperationListInstance(this); + return this._operations; + } + + /** Accessor for participants resource - list operations */ + participants(ConversationId: string): ParticipantListInstance; + /** Accessor for participants resource - instance operations */ + participants(ConversationId: string, id: string): ParticipantContext; + /** Implementation */ + participants(ConversationId: string, id?: string): ParticipantListInstance | ParticipantContext { + const listInstance = ParticipantListInstance(this, ConversationId); + if (id !== undefined) { + return listInstance.get(id); + } + return listInstance; + } + +} diff --git a/rest/conversations/v1/addressConfiguration.ts b/rest/conversations/v1/addressConfiguration.ts new file mode 100644 index 000000000..c446f110a --- /dev/null +++ b/rest/conversations/v1/addressConfiguration.ts @@ -0,0 +1,1058 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export type AddressConfigurationAutoCreationType = 'webhook'|'studio'|'default'; + +export type AddressConfigurationMethod = 'get'|'post'; + +/** + * Type of Address, value can be `whatsapp` or `sms`. + */ +export type AddressConfigurationType = 'sms'|'whatsapp'|'messenger'|'gbm'|'email'|'rcs'|'apple'|'chat'; + + + + +/** + * Options to pass to update a AddressConfigurationInstance + */ +export interface AddressConfigurationContextUpdateOptions { + /** The human-readable name of this configuration, limited to 256 characters. Optional. */ + "friendlyName"?: string; + /** Enable/Disable auto-creating conversations for messages to this address */ + "autoCreation.enabled"?: boolean; + /** */ + "autoCreation.type"?: AddressConfigurationAutoCreationType; + /** Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. */ + "autoCreation.conversationServiceSid"?: string; + /** For type `webhook`, the url for the webhook request. */ + "autoCreation.webhookUrl"?: string; + /** */ + "autoCreation.webhookMethod"?: AddressConfigurationMethod; + /** The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` */ + "autoCreation.webhookFilters"?: Array; + /** For type `studio`, the studio flow SID where the webhook should be sent to. */ + "autoCreation.studioFlowSid"?: string; + /** For type `studio`, number of times to retry the webhook request */ + "autoCreation.studioRetryCount"?: number; +} + +/** + * Options to pass to create a AddressConfigurationInstance + */ +export interface AddressConfigurationListInstanceCreateOptions { + /** */ + "type": AddressConfigurationType; + /** The unique address to be configured. The address can be a whatsapp address or phone number */ + "address": string; + /** The human-readable name of this configuration, limited to 256 characters. Optional. */ + "friendlyName"?: string; + /** Enable/Disable auto-creating conversations for messages to this address */ + "autoCreation.enabled"?: boolean; + /** */ + "autoCreation.type"?: AddressConfigurationAutoCreationType; + /** Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. */ + "autoCreation.conversationServiceSid"?: string; + /** For type `webhook`, the url for the webhook request. */ + "autoCreation.webhookUrl"?: string; + /** */ + "autoCreation.webhookMethod"?: AddressConfigurationMethod; + /** The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` */ + "autoCreation.webhookFilters"?: Array; + /** For type `studio`, the studio flow SID where the webhook should be sent to. */ + "autoCreation.studioFlowSid"?: string; + /** For type `studio`, number of times to retry the webhook request */ + "autoCreation.studioRetryCount"?: number; + /** An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. */ + "addressCountry"?: string; +} + +/** + * Options to pass to each + */ +export interface AddressConfigurationListInstanceEachOptions { + /** Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. */ + "type"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AddressConfigurationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AddressConfigurationListInstanceOptions { + /** Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. */ + "type"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AddressConfigurationListInstancePageOptions { + /** Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. */ + "type"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AddressConfigurationContext { + + /** + * Remove a AddressConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a AddressConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a AddressConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: AddressConfigurationInstance) => any): Promise + + /** + * Fetch a AddressConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a AddressConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance + */ + update(callback?: (error: Error | null, item?: AddressConfigurationInstance) => any): Promise; + /** + * Update a AddressConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance + */ + update(params: AddressConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: AddressConfigurationInstance) => any): Promise; + + /** + * Update a AddressConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AddressConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: AddressConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AddressConfigurationContextSolution { + "sid": string; +} + +export class AddressConfigurationContextImpl implements AddressConfigurationContext { + protected _solution: AddressConfigurationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Configuration/Addresses/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AddressConfigurationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AddressConfigurationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AddressConfigurationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: AddressConfigurationContextUpdateOptions | ((error: Error | null, item?: AddressConfigurationInstance) => any),callback?: (error: Error | null, item?: AddressConfigurationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["autoCreation.enabled"] !== undefined) + data["AutoCreation.Enabled"] = serialize.bool(params["autoCreation.enabled"]); + if (params["autoCreation.type"] !== undefined) + data["AutoCreation.Type"] = params["autoCreation.type"]; + if (params["autoCreation.conversationServiceSid"] !== undefined) + data["AutoCreation.ConversationServiceSid"] = params["autoCreation.conversationServiceSid"]; + if (params["autoCreation.webhookUrl"] !== undefined) + data["AutoCreation.WebhookUrl"] = params["autoCreation.webhookUrl"]; + if (params["autoCreation.webhookMethod"] !== undefined) + data["AutoCreation.WebhookMethod"] = params["autoCreation.webhookMethod"]; + if (params["autoCreation.webhookFilters"] !== undefined) + data["AutoCreation.WebhookFilters"] = serialize.map(params["autoCreation.webhookFilters"], (e: string) => (e)); + if (params["autoCreation.studioFlowSid"] !== undefined) + data["AutoCreation.StudioFlowSid"] = params["autoCreation.studioFlowSid"]; + if (params["autoCreation.studioRetryCount"] !== undefined) + data["AutoCreation.StudioRetryCount"] = params["autoCreation.studioRetryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AddressConfigurationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: AddressConfigurationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["autoCreation.enabled"] !== undefined) + data["AutoCreation.Enabled"] = serialize.bool(params["autoCreation.enabled"]); + if (params["autoCreation.type"] !== undefined) + data["AutoCreation.Type"] = params["autoCreation.type"]; + if (params["autoCreation.conversationServiceSid"] !== undefined) + data["AutoCreation.ConversationServiceSid"] = params["autoCreation.conversationServiceSid"]; + if (params["autoCreation.webhookUrl"] !== undefined) + data["AutoCreation.WebhookUrl"] = params["autoCreation.webhookUrl"]; + if (params["autoCreation.webhookMethod"] !== undefined) + data["AutoCreation.WebhookMethod"] = params["autoCreation.webhookMethod"]; + if (params["autoCreation.webhookFilters"] !== undefined) + data["AutoCreation.WebhookFilters"] = serialize.map(params["autoCreation.webhookFilters"], (e: string) => (e)); + if (params["autoCreation.studioFlowSid"] !== undefined) + data["AutoCreation.StudioFlowSid"] = params["autoCreation.studioFlowSid"]; + if (params["autoCreation.studioRetryCount"] !== undefined) + data["AutoCreation.StudioRetryCount"] = params["autoCreation.studioRetryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AddressConfigurationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AddressConfigurationPayload extends TwilioResponsePayload { + address_configurations: AddressConfigurationResource[]; +} + +interface AddressConfigurationResource { + sid: string; + account_sid: string; + type: string; + address: string; + friendly_name: string; + auto_creation: any; + date_created: Date; + date_updated: Date; + url: string; + address_country: string; +} + +export class AddressConfigurationInstance { + protected _solution: AddressConfigurationContextSolution; + protected _context?: AddressConfigurationContext; + + constructor(protected _version: V1, payload: AddressConfigurationResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.type = (payload.type); + this.address = (payload.address); + this.friendlyName = (payload.friendly_name); + this.autoCreation = (payload.auto_creation); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.addressCountry = (payload.address_country); + + this._solution = { sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) the address belongs to + */ + accountSid: string; + /** + * Type of Address, value can be `whatsapp` or `sms`. + */ + type: string; + /** + * The unique address to be configured. The address can be a whatsapp address or phone number + */ + address: string; + /** + * The human-readable name of this configuration, limited to 256 characters. Optional. + */ + friendlyName: string; + /** + * Auto Creation configuration for the address. + */ + autoCreation: any; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this address configuration. + */ + url: string; + /** + * An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + */ + addressCountry: string; + + private get _proxy(): AddressConfigurationContext { + this._context = this._context || new AddressConfigurationContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a AddressConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AddressConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AddressConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: AddressConfigurationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AddressConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a AddressConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance + */ + update(callback?: (error: Error | null, item?: AddressConfigurationInstance) => any): Promise; + /** + * Update a AddressConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance + */ + update(params: AddressConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: AddressConfigurationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: AddressConfigurationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a AddressConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AddressConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: AddressConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + type: this.type, + address: this.address, + friendlyName: this.friendlyName, + autoCreation: this.autoCreation, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + addressCountry: this.addressCountry, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AddressConfigurationSolution { +} + +export interface AddressConfigurationListInstance { + _version: V1; + _solution: AddressConfigurationSolution; + _uri: string; + + (sid: string, ): AddressConfigurationContext; + get(sid: string, ): AddressConfigurationContext; + + + + + + + + + /** + * Create a AddressConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance + */ + create(params: AddressConfigurationListInstanceCreateOptions, callback?: (error: Error | null, item?: AddressConfigurationInstance) => any): Promise; + + /** + * Create a AddressConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AddressConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: AddressConfigurationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams AddressConfigurationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AddressConfigurationInstance, done: (err?: Error) => void) => void): void; + each(params: AddressConfigurationListInstanceEachOptions, callback?: (item: AddressConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AddressConfigurationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AddressConfigurationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AddressConfigurationListInstanceEachOptions, callback?: (item: AddressConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AddressConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AddressConfigurationPage) => any): Promise; + /** + * Retrieve a single target page of AddressConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AddressConfigurationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AddressConfigurationInstance[]) => any): Promise; + list(params: AddressConfigurationListInstanceOptions, callback?: (error: Error | null, items: AddressConfigurationInstance[]) => any): Promise; + /** + * Lists AddressConfigurationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AddressConfigurationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AddressConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AddressConfigurationPage) => any): Promise; + page(params: AddressConfigurationListInstancePageOptions, callback?: (error: Error | null, items: AddressConfigurationPage) => any): Promise; + /** + * Retrieve a single page of AddressConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AddressConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AddressConfigurationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AddressConfigurationListInstance(version: V1): AddressConfigurationListInstance { + const instance = ((sid, ) => instance.get(sid, )) as AddressConfigurationListInstance; + + instance.get = function get(sid, ): AddressConfigurationContext { + return new AddressConfigurationContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Configuration/Addresses`; + + instance.create = function create(params: AddressConfigurationListInstanceCreateOptions, callback?: (error: Error | null, items: AddressConfigurationInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["address"] === null || params["address"] === undefined) { + throw new Error('Required parameter "params[\'address\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + + data["Address"] = params["address"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["autoCreation.enabled"] !== undefined) + data["AutoCreation.Enabled"] = serialize.bool(params["autoCreation.enabled"]); + if (params["autoCreation.type"] !== undefined) + data["AutoCreation.Type"] = params["autoCreation.type"]; + if (params["autoCreation.conversationServiceSid"] !== undefined) + data["AutoCreation.ConversationServiceSid"] = params["autoCreation.conversationServiceSid"]; + if (params["autoCreation.webhookUrl"] !== undefined) + data["AutoCreation.WebhookUrl"] = params["autoCreation.webhookUrl"]; + if (params["autoCreation.webhookMethod"] !== undefined) + data["AutoCreation.WebhookMethod"] = params["autoCreation.webhookMethod"]; + if (params["autoCreation.webhookFilters"] !== undefined) + data["AutoCreation.WebhookFilters"] = serialize.map(params["autoCreation.webhookFilters"], (e: string) => (e)); + if (params["autoCreation.studioFlowSid"] !== undefined) + data["AutoCreation.StudioFlowSid"] = params["autoCreation.studioFlowSid"]; + if (params["autoCreation.studioRetryCount"] !== undefined) + data["AutoCreation.StudioRetryCount"] = params["autoCreation.studioRetryCount"]; + if (params["addressCountry"] !== undefined) + data["AddressCountry"] = params["addressCountry"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AddressConfigurationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AddressConfigurationListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["address"] === null || params["address"] === undefined) { + throw new Error('Required parameter "params[\'address\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + + data["Address"] = params["address"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["autoCreation.enabled"] !== undefined) + data["AutoCreation.Enabled"] = serialize.bool(params["autoCreation.enabled"]); + if (params["autoCreation.type"] !== undefined) + data["AutoCreation.Type"] = params["autoCreation.type"]; + if (params["autoCreation.conversationServiceSid"] !== undefined) + data["AutoCreation.ConversationServiceSid"] = params["autoCreation.conversationServiceSid"]; + if (params["autoCreation.webhookUrl"] !== undefined) + data["AutoCreation.WebhookUrl"] = params["autoCreation.webhookUrl"]; + if (params["autoCreation.webhookMethod"] !== undefined) + data["AutoCreation.WebhookMethod"] = params["autoCreation.webhookMethod"]; + if (params["autoCreation.webhookFilters"] !== undefined) + data["AutoCreation.WebhookFilters"] = serialize.map(params["autoCreation.webhookFilters"], (e: string) => (e)); + if (params["autoCreation.studioFlowSid"] !== undefined) + data["AutoCreation.StudioFlowSid"] = params["autoCreation.studioFlowSid"]; + if (params["autoCreation.studioRetryCount"] !== undefined) + data["AutoCreation.StudioRetryCount"] = params["autoCreation.studioRetryCount"]; + if (params["addressCountry"] !== undefined) + data["AddressCountry"] = params["addressCountry"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AddressConfigurationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AddressConfigurationListInstancePageOptions | ((error: Error | null, items: AddressConfigurationPage) => any), callback?: (error: Error | null, items: AddressConfigurationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AddressConfigurationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AddressConfigurationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AddressConfigurationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AddressConfigurationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AddressConfigurationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AddressConfigurationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AddressConfigurationPage extends Page { +/** +* Initialize the AddressConfigurationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: AddressConfigurationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AddressConfigurationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AddressConfigurationResource): AddressConfigurationInstance { + + return new AddressConfigurationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/configuration.ts b/rest/conversations/v1/configuration.ts new file mode 100644 index 000000000..b819c3544 --- /dev/null +++ b/rest/conversations/v1/configuration.ts @@ -0,0 +1,462 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { WebhookListInstance } from "./configuration/webhook"; + + + + +/** + * Options to pass to update a ConfigurationInstance + */ +export interface ConfigurationContextUpdateOptions { + /** The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. */ + "defaultChatServiceSid"?: string; + /** The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. */ + "defaultMessagingServiceSid"?: string; + /** Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. */ + "defaultInactiveTimer"?: string; + /** Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. */ + "defaultClosedTimer"?: string; +} + +export interface ConfigurationContext { + + /** + * Fetch a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Update a ConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(params: ConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConfigurationContextSolution { +} + +export class ConfigurationContextImpl implements ConfigurationContext { + protected _solution: ConfigurationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/Configuration`; + } + + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ConfigurationContextUpdateOptions | ((error: Error | null, item?: ConfigurationInstance) => any),callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["defaultChatServiceSid"] !== undefined) + data["DefaultChatServiceSid"] = params["defaultChatServiceSid"]; + if (params["defaultMessagingServiceSid"] !== undefined) + data["DefaultMessagingServiceSid"] = params["defaultMessagingServiceSid"]; + if (params["defaultInactiveTimer"] !== undefined) + data["DefaultInactiveTimer"] = params["defaultInactiveTimer"]; + if (params["defaultClosedTimer"] !== undefined) + data["DefaultClosedTimer"] = params["defaultClosedTimer"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ConfigurationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["defaultChatServiceSid"] !== undefined) + data["DefaultChatServiceSid"] = params["defaultChatServiceSid"]; + if (params["defaultMessagingServiceSid"] !== undefined) + data["DefaultMessagingServiceSid"] = params["defaultMessagingServiceSid"]; + if (params["defaultInactiveTimer"] !== undefined) + data["DefaultInactiveTimer"] = params["defaultInactiveTimer"]; + if (params["defaultClosedTimer"] !== undefined) + data["DefaultClosedTimer"] = params["defaultClosedTimer"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConfigurationPayload extends ConfigurationResource {} + +interface ConfigurationResource { + account_sid: string; + default_chat_service_sid: string; + default_messaging_service_sid: string; + default_inactive_timer: string; + default_closed_timer: string; + url: string; + links: Record; +} + +export class ConfigurationInstance { + protected _solution: ConfigurationContextSolution; + protected _context?: ConfigurationContext; + + constructor(protected _version: V1, payload: ConfigurationResource) { + + this.accountSid = (payload.account_sid); + this.defaultChatServiceSid = (payload.default_chat_service_sid); + this.defaultMessagingServiceSid = (payload.default_messaging_service_sid); + this.defaultInactiveTimer = (payload.default_inactive_timer); + this.defaultClosedTimer = (payload.default_closed_timer); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this configuration. + */ + accountSid: string; + /** + * The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) used when creating a conversation. + */ + defaultChatServiceSid: string; + /** + * The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) used when creating a conversation. + */ + defaultMessagingServiceSid: string; + /** + * Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + */ + defaultInactiveTimer: string; + /** + * Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + */ + defaultClosedTimer: string; + /** + * An absolute API resource URL for this global configuration. + */ + url: string; + /** + * Contains absolute API resource URLs to access the webhook and default service configurations. + */ + links: Record; + + private get _proxy(): ConfigurationContext { + this._context = this._context || new ConfigurationContextImpl(this._version); + return this._context; + } + + /** + * Fetch a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Update a ConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(params: ConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + defaultChatServiceSid: this.defaultChatServiceSid, + defaultMessagingServiceSid: this.defaultMessagingServiceSid, + defaultInactiveTimer: this.defaultInactiveTimer, + defaultClosedTimer: this.defaultClosedTimer, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConfigurationSolution { +} + +export interface ConfigurationListInstance { + _version: V1; + _solution: ConfigurationSolution; + _uri: string; + + (): ConfigurationContext; + get(): ConfigurationContext; + + _webhooks?: WebhookListInstance; + webhooks: WebhookListInstance; + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConfigurationListInstance(version: V1): ConfigurationListInstance { + const instance = (() => instance.get()) as ConfigurationListInstance; + + instance.get = function get(): ConfigurationContext { + return new ConfigurationContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + Object.defineProperty(instance, "webhooks", { + get: function webhooks() { + if (!instance._webhooks) { + instance._webhooks = WebhookListInstance(instance._version); + } + return instance._webhooks; + } + }); + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/conversations/v1/configuration/webhook.ts b/rest/conversations/v1/configuration/webhook.ts new file mode 100644 index 000000000..ef21f7021 --- /dev/null +++ b/rest/conversations/v1/configuration/webhook.ts @@ -0,0 +1,460 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The HTTP method to be used when sending a webhook request. + */ +export type WebhookMethod = 'GET'|'POST'; + +/** + * The routing target of the webhook. Can be ordinary or route internally to Flex + */ +export type WebhookTarget = 'webhook'|'flex'; + + + +/** + * Options to pass to update a WebhookInstance + */ +export interface WebhookContextUpdateOptions { + /** The HTTP method to be used when sending a webhook request. */ + "method"?: string; + /** The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` */ + "filters"?: Array; + /** The absolute url the pre-event webhook request should be sent to. */ + "preWebhookUrl"?: string; + /** The absolute url the post-event webhook request should be sent to. */ + "postWebhookUrl"?: string; + /** */ + "target"?: WebhookTarget; +} + +export interface WebhookContext { + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WebhookContextSolution { +} + +export class WebhookContextImpl implements WebhookContext { + protected _solution: WebhookContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/Configuration/Webhooks`; + } + + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: WebhookInstance) => any),callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["method"] !== undefined) + data["Method"] = params["method"]; + if (params["filters"] !== undefined) + data["Filters"] = serialize.map(params["filters"], (e: string) => (e)); + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["target"] !== undefined) + data["Target"] = params["target"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["method"] !== undefined) + data["Method"] = params["method"]; + if (params["filters"] !== undefined) + data["Filters"] = serialize.map(params["filters"], (e: string) => (e)); + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["target"] !== undefined) + data["Target"] = params["target"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WebhookPayload extends WebhookResource {} + +interface WebhookResource { + account_sid: string; + method: WebhookMethod; + filters: Array; + pre_webhook_url: string; + post_webhook_url: string; + target: WebhookTarget; + url: string; +} + +export class WebhookInstance { + protected _solution: WebhookContextSolution; + protected _context?: WebhookContext; + + constructor(protected _version: V1, payload: WebhookResource) { + + this.accountSid = (payload.account_sid); + this.method = payload.method; + this.filters = (payload.filters); + this.preWebhookUrl = (payload.pre_webhook_url); + this.postWebhookUrl = (payload.post_webhook_url); + this.target = payload.target; + this.url = (payload.url); + + this._solution = { }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + method: WebhookMethod; + /** + * The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + */ + filters: Array; + /** + * The absolute url the pre-event webhook request should be sent to. + */ + preWebhookUrl: string; + /** + * The absolute url the post-event webhook request should be sent to. + */ + postWebhookUrl: string; + target: WebhookTarget; + /** + * An absolute API resource API resource URL for this webhook. + */ + url: string; + + private get _proxy(): WebhookContext { + this._context = this._context || new WebhookContextImpl(this._version); + return this._context; + } + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + method: this.method, + filters: this.filters, + preWebhookUrl: this.preWebhookUrl, + postWebhookUrl: this.postWebhookUrl, + target: this.target, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WebhookSolution { +} + +export interface WebhookListInstance { + _version: V1; + _solution: WebhookSolution; + _uri: string; + + (): WebhookContext; + get(): WebhookContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WebhookListInstance(version: V1): WebhookListInstance { + const instance = (() => instance.get()) as WebhookListInstance; + + instance.get = function get(): WebhookContext { + return new WebhookContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/conversations/v1/conversation.ts b/rest/conversations/v1/conversation.ts new file mode 100644 index 000000000..0dc9860c4 --- /dev/null +++ b/rest/conversations/v1/conversation.ts @@ -0,0 +1,1238 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { MessageListInstance } from "./conversation/message"; +import { ParticipantListInstance } from "./conversation/participant"; +import { WebhookListInstance } from "./conversation/webhook"; + + +/** + * Current state of this conversation. Can be either `initializing`, `active`, `inactive` or `closed` and defaults to `active` + */ +export type ConversationState = 'initializing'|'inactive'|'active'|'closed'; + +export type ConversationWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a ConversationInstance + */ +export interface ConversationContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ConversationWebhookEnabledType; +} + + +/** + * Options to pass to update a ConversationInstance + */ +export interface ConversationContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ConversationWebhookEnabledType; + /** The human-readable name of this conversation, limited to 256 characters. Optional. */ + "friendlyName"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. */ + "dateUpdated"?: Date; + /** An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. */ + "messagingServiceSid"?: string; + /** */ + "state"?: ConversationState; + /** ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. */ + "timers.inactive"?: string; + /** ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. */ + "timers.closed"?: string; + /** An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\\\'s `sid` in the URL. */ + "uniqueName"?: string; + /** The default email address that will be used when sending outbound emails in this conversation. */ + "bindings.email.address"?: string; + /** The default name that will be used when sending outbound emails in this conversation. */ + "bindings.email.name"?: string; +} + +/** + * Options to pass to create a ConversationInstance + */ +export interface ConversationListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ConversationWebhookEnabledType; + /** The human-readable name of this conversation, limited to 256 characters. Optional. */ + "friendlyName"?: string; + /** An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\\\'s `sid` in the URL. */ + "uniqueName"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. */ + "dateUpdated"?: Date; + /** The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. */ + "messagingServiceSid"?: string; + /** An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** */ + "state"?: ConversationState; + /** ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. */ + "timers.inactive"?: string; + /** ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. */ + "timers.closed"?: string; + /** The default email address that will be used when sending outbound emails in this conversation. */ + "bindings.email.address"?: string; + /** The default name that will be used when sending outbound emails in this conversation. */ + "bindings.email.name"?: string; +} + +/** + * Options to pass to each + */ +export interface ConversationListInstanceEachOptions { + /** Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "startDate"?: string; + /** Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "endDate"?: string; + /** State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` */ + "state"?: ConversationState; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConversationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConversationListInstanceOptions { + /** Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "startDate"?: string; + /** Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "endDate"?: string; + /** State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` */ + "state"?: ConversationState; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConversationListInstancePageOptions { + /** Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "startDate"?: string; + /** Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "endDate"?: string; + /** State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` */ + "state"?: ConversationState; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ConversationContext { + messages: MessageListInstance; + participants: ParticipantListInstance; + webhooks: WebhookListInstance; + + /** + * Remove a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + remove(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + removeWithHttpInfo(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + + /** + * Fetch a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Update a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(params: ConversationContextUpdateOptions, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + /** + * Update a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConversationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConversationContextSolution { + "sid": string; +} + +export class ConversationContextImpl implements ConversationContext { + protected _solution: ConversationContextSolution; + protected _uri: string; + + protected _messages?: MessageListInstance; + protected _participants?: ParticipantListInstance; + protected _webhooks?: WebhookListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Conversations/${sid}`; + } + + get messages(): MessageListInstance { + this._messages = this._messages || MessageListInstance(this._version, this._solution.sid); + return this._messages; + } + + get participants(): ParticipantListInstance { + this._participants = this._participants || ParticipantListInstance(this._version, this._solution.sid); + return this._participants; + } + + get webhooks(): WebhookListInstance { + this._webhooks = this._webhooks || WebhookListInstance(this._version, this._solution.sid); + return this._webhooks; + } + + remove(params?: ConversationContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: ConversationContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ConversationContextUpdateOptions | ((error: Error | null, item?: ConversationInstance) => any),callback?: (error: Error | null, item?: ConversationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ConversationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConversationPayload extends TwilioResponsePayload { + conversations: ConversationResource[]; +} + +interface ConversationResource { + account_sid: string; + chat_service_sid: string; + messaging_service_sid: string; + sid: string; + friendly_name: string; + unique_name: string; + attributes: string; + state: ConversationState; + date_created: Date; + date_updated: Date; + timers: any; + url: string; + links: Record; + bindings: any; +} + +export class ConversationInstance { + protected _solution: ConversationContextSolution; + protected _context?: ConversationContext; + + constructor(protected _version: V1, payload: ConversationResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.messagingServiceSid = (payload.messaging_service_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.attributes = (payload.attributes); + this.state = payload.state; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.timers = (payload.timers); + this.url = (payload.url); + this.links = (payload.links); + this.bindings = (payload.bindings); + + this._solution = { sid: sid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + /** + * The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + */ + chatServiceSid: string; + /** + * The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + */ + messagingServiceSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The human-readable name of this conversation, limited to 256 characters. Optional. + */ + friendlyName: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\'s `sid` in the URL. + */ + uniqueName: string; + /** + * An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + attributes: string; + state: ConversationState; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + /** + * Timer date values representing state update for this conversation. + */ + timers: any; + /** + * An absolute API resource URL for this conversation. + */ + url: string; + /** + * Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + */ + links: Record; + bindings: any; + + private get _proxy(): ConversationContext { + this._context = this._context || new ConversationContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + remove(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + removeWithHttpInfo(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Update a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(params: ConversationContextUpdateOptions, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConversationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the messages. + */ + messages(): MessageListInstance { + return this._proxy.messages; + } + + /** + * Access the participants. + */ + participants(): ParticipantListInstance { + return this._proxy.participants; + } + + /** + * Access the webhooks. + */ + webhooks(): WebhookListInstance { + return this._proxy.webhooks; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + messagingServiceSid: this.messagingServiceSid, + sid: this.sid, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + attributes: this.attributes, + state: this.state, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + timers: this.timers, + url: this.url, + links: this.links, + bindings: this.bindings, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConversationSolution { +} + +export interface ConversationListInstance { + _version: V1; + _solution: ConversationSolution; + _uri: string; + + (sid: string, ): ConversationContext; + get(sid: string, ): ConversationContext; + + + + + + + + + /** + * Create a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + create(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Create a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + create(params: ConversationListInstanceCreateOptions, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + /** + * Create a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + createWithHttpInfo(params: ConversationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ConversationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + each(params: ConversationListInstanceEachOptions, callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConversationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConversationListInstanceEachOptions, callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConversationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConversationPage) => any): Promise; + /** + * Retrieve a single target page of ConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConversationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConversationInstance[]) => any): Promise; + list(params: ConversationListInstanceOptions, callback?: (error: Error | null, items: ConversationInstance[]) => any): Promise; + /** + * Lists ConversationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConversationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConversationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConversationPage) => any): Promise; + page(params: ConversationListInstancePageOptions, callback?: (error: Error | null, items: ConversationPage) => any): Promise; + /** + * Retrieve a single page of ConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConversationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConversationListInstance(version: V1): ConversationListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ConversationListInstance; + + instance.get = function get(sid, ): ConversationContext { + return new ConversationContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Conversations`; + + instance.create = function create(params?: ConversationListInstanceCreateOptions | ((error: Error | null, items: ConversationInstance) => any), callback?: (error: Error | null, items: ConversationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ConversationListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ConversationListInstancePageOptions | ((error: Error | null, items: ConversationPage) => any), callback?: (error: Error | null, items: ConversationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["startDate"] !== undefined) + data["StartDate"] = params["startDate"]; + if (params["endDate"] !== undefined) + data["EndDate"] = params["endDate"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConversationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConversationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConversationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConversationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["startDate"] !== undefined) + data["StartDate"] = params["startDate"]; + if (params["endDate"] !== undefined) + data["EndDate"] = params["endDate"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConversationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConversationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConversationPage extends Page { +/** +* Initialize the ConversationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ConversationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ConversationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConversationResource): ConversationInstance { + + return new ConversationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/conversation/message.ts b/rest/conversations/v1/conversation/message.ts new file mode 100644 index 000000000..7ee5e9d6c --- /dev/null +++ b/rest/conversations/v1/conversation/message.ts @@ -0,0 +1,1167 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { DeliveryReceiptListInstance } from "./message/deliveryReceipt"; + + +export type MessageOrderType = 'asc'|'desc'; + +export type MessageWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a MessageInstance + */ +export interface MessageContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; +} + + +/** + * Options to pass to update a MessageInstance + */ +export interface MessageContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; + /** The channel specific identifier of the message\\\'s author. Defaults to `system`. */ + "author"?: string; + /** The content of the message, can be up to 1,600 characters long. */ + "body"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. `null` if the message has not been edited. */ + "dateUpdated"?: Date; + /** A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** The subject of the message, can be up to 256 characters long. */ + "subject"?: string; +} + +/** + * Options to pass to create a MessageInstance + */ +export interface MessageListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; + /** The channel specific identifier of the message\\\'s author. Defaults to `system`. */ + "author"?: string; + /** The content of the message, can be up to 1,600 characters long. */ + "body"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. `null` if the message has not been edited. */ + "dateUpdated"?: Date; + /** A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** The Media SID to be attached to the new Message. */ + "mediaSid"?: string; + /** The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. */ + "contentSid"?: string; + /** A structurally valid JSON string that contains values to resolve Rich Content template variables. */ + "contentVariables"?: string; + /** The subject of the message, can be up to 256 characters long. */ + "subject"?: string; +} + +/** + * Options to pass to each + */ +export interface MessageListInstanceEachOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MessageInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MessageListInstanceOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MessageListInstancePageOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MessageContext { + deliveryReceipts: DeliveryReceiptListInstance; + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + remove(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + removeWithHttpInfo(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MessageContextSolution { + "conversationSid": string; + "sid": string; +} + +export class MessageContextImpl implements MessageContext { + protected _solution: MessageContextSolution; + protected _uri: string; + + protected _deliveryReceipts?: DeliveryReceiptListInstance; + + constructor(protected _version: V1, conversationSid: string, sid: string) { + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { conversationSid, sid, }; + this._uri = `/Conversations/${conversationSid}/Messages/${sid}`; + } + + get deliveryReceipts(): DeliveryReceiptListInstance { + this._deliveryReceipts = this._deliveryReceipts || DeliveryReceiptListInstance(this._version, this._solution.conversationSid, this._solution.sid); + return this._deliveryReceipts; + } + + remove(params?: MessageContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: MessageContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MessageContextUpdateOptions | ((error: Error | null, item?: MessageInstance) => any),callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["author"] !== undefined) + data["Author"] = params["author"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["subject"] !== undefined) + data["Subject"] = params["subject"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MessageContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["author"] !== undefined) + data["Author"] = params["author"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["subject"] !== undefined) + data["Subject"] = params["subject"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MessagePayload extends TwilioResponsePayload { + messages: MessageResource[]; +} + +interface MessageResource { + account_sid: string; + conversation_sid: string; + sid: string; + index: number; + author: string; + body: string; + media: Array; + attributes: string; + participant_sid: string; + date_created: Date; + date_updated: Date; + url: string; + delivery: any; + links: Record; + content_sid: string; +} + +export class MessageInstance { + protected _solution: MessageContextSolution; + protected _context?: MessageContext; + + constructor(protected _version: V1, payload: MessageResource, conversationSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.conversationSid = (payload.conversation_sid); + this.sid = (payload.sid); + this.index = deserialize.integer(payload.index); + this.author = (payload.author); + this.body = (payload.body); + this.media = (payload.media); + this.attributes = (payload.attributes); + this.participantSid = (payload.participant_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.delivery = (payload.delivery); + this.links = (payload.links); + this.contentSid = (payload.content_sid); + + this._solution = { conversationSid, sid: sid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this message. + */ + accountSid: string; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + */ + conversationSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The index of the message within the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource). Indices may skip numbers, but will always be in order of when the message was received. + */ + index: number; + /** + * The channel specific identifier of the message\'s author. Defaults to `system`. + */ + author: string; + /** + * The content of the message, can be up to 1,600 characters long. + */ + body: string; + /** + * An array of objects that describe the Message\'s media, if the message contains media. Each object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object\'s file size in bytes. If the Message has no media, this value is `null`. + */ + media: Array; + /** + * A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + attributes: string; + /** + * The unique ID of messages\'s author participant. Null in case of `system` sent message. + */ + participantSid: string; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. `null` if the message has not been edited. + */ + dateUpdated: Date; + /** + * An absolute API resource API URL for this message. + */ + url: string; + /** + * An object that contains the summary of delivery statuses for the message to non-chat participants. + */ + delivery: any; + /** + * Contains an absolute API resource URL to access the delivery & read receipts of this message. + */ + links: Record; + /** + * The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template. + */ + contentSid: string; + + private get _proxy(): MessageContext { + this._context = this._context || new MessageContextImpl(this._version, this._solution.conversationSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + remove(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + removeWithHttpInfo(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MessageInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the deliveryReceipts. + */ + deliveryReceipts(): DeliveryReceiptListInstance { + return this._proxy.deliveryReceipts; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + conversationSid: this.conversationSid, + sid: this.sid, + index: this.index, + author: this.author, + body: this.body, + media: this.media, + attributes: this.attributes, + participantSid: this.participantSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + delivery: this.delivery, + links: this.links, + contentSid: this.contentSid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MessageSolution { + conversationSid: string; +} + +export interface MessageListInstance { + _version: V1; + _solution: MessageSolution; + _uri: string; + + (sid: string, ): MessageContext; + get(sid: string, ): MessageContext; + + + + + + + + + /** + * Create a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Create a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Create a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MessageInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + each(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MessageInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single target page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MessageInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + list(params: MessageListInstanceOptions, callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + /** + * Lists MessageInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MessageListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MessagePage) => any): Promise; + page(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessageListInstance(version: V1, conversationSid: string): MessageListInstance { + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MessageListInstance; + + instance.get = function get(sid, ): MessageContext { + return new MessageContextImpl(version, conversationSid, sid); + } + + instance._version = version; + instance._solution = { conversationSid, }; + instance._uri = `/Conversations/${conversationSid}/Messages`; + + instance.create = function create(params?: MessageListInstanceCreateOptions | ((error: Error | null, items: MessageInstance) => any), callback?: (error: Error | null, items: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["author"] !== undefined) + data["Author"] = params["author"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["mediaSid"] !== undefined) + data["MediaSid"] = params["mediaSid"]; + if (params["contentSid"] !== undefined) + data["ContentSid"] = params["contentSid"]; + if (params["contentVariables"] !== undefined) + data["ContentVariables"] = params["contentVariables"]; + if (params["subject"] !== undefined) + data["Subject"] = params["subject"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.conversationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: MessageListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["author"] !== undefined) + data["Author"] = params["author"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["mediaSid"] !== undefined) + data["MediaSid"] = params["mediaSid"]; + if (params["contentSid"] !== undefined) + data["ContentSid"] = params["contentSid"]; + if (params["contentVariables"] !== undefined) + data["ContentVariables"] = params["contentVariables"]; + if (params["subject"] !== undefined) + data["Subject"] = params["subject"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.conversationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MessageListInstancePageOptions | ((error: Error | null, items: MessagePage) => any), callback?: (error: Error | null, items: MessagePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MessagePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MessagePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MessageListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MessagePage extends Page { +/** +* Initialize the MessagePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: MessageSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MessageInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MessageResource): MessageInstance { + + return new MessageInstance( + this._version, + payload, + this._solution.conversationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/conversation/message/deliveryReceipt.ts b/rest/conversations/v1/conversation/message/deliveryReceipt.ts new file mode 100644 index 000000000..16c90917d --- /dev/null +++ b/rest/conversations/v1/conversation/message/deliveryReceipt.ts @@ -0,0 +1,610 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The message delivery status, can be `read`, `failed`, `delivered`, `undelivered`, `sent` or null. + */ +export type DeliveryReceiptDeliveryStatus = 'read'|'failed'|'delivered'|'undelivered'|'sent'; + + + +/** + * Options to pass to each + */ +export interface DeliveryReceiptListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DeliveryReceiptInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DeliveryReceiptListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DeliveryReceiptListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface DeliveryReceiptContext { + + /** + * Fetch a DeliveryReceiptInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeliveryReceiptInstance + */ + fetch(callback?: (error: Error | null, item?: DeliveryReceiptInstance) => any): Promise + + /** + * Fetch a DeliveryReceiptInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeliveryReceiptInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DeliveryReceiptContextSolution { + "conversationSid": string; + "messageSid": string; + "sid": string; +} + +export class DeliveryReceiptContextImpl implements DeliveryReceiptContext { + protected _solution: DeliveryReceiptContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, conversationSid: string, messageSid: string, sid: string) { + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + if (!isValidPathParam(messageSid)) { + throw new Error('Parameter \'messageSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { conversationSid, messageSid, sid, }; + this._uri = `/Conversations/${conversationSid}/Messages/${messageSid}/Receipts/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: DeliveryReceiptInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DeliveryReceiptInstance(operationVersion, payload, instance._solution.conversationSid, instance._solution.messageSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new DeliveryReceiptInstance(operationVersion, response.body, instance._solution.conversationSid, instance._solution.messageSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DeliveryReceiptPayload extends TwilioResponsePayload { + delivery_receipts: DeliveryReceiptResource[]; +} + +interface DeliveryReceiptResource { + account_sid: string; + conversation_sid: string; + sid: string; + message_sid: string; + channel_message_sid: string; + participant_sid: string; + status: DeliveryReceiptDeliveryStatus; + error_code: number; + date_created: Date; + date_updated: Date; + url: string; +} + +export class DeliveryReceiptInstance { + protected _solution: DeliveryReceiptContextSolution; + protected _context?: DeliveryReceiptContext; + + constructor(protected _version: V1, payload: DeliveryReceiptResource, conversationSid: string, messageSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.conversationSid = (payload.conversation_sid); + this.sid = (payload.sid); + this.messageSid = (payload.message_sid); + this.channelMessageSid = (payload.channel_message_sid); + this.participantSid = (payload.participant_sid); + this.status = payload.status; + this.errorCode = deserialize.integer(payload.error_code); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { conversationSid, messageSid, sid: sid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + */ + accountSid: string; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + */ + conversationSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to + */ + messageSid: string; + /** + * A messaging channel-specific identifier for the message delivered to participant e.g. `SMxx` for SMS, `WAxx` for Whatsapp etc. + */ + channelMessageSid: string; + /** + * The unique ID of the participant the delivery receipt belongs to. + */ + participantSid: string; + status: DeliveryReceiptDeliveryStatus; + /** + * The message [delivery error code](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors) for a `failed` status, + */ + errorCode: number; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. `null` if the delivery receipt has not been updated. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this delivery receipt. + */ + url: string; + + private get _proxy(): DeliveryReceiptContext { + this._context = this._context || new DeliveryReceiptContextImpl(this._version, this._solution.conversationSid, this._solution.messageSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a DeliveryReceiptInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeliveryReceiptInstance + */ + fetch(callback?: (error: Error | null, item?: DeliveryReceiptInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DeliveryReceiptInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeliveryReceiptInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + conversationSid: this.conversationSid, + sid: this.sid, + messageSid: this.messageSid, + channelMessageSid: this.channelMessageSid, + participantSid: this.participantSid, + status: this.status, + errorCode: this.errorCode, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DeliveryReceiptSolution { + conversationSid: string; + messageSid: string; +} + +export interface DeliveryReceiptListInstance { + _version: V1; + _solution: DeliveryReceiptSolution; + _uri: string; + + (sid: string, ): DeliveryReceiptContext; + get(sid: string, ): DeliveryReceiptContext; + + + + + + /** + * Streams DeliveryReceiptInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DeliveryReceiptInstance, done: (err?: Error) => void) => void): void; + each(params: DeliveryReceiptListInstanceEachOptions, callback?: (item: DeliveryReceiptInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DeliveryReceiptInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DeliveryReceiptInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DeliveryReceiptListInstanceEachOptions, callback?: (item: DeliveryReceiptInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DeliveryReceiptInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DeliveryReceiptPage) => any): Promise; + /** + * Retrieve a single target page of DeliveryReceiptInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists DeliveryReceiptInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DeliveryReceiptInstance[]) => any): Promise; + list(params: DeliveryReceiptListInstanceOptions, callback?: (error: Error | null, items: DeliveryReceiptInstance[]) => any): Promise; + /** + * Lists DeliveryReceiptInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: DeliveryReceiptListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of DeliveryReceiptInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DeliveryReceiptPage) => any): Promise; + page(params: DeliveryReceiptListInstancePageOptions, callback?: (error: Error | null, items: DeliveryReceiptPage) => any): Promise; + /** + * Retrieve a single page of DeliveryReceiptInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: DeliveryReceiptListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DeliveryReceiptListInstance(version: V1, conversationSid: string, messageSid: string): DeliveryReceiptListInstance { + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + if (!isValidPathParam(messageSid)) { + throw new Error('Parameter \'messageSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as DeliveryReceiptListInstance; + + instance.get = function get(sid, ): DeliveryReceiptContext { + return new DeliveryReceiptContextImpl(version, conversationSid, messageSid, sid); + } + + instance._version = version; + instance._solution = { conversationSid, messageSid, }; + instance._uri = `/Conversations/${conversationSid}/Messages/${messageSid}/Receipts`; + + instance.page = function page(params?: DeliveryReceiptListInstancePageOptions | ((error: Error | null, items: DeliveryReceiptPage) => any), callback?: (error: Error | null, items: DeliveryReceiptPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DeliveryReceiptPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DeliveryReceiptPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DeliveryReceiptPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DeliveryReceiptListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DeliveryReceiptPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DeliveryReceiptPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class DeliveryReceiptPage extends Page { +/** +* Initialize the DeliveryReceiptPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: DeliveryReceiptSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DeliveryReceiptInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DeliveryReceiptResource): DeliveryReceiptInstance { + + return new DeliveryReceiptInstance( + this._version, + payload, + this._solution.conversationSid, + this._solution.messageSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/conversation/participant.ts b/rest/conversations/v1/conversation/participant.ts new file mode 100644 index 000000000..a211464f5 --- /dev/null +++ b/rest/conversations/v1/conversation/participant.ts @@ -0,0 +1,1131 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export type ParticipantWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a ParticipantInstance + */ +export interface ParticipantContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ParticipantWebhookEnabledType; +} + + +/** + * Options to pass to update a ParticipantInstance + */ +export interface ParticipantContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ParticipantWebhookEnabledType; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. */ + "dateUpdated"?: Date; + /** An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. */ + "roleSid"?: string; + /** The address of the Twilio phone number that the participant is in contact with. \\\'null\\\' value will remove it. */ + "messagingBinding.proxyAddress"?: string; + /** The address of the Twilio phone number that is used in Group MMS. \\\'null\\\' value will remove it. */ + "messagingBinding.projectedAddress"?: string; + /** A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. */ + "identity"?: string; + /** Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. */ + "lastReadMessageIndex"?: number; + /** Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. */ + "lastReadTimestamp"?: string; +} + +/** + * Options to pass to create a ParticipantInstance + */ +export interface ParticipantListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ParticipantWebhookEnabledType; + /** A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. */ + "identity"?: string; + /** The address of the participant\\\'s device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with proxy_address) is only null when the participant is interacting from an SDK endpoint (see the \\\'identity\\\' field). */ + "messagingBinding.address"?: string; + /** The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the \\\'identity\\\' field). */ + "messagingBinding.proxyAddress"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. */ + "dateUpdated"?: Date; + /** An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. */ + "messagingBinding.projectedAddress"?: string; + /** The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. */ + "roleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface ParticipantListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ParticipantListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ParticipantListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ParticipantContext { + + /** + * Remove a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + remove(params: ParticipantContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + removeWithHttpInfo(params: ParticipantContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Update a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + /** + * Update a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ParticipantContextSolution { + "conversationSid": string; + "sid": string; +} + +export class ParticipantContextImpl implements ParticipantContext { + protected _solution: ParticipantContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, conversationSid: string, sid: string) { + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { conversationSid, sid, }; + this._uri = `/Conversations/${conversationSid}/Participants/${sid}`; + } + + remove(params?: ParticipantContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: ParticipantContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ParticipantContextUpdateOptions | ((error: Error | null, item?: ParticipantInstance) => any),callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["messagingBinding.proxyAddress"] !== undefined) + data["MessagingBinding.ProxyAddress"] = params["messagingBinding.proxyAddress"]; + if (params["messagingBinding.projectedAddress"] !== undefined) + data["MessagingBinding.ProjectedAddress"] = params["messagingBinding.projectedAddress"]; + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["lastReadMessageIndex"] !== undefined) + data["LastReadMessageIndex"] = params["lastReadMessageIndex"]; + if (params["lastReadTimestamp"] !== undefined) + data["LastReadTimestamp"] = params["lastReadTimestamp"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ParticipantContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["messagingBinding.proxyAddress"] !== undefined) + data["MessagingBinding.ProxyAddress"] = params["messagingBinding.proxyAddress"]; + if (params["messagingBinding.projectedAddress"] !== undefined) + data["MessagingBinding.ProjectedAddress"] = params["messagingBinding.projectedAddress"]; + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["lastReadMessageIndex"] !== undefined) + data["LastReadMessageIndex"] = params["lastReadMessageIndex"]; + if (params["lastReadTimestamp"] !== undefined) + data["LastReadTimestamp"] = params["lastReadTimestamp"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ParticipantPayload extends TwilioResponsePayload { + participants: ParticipantResource[]; +} + +interface ParticipantResource { + account_sid: string; + conversation_sid: string; + sid: string; + identity: string; + attributes: string; + messaging_binding: any; + role_sid: string; + date_created: Date; + date_updated: Date; + url: string; + last_read_message_index: number; + last_read_timestamp: string; +} + +export class ParticipantInstance { + protected _solution: ParticipantContextSolution; + protected _context?: ParticipantContext; + + constructor(protected _version: V1, payload: ParticipantResource, conversationSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.conversationSid = (payload.conversation_sid); + this.sid = (payload.sid); + this.identity = (payload.identity); + this.attributes = (payload.attributes); + this.messagingBinding = (payload.messaging_binding); + this.roleSid = (payload.role_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.lastReadMessageIndex = deserialize.integer(payload.last_read_message_index); + this.lastReadTimestamp = (payload.last_read_timestamp); + + this._solution = { conversationSid, sid: sid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + */ + accountSid: string; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + */ + conversationSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + */ + identity: string; + /** + * An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + attributes: string; + /** + * Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + */ + messagingBinding: any; + /** + * The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + */ + roleSid: string; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this participant. + */ + url: string; + /** + * Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + */ + lastReadMessageIndex: number; + /** + * Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + */ + lastReadTimestamp: string; + + private get _proxy(): ParticipantContext { + this._context = this._context || new ParticipantContextImpl(this._version, this._solution.conversationSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + remove(params: ParticipantContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + removeWithHttpInfo(params: ParticipantContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Update a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + conversationSid: this.conversationSid, + sid: this.sid, + identity: this.identity, + attributes: this.attributes, + messagingBinding: this.messagingBinding, + roleSid: this.roleSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + lastReadMessageIndex: this.lastReadMessageIndex, + lastReadTimestamp: this.lastReadTimestamp, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ParticipantSolution { + conversationSid: string; +} + +export interface ParticipantListInstance { + _version: V1; + _solution: ParticipantSolution; + _uri: string; + + (sid: string, ): ParticipantContext; + get(sid: string, ): ParticipantContext; + + + + + + + + + /** + * Create a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + create(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Create a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + create(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + /** + * Create a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + createWithHttpInfo(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ParticipantInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + each(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ParticipantInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + /** + * Retrieve a single target page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ParticipantInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise; + list(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise; + /** + * Lists ParticipantInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + page(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + /** + * Retrieve a single page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ParticipantListInstance(version: V1, conversationSid: string): ParticipantListInstance { + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ParticipantListInstance; + + instance.get = function get(sid, ): ParticipantContext { + return new ParticipantContextImpl(version, conversationSid, sid); + } + + instance._version = version; + instance._solution = { conversationSid, }; + instance._uri = `/Conversations/${conversationSid}/Participants`; + + instance.create = function create(params?: ParticipantListInstanceCreateOptions | ((error: Error | null, items: ParticipantInstance) => any), callback?: (error: Error | null, items: ParticipantInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["messagingBinding.address"] !== undefined) + data["MessagingBinding.Address"] = params["messagingBinding.address"]; + if (params["messagingBinding.proxyAddress"] !== undefined) + data["MessagingBinding.ProxyAddress"] = params["messagingBinding.proxyAddress"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["messagingBinding.projectedAddress"] !== undefined) + data["MessagingBinding.ProjectedAddress"] = params["messagingBinding.projectedAddress"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.conversationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ParticipantListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["messagingBinding.address"] !== undefined) + data["MessagingBinding.Address"] = params["messagingBinding.address"]; + if (params["messagingBinding.proxyAddress"] !== undefined) + data["MessagingBinding.ProxyAddress"] = params["messagingBinding.proxyAddress"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["messagingBinding.projectedAddress"] !== undefined) + data["MessagingBinding.ProjectedAddress"] = params["messagingBinding.projectedAddress"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.conversationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ParticipantPage) => any), callback?: (error: Error | null, items: ParticipantPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ParticipantPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ParticipantPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ParticipantPage extends Page { +/** +* Initialize the ParticipantPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ParticipantSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ParticipantInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ParticipantResource): ParticipantInstance { + + return new ParticipantInstance( + this._version, + payload, + this._solution.conversationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/conversation/webhook.ts b/rest/conversations/v1/conversation/webhook.ts new file mode 100644 index 000000000..688b0c812 --- /dev/null +++ b/rest/conversations/v1/conversation/webhook.ts @@ -0,0 +1,981 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export type WebhookMethod = 'get'|'post'; + +/** + * The target of this webhook: `webhook`, `studio`, `trigger` + */ +export type WebhookTarget = 'webhook'|'trigger'|'studio'; + + + + +/** + * Options to pass to update a WebhookInstance + */ +export interface WebhookContextUpdateOptions { + /** The absolute url the webhook request should be sent to. */ + "configuration.url"?: string; + /** */ + "configuration.method"?: WebhookMethod; + /** The list of events, firing webhook event for this Conversation. */ + "configuration.filters"?: Array; + /** The list of keywords, firing webhook event for this Conversation. */ + "configuration.triggers"?: Array; + /** The studio flow SID, where the webhook should be sent to. */ + "configuration.flowSid"?: string; +} + +/** + * Options to pass to create a WebhookInstance + */ +export interface WebhookListInstanceCreateOptions { + /** */ + "target": WebhookTarget; + /** The absolute url the webhook request should be sent to. */ + "configuration.url"?: string; + /** */ + "configuration.method"?: WebhookMethod; + /** The list of events, firing webhook event for this Conversation. */ + "configuration.filters"?: Array; + /** The list of keywords, firing webhook event for this Conversation. */ + "configuration.triggers"?: Array; + /** The studio flow SID, where the webhook should be sent to. */ + "configuration.flowSid"?: string; + /** The message index for which and it\\\'s successors the webhook will be replayed. Not set by default */ + "configuration.replayAfter"?: number; +} + +/** + * Options to pass to each + */ +export interface WebhookListInstanceEachOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: WebhookInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface WebhookListInstanceOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface WebhookListInstancePageOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface WebhookContext { + + /** + * Remove a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WebhookContextSolution { + "conversationSid": string; + "sid": string; +} + +export class WebhookContextImpl implements WebhookContext { + protected _solution: WebhookContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, conversationSid: string, sid: string) { + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { conversationSid, sid, }; + this._uri = `/Conversations/${conversationSid}/Webhooks/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: WebhookInstance) => any),callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WebhookPayload extends TwilioResponsePayload { + webhooks: WebhookResource[]; +} + +interface WebhookResource { + sid: string; + account_sid: string; + conversation_sid: string; + target: string; + url: string; + configuration: any; + date_created: Date; + date_updated: Date; +} + +export class WebhookInstance { + protected _solution: WebhookContextSolution; + protected _context?: WebhookContext; + + constructor(protected _version: V1, payload: WebhookResource, conversationSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.conversationSid = (payload.conversation_sid); + this.target = (payload.target); + this.url = (payload.url); + this.configuration = (payload.configuration); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { conversationSid, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + */ + conversationSid: string; + /** + * The target of this webhook: `webhook`, `studio`, `trigger` + */ + target: string; + /** + * An absolute API resource URL for this webhook. + */ + url: string; + /** + * The configuration of this webhook. Is defined based on target. + */ + configuration: any; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + + private get _proxy(): WebhookContext { + this._context = this._context || new WebhookContextImpl(this._version, this._solution.conversationSid, this._solution.sid); + return this._context; + } + + /** + * Remove a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + conversationSid: this.conversationSid, + target: this.target, + url: this.url, + configuration: this.configuration, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WebhookSolution { + conversationSid: string; +} + +export interface WebhookListInstance { + _version: V1; + _solution: WebhookSolution; + _uri: string; + + (sid: string, ): WebhookContext; + get(sid: string, ): WebhookContext; + + + + + + + + + /** + * Create a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + create(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + /** + * Create a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + createWithHttpInfo(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams WebhookInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + each(params: WebhookListInstanceEachOptions, callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + /** + * Streams WebhookInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: WebhookListInstanceEachOptions, callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of WebhookInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: WebhookPage) => any): Promise; + /** + * Retrieve a single target page of WebhookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists WebhookInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: WebhookInstance[]) => any): Promise; + list(params: WebhookListInstanceOptions, callback?: (error: Error | null, items: WebhookInstance[]) => any): Promise; + /** + * Lists WebhookInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: WebhookListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of WebhookInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: WebhookPage) => any): Promise; + page(params: WebhookListInstancePageOptions, callback?: (error: Error | null, items: WebhookPage) => any): Promise; + /** + * Retrieve a single page of WebhookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: WebhookListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WebhookListInstance(version: V1, conversationSid: string): WebhookListInstance { + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as WebhookListInstance; + + instance.get = function get(sid, ): WebhookContext { + return new WebhookContextImpl(version, conversationSid, sid); + } + + instance._version = version; + instance._solution = { conversationSid, }; + instance._uri = `/Conversations/${conversationSid}/Webhooks`; + + instance.create = function create(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, items: WebhookInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["target"] === null || params["target"] === undefined) { + throw new Error('Required parameter "params[\'target\']" missing.'); + } + + let data: any = {}; + + + + data["Target"] = params["target"]; + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.replayAfter"] !== undefined) + data["Configuration.ReplayAfter"] = params["configuration.replayAfter"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.conversationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["target"] === null || params["target"] === undefined) { + throw new Error('Required parameter "params[\'target\']" missing.'); + } + + let data: any = {}; + + + + data["Target"] = params["target"]; + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.replayAfter"] !== undefined) + data["Configuration.ReplayAfter"] = params["configuration.replayAfter"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.conversationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: WebhookListInstancePageOptions | ((error: Error | null, items: WebhookPage) => any), callback?: (error: Error | null, items: WebhookPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new WebhookPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: WebhookPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new WebhookPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: WebhookListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebhookPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebhookPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class WebhookPage extends Page { +/** +* Initialize the WebhookPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: WebhookSolution) { + super(version, response, solution); + } + + /** + * Build an instance of WebhookInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: WebhookResource): WebhookInstance { + + return new WebhookInstance( + this._version, + payload, + this._solution.conversationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/conversationWithParticipants.ts b/rest/conversations/v1/conversationWithParticipants.ts new file mode 100644 index 000000000..13e8fbec4 --- /dev/null +++ b/rest/conversations/v1/conversationWithParticipants.ts @@ -0,0 +1,371 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Current state of this conversation. Can be either `initializing`, `active`, `inactive` or `closed` and defaults to `active` + */ +export type ConversationWithParticipantsState = 'initializing'|'inactive'|'active'|'closed'; + +export type ConversationWithParticipantsWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to create a ConversationWithParticipantsInstance + */ +export interface ConversationWithParticipantsListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ConversationWithParticipantsWebhookEnabledType; + /** The human-readable name of this conversation, limited to 256 characters. Optional. */ + "friendlyName"?: string; + /** An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\\\'s `sid` in the URL. */ + "uniqueName"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. */ + "dateUpdated"?: Date; + /** The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. */ + "messagingServiceSid"?: string; + /** An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** */ + "state"?: ConversationWithParticipantsState; + /** ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. */ + "timers.inactive"?: string; + /** ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. */ + "timers.closed"?: string; + /** The default email address that will be used when sending outbound emails in this conversation. */ + "bindings.email.address"?: string; + /** The default name that will be used when sending outbound emails in this conversation. */ + "bindings.email.name"?: string; + /** The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. */ + "participant"?: Array; +} + + +export interface ConversationWithParticipantsSolution { +} + +export interface ConversationWithParticipantsListInstance { + _version: V1; + _solution: ConversationWithParticipantsSolution; + _uri: string; + + + + /** + * Create a ConversationWithParticipantsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationWithParticipantsInstance + */ + create(callback?: (error: Error | null, item?: ConversationWithParticipantsInstance) => any): Promise; + /** + * Create a ConversationWithParticipantsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationWithParticipantsInstance + */ + create(params: ConversationWithParticipantsListInstanceCreateOptions, callback?: (error: Error | null, item?: ConversationWithParticipantsInstance) => any): Promise; + + /** + * Create a ConversationWithParticipantsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationWithParticipantsInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ConversationWithParticipantsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationWithParticipantsInstance with HTTP metadata + */ + createWithHttpInfo(params: ConversationWithParticipantsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConversationWithParticipantsListInstance(version: V1): ConversationWithParticipantsListInstance { + const instance = {} as ConversationWithParticipantsListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/ConversationWithParticipants`; + + instance.create = function create(params?: ConversationWithParticipantsListInstanceCreateOptions | ((error: Error | null, items: ConversationWithParticipantsInstance) => any), callback?: (error: Error | null, items: ConversationWithParticipantsInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + if (params["participant"] !== undefined) + data["Participant"] = serialize.map(params["participant"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationWithParticipantsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ConversationWithParticipantsListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + if (params["participant"] !== undefined) + data["Participant"] = serialize.map(params["participant"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationWithParticipantsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ConversationWithParticipantsPayload extends ConversationWithParticipantsResource {} + +interface ConversationWithParticipantsResource { + account_sid: string; + chat_service_sid: string; + messaging_service_sid: string; + sid: string; + friendly_name: string; + unique_name: string; + attributes: string; + state: ConversationWithParticipantsState; + date_created: Date; + date_updated: Date; + timers: any; + links: Record; + bindings: any; + url: string; +} + +export class ConversationWithParticipantsInstance { + + constructor(protected _version: V1, payload: ConversationWithParticipantsResource) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.messagingServiceSid = (payload.messaging_service_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.attributes = (payload.attributes); + this.state = payload.state; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.timers = (payload.timers); + this.links = (payload.links); + this.bindings = (payload.bindings); + this.url = (payload.url); + + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + /** + * The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + */ + chatServiceSid: string; + /** + * The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + */ + messagingServiceSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The human-readable name of this conversation, limited to 256 characters. Optional. + */ + friendlyName: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\'s `sid` in the URL. + */ + uniqueName: string; + /** + * An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + attributes: string; + state: ConversationWithParticipantsState; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + /** + * Timer date values representing state update for this conversation. + */ + timers: any; + /** + * Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + */ + links: Record; + bindings: any; + /** + * An absolute API resource URL for this conversation. + */ + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + messagingServiceSid: this.messagingServiceSid, + sid: this.sid, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + attributes: this.attributes, + state: this.state, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + timers: this.timers, + links: this.links, + bindings: this.bindings, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/conversations/v1/credential.ts b/rest/conversations/v1/credential.ts new file mode 100644 index 000000000..fb4c04b94 --- /dev/null +++ b/rest/conversations/v1/credential.ts @@ -0,0 +1,977 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The type of push-notification service the credential is for. Can be: `fcm`, `gcm`, or `apn`. + */ +export type CredentialPushType = 'apn'|'gcm'|'fcm'; + + + + +/** + * Options to pass to update a CredentialInstance + */ +export interface CredentialContextUpdateOptions { + /** */ + "type"?: CredentialPushType; + /** A descriptive string that you create to describe the new resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. */ + "certificate"?: string; + /** [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. */ + "privateKey"?: string; + /** [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. */ + "sandbox"?: boolean; + /** [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. */ + "apiKey"?: string; + /** [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. */ + "secret"?: string; +} + +/** + * Options to pass to create a CredentialInstance + */ +export interface CredentialListInstanceCreateOptions { + /** */ + "type": CredentialPushType; + /** A descriptive string that you create to describe the new resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. */ + "certificate"?: string; + /** [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. */ + "privateKey"?: string; + /** [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. */ + "sandbox"?: boolean; + /** [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. */ + "apiKey"?: string; + /** [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. */ + "secret"?: string; +} + +/** + * Options to pass to each + */ +export interface CredentialListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CredentialInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CredentialListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CredentialListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CredentialContext { + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CredentialContextSolution { + "sid": string; +} + +export class CredentialContextImpl implements CredentialContext { + protected _solution: CredentialContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Credentials/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: CredentialInstance) => any),callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CredentialPayload extends TwilioResponsePayload { + credentials: CredentialResource[]; +} + +interface CredentialResource { + sid: string; + account_sid: string; + friendly_name: string; + type: CredentialPushType; + sandbox: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CredentialInstance { + protected _solution: CredentialContextSolution; + protected _context?: CredentialContext; + + constructor(protected _version: V1, payload: CredentialResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.sandbox = (payload.sandbox); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this credential. + */ + accountSid: string; + /** + * The human-readable name of this credential, limited to 64 characters. Optional. + */ + friendlyName: string; + type: CredentialPushType; + /** + * [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + */ + sandbox: string; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this credential. + */ + url: string; + + private get _proxy(): CredentialContext { + this._context = this._context || new CredentialContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + type: this.type, + sandbox: this.sandbox, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CredentialSolution { +} + +export interface CredentialListInstance { + _version: V1; + _solution: CredentialSolution; + _uri: string; + + (sid: string, ): CredentialContext; + get(sid: string, ): CredentialContext; + + + + + + + + + /** + * Create a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Create a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CredentialInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + each(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CredentialInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single target page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CredentialInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + list(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + /** + * Lists CredentialInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CredentialPage) => any): Promise; + page(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CredentialListInstance(version: V1): CredentialListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CredentialListInstance; + + instance.get = function get(sid, ): CredentialContext { + return new CredentialContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Credentials`; + + instance.create = function create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: CredentialInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CredentialListInstancePageOptions | ((error: Error | null, items: CredentialPage) => any), callback?: (error: Error | null, items: CredentialPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CredentialPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CredentialPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CredentialListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CredentialPage extends Page { +/** +* Initialize the CredentialPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: CredentialSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CredentialInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CredentialResource): CredentialInstance { + + return new CredentialInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/participantConversation.ts b/rest/conversations/v1/participantConversation.ts new file mode 100644 index 000000000..4abd1acc4 --- /dev/null +++ b/rest/conversations/v1/participantConversation.ts @@ -0,0 +1,505 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The current state of this User Conversation. One of `inactive`, `active` or `closed`. + */ +export type ParticipantConversationState = 'inactive'|'active'|'closed'; + + +/** + * Options to pass to each + */ +export interface ParticipantConversationListInstanceEachOptions { + /** A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. */ + "identity"?: string; + /** A unique string identifier for the conversation participant who\'s not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. */ + "address"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ParticipantConversationListInstanceOptions { + /** A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. */ + "identity"?: string; + /** A unique string identifier for the conversation participant who\'s not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. */ + "address"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ParticipantConversationListInstancePageOptions { + /** A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. */ + "identity"?: string; + /** A unique string identifier for the conversation participant who\'s not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. */ + "address"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface ParticipantConversationSolution { +} + +export interface ParticipantConversationListInstance { + _version: V1; + _solution: ParticipantConversationSolution; + _uri: string; + + + + + /** + * Streams ParticipantConversationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void): void; + each(params: ParticipantConversationListInstanceEachOptions, callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ParticipantConversationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ParticipantConversationListInstanceEachOptions, callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ParticipantConversationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise; + /** + * Retrieve a single target page of ParticipantConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ParticipantConversationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ParticipantConversationInstance[]) => any): Promise; + list(params: ParticipantConversationListInstanceOptions, callback?: (error: Error | null, items: ParticipantConversationInstance[]) => any): Promise; + /** + * Lists ParticipantConversationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ParticipantConversationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ParticipantConversationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise; + page(params: ParticipantConversationListInstancePageOptions, callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise; + /** + * Retrieve a single page of ParticipantConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ParticipantConversationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ParticipantConversationListInstance(version: V1): ParticipantConversationListInstance { + const instance = {} as ParticipantConversationListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/ParticipantConversations`; + + instance.page = function page(params?: ParticipantConversationListInstancePageOptions | ((error: Error | null, items: ParticipantConversationPage) => any), callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["address"] !== undefined) + data["Address"] = params["address"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ParticipantConversationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ParticipantConversationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ParticipantConversationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["address"] !== undefined) + data["Address"] = params["address"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantConversationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantConversationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ParticipantConversationPayload extends TwilioResponsePayload { + conversations: ParticipantConversationResource[]; +} + +interface ParticipantConversationResource { + account_sid: string; + chat_service_sid: string; + participant_sid: string; + participant_user_sid: string; + participant_identity: string; + participant_messaging_binding: any; + conversation_sid: string; + conversation_unique_name: string; + conversation_friendly_name: string; + conversation_attributes: string; + conversation_date_created: Date; + conversation_date_updated: Date; + conversation_created_by: string; + conversation_state: ParticipantConversationState; + conversation_timers: any; + links: Record; +} + +export class ParticipantConversationInstance { + + constructor(protected _version: V1, payload: ParticipantConversationResource) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.participantSid = (payload.participant_sid); + this.participantUserSid = (payload.participant_user_sid); + this.participantIdentity = (payload.participant_identity); + this.participantMessagingBinding = (payload.participant_messaging_binding); + this.conversationSid = (payload.conversation_sid); + this.conversationUniqueName = (payload.conversation_unique_name); + this.conversationFriendlyName = (payload.conversation_friendly_name); + this.conversationAttributes = (payload.conversation_attributes); + this.conversationDateCreated = deserialize.iso8601DateTime(payload.conversation_date_created); + this.conversationDateUpdated = deserialize.iso8601DateTime(payload.conversation_date_updated); + this.conversationCreatedBy = (payload.conversation_created_by); + this.conversationState = payload.conversation_state; + this.conversationTimers = (payload.conversation_timers); + this.links = (payload.links); + + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + /** + * The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + */ + chatServiceSid: string; + /** + * The unique ID of the [Participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). + */ + participantSid: string; + /** + * The unique string that identifies the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). + */ + participantUserSid: string; + /** + * A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + */ + participantIdentity: string; + /** + * Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + */ + participantMessagingBinding: any; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) this Participant belongs to. + */ + conversationSid: string; + /** + * An application-defined string that uniquely identifies the Conversation resource. + */ + conversationUniqueName: string; + /** + * The human-readable name of this conversation, limited to 256 characters. Optional. + */ + conversationFriendlyName: string; + /** + * An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + conversationAttributes: string; + /** + * The date that this conversation was created, given in ISO 8601 format. + */ + conversationDateCreated: Date; + /** + * The date that this conversation was last updated, given in ISO 8601 format. + */ + conversationDateUpdated: Date; + /** + * Identity of the creator of this Conversation. + */ + conversationCreatedBy: string; + conversationState: ParticipantConversationState; + /** + * Timer date values representing state update for this conversation. + */ + conversationTimers: any; + /** + * Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + */ + links: Record; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + participantSid: this.participantSid, + participantUserSid: this.participantUserSid, + participantIdentity: this.participantIdentity, + participantMessagingBinding: this.participantMessagingBinding, + conversationSid: this.conversationSid, + conversationUniqueName: this.conversationUniqueName, + conversationFriendlyName: this.conversationFriendlyName, + conversationAttributes: this.conversationAttributes, + conversationDateCreated: this.conversationDateCreated, + conversationDateUpdated: this.conversationDateUpdated, + conversationCreatedBy: this.conversationCreatedBy, + conversationState: this.conversationState, + conversationTimers: this.conversationTimers, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class ParticipantConversationPage extends Page { +/** +* Initialize the ParticipantConversationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ParticipantConversationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ParticipantConversationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ParticipantConversationResource): ParticipantConversationInstance { + + return new ParticipantConversationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/role.ts b/rest/conversations/v1/role.ts new file mode 100644 index 000000000..9250fd096 --- /dev/null +++ b/rest/conversations/v1/role.ts @@ -0,0 +1,910 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The type of role. Can be: `conversation` for [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) roles or `service` for [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) roles. + */ +export type RoleRoleType = 'conversation'|'service'; + + + + +/** + * Options to pass to update a RoleInstance + */ +export interface RoleContextUpdateOptions { + /** A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role\\\'s `type`. */ + "permission": Array; +} + +/** + * Options to pass to create a RoleInstance + */ +export interface RoleListInstanceCreateOptions { + /** A descriptive string that you create to describe the new resource. It can be up to 64 characters long. */ + "friendlyName": string; + /** */ + "type": RoleRoleType; + /** A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role\\\'s `type`. */ + "permission": Array; +} + +/** + * Options to pass to each + */ +export interface RoleListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoleInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoleListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoleListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoleContext { + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoleContextSolution { + "sid": string; +} + +export class RoleContextImpl implements RoleContext { + protected _solution: RoleContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Roles/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RolePayload extends TwilioResponsePayload { + roles: RoleResource[]; +} + +interface RoleResource { + sid: string; + account_sid: string; + chat_service_sid: string; + friendly_name: string; + type: RoleRoleType; + permissions: Array; + date_created: Date; + date_updated: Date; + url: string; +} + +export class RoleInstance { + protected _solution: RoleContextSolution; + protected _context?: RoleContext; + + constructor(protected _version: V1, payload: RoleResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.permissions = (payload.permissions); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Role resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Role resource. + */ + accountSid: string; + /** + * The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Role resource is associated with. + */ + chatServiceSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + type: RoleRoleType; + /** + * An array of the permissions the role has been granted. + */ + permissions: Array; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this user role. + */ + url: string; + + private get _proxy(): RoleContext { + this._context = this._context || new RoleContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: RoleInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + friendlyName: this.friendlyName, + type: this.type, + permissions: this.permissions, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoleSolution { +} + +export interface RoleListInstance { + _version: V1; + _solution: RoleSolution; + _uri: string; + + (sid: string, ): RoleContext; + get(sid: string, ): RoleContext; + + + + + + + + + /** + * Create a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Create a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams RoleInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + each(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoleInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single target page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RoleInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + list(params: RoleListInstanceOptions, callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + /** + * Lists RoleInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RoleListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RolePage) => any): Promise; + page(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoleListInstance(version: V1): RoleListInstance { + const instance = ((sid, ) => instance.get(sid, )) as RoleListInstance; + + instance.get = function get(sid, ): RoleContext { + return new RoleContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Roles`; + + instance.create = function create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RoleListInstancePageOptions | ((error: Error | null, items: RolePage) => any), callback?: (error: Error | null, items: RolePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RolePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RolePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoleListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RolePage extends Page { +/** +* Initialize the RolePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: RoleSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoleInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoleResource): RoleInstance { + + return new RoleInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service.ts b/rest/conversations/v1/service.ts new file mode 100644 index 000000000..da21ca860 --- /dev/null +++ b/rest/conversations/v1/service.ts @@ -0,0 +1,840 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { BindingListInstance } from "./service/binding"; +import { ConfigurationListInstance } from "./service/configuration"; +import { ConversationListInstance } from "./service/conversation"; +import { ConversationWithParticipantsListInstance } from "./service/conversationWithParticipants"; +import { ParticipantConversationListInstance } from "./service/participantConversation"; +import { RoleListInstance } from "./service/role"; +import { UserListInstance } from "./service/user"; + + + + + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** The human-readable name of this service, limited to 256 characters. Optional. */ + "friendlyName": string; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + bindings: BindingListInstance; + configuration: ConfigurationListInstance; + conversations: ConversationListInstance; + conversationWithParticipants: ConversationWithParticipantsListInstance; + participantConversations: ParticipantConversationListInstance; + roles: RoleListInstance; + users: UserListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _bindings?: BindingListInstance; + protected _configuration?: ConfigurationListInstance; + protected _conversations?: ConversationListInstance; + protected _conversationWithParticipants?: ConversationWithParticipantsListInstance; + protected _participantConversations?: ParticipantConversationListInstance; + protected _roles?: RoleListInstance; + protected _users?: UserListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get bindings(): BindingListInstance { + this._bindings = this._bindings || BindingListInstance(this._version, this._solution.sid); + return this._bindings; + } + + get configuration(): ConfigurationListInstance { + this._configuration = this._configuration || ConfigurationListInstance(this._version, this._solution.sid); + return this._configuration; + } + + get conversations(): ConversationListInstance { + this._conversations = this._conversations || ConversationListInstance(this._version, this._solution.sid); + return this._conversations; + } + + get conversationWithParticipants(): ConversationWithParticipantsListInstance { + this._conversationWithParticipants = this._conversationWithParticipants || ConversationWithParticipantsListInstance(this._version, this._solution.sid); + return this._conversationWithParticipants; + } + + get participantConversations(): ParticipantConversationListInstance { + this._participantConversations = this._participantConversations || ParticipantConversationListInstance(this._version, this._solution.sid); + return this._participantConversations; + } + + get roles(): RoleListInstance { + this._roles = this._roles || RoleListInstance(this._version, this._solution.sid); + return this._roles; + } + + get users(): UserListInstance { + this._users = this._users || UserListInstance(this._version, this._solution.sid); + return this._users; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + account_sid: string; + sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V1, payload: ServiceResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this service. + */ + accountSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The human-readable name of this service, limited to 256 characters. Optional. + */ + friendlyName: string; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this service. + */ + url: string; + /** + * Contains absolute API resource URLs to access conversations, users, roles, bindings and configuration of this service. + */ + links: Record; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the bindings. + */ + bindings(): BindingListInstance { + return this._proxy.bindings; + } + + /** + * Access the configuration. + */ + configuration(): ConfigurationListInstance { + return this._proxy.configuration; + } + + /** + * Access the conversations. + */ + conversations(): ConversationListInstance { + return this._proxy.conversations; + } + + /** + * Access the conversationWithParticipants. + */ + conversationWithParticipants(): ConversationWithParticipantsListInstance { + return this._proxy.conversationWithParticipants; + } + + /** + * Access the participantConversations. + */ + participantConversations(): ParticipantConversationListInstance { + return this._proxy.participantConversations; + } + + /** + * Access the roles. + */ + roles(): RoleListInstance { + return this._proxy.roles; + } + + /** + * Access the users. + */ + users(): UserListInstance { + return this._proxy.users; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V1; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V1): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ServiceInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service/binding.ts b/rest/conversations/v1/service/binding.ts new file mode 100644 index 000000000..2ab61d896 --- /dev/null +++ b/rest/conversations/v1/service/binding.ts @@ -0,0 +1,697 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The push technology to use for the Binding. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + */ +export type BindingBindingType = 'apn'|'gcm'|'fcm'|'twilsock'; + + + + +/** + * Options to pass to each + */ +export interface BindingListInstanceEachOptions { + /** The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. */ + "bindingType"?: Array; + /** The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BindingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BindingListInstanceOptions { + /** The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. */ + "bindingType"?: Array; + /** The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BindingListInstancePageOptions { + /** The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. */ + "bindingType"?: Array; + /** The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface BindingContext { + + /** + * Remove a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance + */ + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise + + /** + * Fetch a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BindingContextSolution { + "chatServiceSid": string; + "sid": string; +} + +export class BindingContextImpl implements BindingContext { + protected _solution: BindingContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, chatServiceSid: string, sid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { chatServiceSid, sid, }; + this._uri = `/Services/${chatServiceSid}/Bindings/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BindingInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new BindingInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BindingPayload extends TwilioResponsePayload { + bindings: BindingResource[]; +} + +interface BindingResource { + sid: string; + account_sid: string; + chat_service_sid: string; + credential_sid: string; + date_created: Date; + date_updated: Date; + endpoint: string; + identity: string; + binding_type: BindingBindingType; + message_types: Array; + url: string; +} + +export class BindingInstance { + protected _solution: BindingContextSolution; + protected _context?: BindingContext; + + constructor(protected _version: V1, payload: BindingResource, chatServiceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.credentialSid = (payload.credential_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.endpoint = (payload.endpoint); + this.identity = (payload.identity); + this.bindingType = payload.binding_type; + this.messageTypes = (payload.message_types); + this.url = (payload.url); + + this._solution = { chatServiceSid, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this binding. + */ + accountSid: string; + /** + * The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Binding resource is associated with. + */ + chatServiceSid: string; + /** + * The SID of the [Credential](https://www.twilio.com/docs/conversations/api/credential-resource) for the binding. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + */ + credentialSid: string; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + /** + * The unique endpoint identifier for the Binding. The format of this value depends on the `binding_type`. + */ + endpoint: string; + /** + * The application-defined string that uniquely identifies the [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more info. + */ + identity: string; + bindingType: BindingBindingType; + /** + * The [Conversation message types](https://www.twilio.com/docs/chat/push-notification-configuration#push-types) the binding is subscribed to. + */ + messageTypes: Array; + /** + * An absolute API resource URL for this binding. + */ + url: string; + + private get _proxy(): BindingContext { + this._context = this._context || new BindingContextImpl(this._version, this._solution.chatServiceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance + */ + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + credentialSid: this.credentialSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + endpoint: this.endpoint, + identity: this.identity, + bindingType: this.bindingType, + messageTypes: this.messageTypes, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BindingSolution { + chatServiceSid: string; +} + +export interface BindingListInstance { + _version: V1; + _solution: BindingSolution; + _uri: string; + + (sid: string, ): BindingContext; + get(sid: string, ): BindingContext; + + + + + + + + /** + * Streams BindingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + each(params: BindingListInstanceEachOptions, callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BindingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BindingListInstanceEachOptions, callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BindingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BindingPage) => any): Promise; + /** + * Retrieve a single target page of BindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists BindingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BindingInstance[]) => any): Promise; + list(params: BindingListInstanceOptions, callback?: (error: Error | null, items: BindingInstance[]) => any): Promise; + /** + * Lists BindingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: BindingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of BindingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BindingPage) => any): Promise; + page(params: BindingListInstancePageOptions, callback?: (error: Error | null, items: BindingPage) => any): Promise; + /** + * Retrieve a single page of BindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: BindingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BindingListInstance(version: V1, chatServiceSid: string): BindingListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as BindingListInstance; + + instance.get = function get(sid, ): BindingContext { + return new BindingContextImpl(version, chatServiceSid, sid); + } + + instance._version = version; + instance._solution = { chatServiceSid, }; + instance._uri = `/Services/${chatServiceSid}/Bindings`; + + instance.page = function page(params?: BindingListInstancePageOptions | ((error: Error | null, items: BindingPage) => any), callback?: (error: Error | null, items: BindingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["bindingType"] !== undefined) + data["BindingType"] = serialize.map(params["bindingType"], (e: BindingBindingType) => (e)); + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BindingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BindingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BindingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BindingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["bindingType"] !== undefined) + data["BindingType"] = serialize.map(params["bindingType"], (e: BindingBindingType) => (e)); + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BindingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BindingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class BindingPage extends Page { +/** +* Initialize the BindingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: BindingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of BindingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BindingResource): BindingInstance { + + return new BindingInstance( + this._version, + payload, + this._solution.chatServiceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service/configuration.ts b/rest/conversations/v1/service/configuration.ts new file mode 100644 index 000000000..15fed0790 --- /dev/null +++ b/rest/conversations/v1/service/configuration.ts @@ -0,0 +1,484 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { NotificationListInstance } from "./configuration/notification"; +import { WebhookListInstance } from "./configuration/webhook"; + + + + +/** + * Options to pass to update a ConfigurationInstance + */ +export interface ConfigurationContextUpdateOptions { + /** The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. */ + "defaultConversationCreatorRoleSid"?: string; + /** The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. */ + "defaultConversationRoleSid"?: string; + /** The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. */ + "defaultChatServiceRoleSid"?: string; + /** Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. */ + "reachabilityEnabled"?: boolean; +} + +export interface ConfigurationContext { + + /** + * Fetch a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Update a ConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(params: ConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConfigurationContextSolution { + "chatServiceSid": string; +} + +export class ConfigurationContextImpl implements ConfigurationContext { + protected _solution: ConfigurationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, chatServiceSid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + this._solution = { chatServiceSid, }; + this._uri = `/Services/${chatServiceSid}/Configuration`; + } + + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload, instance._solution.chatServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body, instance._solution.chatServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ConfigurationContextUpdateOptions | ((error: Error | null, item?: ConfigurationInstance) => any),callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["defaultConversationCreatorRoleSid"] !== undefined) + data["DefaultConversationCreatorRoleSid"] = params["defaultConversationCreatorRoleSid"]; + if (params["defaultConversationRoleSid"] !== undefined) + data["DefaultConversationRoleSid"] = params["defaultConversationRoleSid"]; + if (params["defaultChatServiceRoleSid"] !== undefined) + data["DefaultChatServiceRoleSid"] = params["defaultChatServiceRoleSid"]; + if (params["reachabilityEnabled"] !== undefined) + data["ReachabilityEnabled"] = serialize.bool(params["reachabilityEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload, instance._solution.chatServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ConfigurationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["defaultConversationCreatorRoleSid"] !== undefined) + data["DefaultConversationCreatorRoleSid"] = params["defaultConversationCreatorRoleSid"]; + if (params["defaultConversationRoleSid"] !== undefined) + data["DefaultConversationRoleSid"] = params["defaultConversationRoleSid"]; + if (params["defaultChatServiceRoleSid"] !== undefined) + data["DefaultChatServiceRoleSid"] = params["defaultChatServiceRoleSid"]; + if (params["reachabilityEnabled"] !== undefined) + data["ReachabilityEnabled"] = serialize.bool(params["reachabilityEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body, instance._solution.chatServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConfigurationPayload extends ConfigurationResource {} + +interface ConfigurationResource { + chat_service_sid: string; + default_conversation_creator_role_sid: string; + default_conversation_role_sid: string; + default_chat_service_role_sid: string; + url: string; + links: Record; + reachability_enabled: boolean; +} + +export class ConfigurationInstance { + protected _solution: ConfigurationContextSolution; + protected _context?: ConfigurationContext; + + constructor(protected _version: V1, payload: ConfigurationResource, chatServiceSid: string) { + + this.chatServiceSid = (payload.chat_service_sid); + this.defaultConversationCreatorRoleSid = (payload.default_conversation_creator_role_sid); + this.defaultConversationRoleSid = (payload.default_conversation_role_sid); + this.defaultChatServiceRoleSid = (payload.default_chat_service_role_sid); + this.url = (payload.url); + this.links = (payload.links); + this.reachabilityEnabled = (payload.reachability_enabled); + + this._solution = { chatServiceSid, }; + } + + /** + * The unique string that we created to identify the Service configuration resource. + */ + chatServiceSid: string; + /** + * The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + */ + defaultConversationCreatorRoleSid: string; + /** + * The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + */ + defaultConversationRoleSid: string; + /** + * The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + */ + defaultChatServiceRoleSid: string; + /** + * An absolute API resource URL for this service configuration. + */ + url: string; + /** + * Contains an absolute API resource URL to access the push notifications configuration of this service. + */ + links: Record; + /** + * Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + */ + reachabilityEnabled: boolean; + + private get _proxy(): ConfigurationContext { + this._context = this._context || new ConfigurationContextImpl(this._version, this._solution.chatServiceSid); + return this._context; + } + + /** + * Fetch a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Update a ConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(params: ConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + chatServiceSid: this.chatServiceSid, + defaultConversationCreatorRoleSid: this.defaultConversationCreatorRoleSid, + defaultConversationRoleSid: this.defaultConversationRoleSid, + defaultChatServiceRoleSid: this.defaultChatServiceRoleSid, + url: this.url, + links: this.links, + reachabilityEnabled: this.reachabilityEnabled, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConfigurationSolution { + chatServiceSid: string; +} + +export interface ConfigurationListInstance { + _version: V1; + _solution: ConfigurationSolution; + _uri: string; + + (): ConfigurationContext; + get(): ConfigurationContext; + + _notifications?: NotificationListInstance; + notifications: NotificationListInstance; + _webhooks?: WebhookListInstance; + webhooks: WebhookListInstance; + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConfigurationListInstance(version: V1, chatServiceSid: string): ConfigurationListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + const instance = (() => instance.get()) as ConfigurationListInstance; + + instance.get = function get(): ConfigurationContext { + return new ConfigurationContextImpl(version, chatServiceSid); + } + + instance._version = version; + instance._solution = { chatServiceSid, }; + instance._uri = ``; + + Object.defineProperty(instance, "notifications", { + get: function notifications() { + if (!instance._notifications) { + instance._notifications = NotificationListInstance(instance._version, instance._solution.chatServiceSid); + } + return instance._notifications; + } + }); + + Object.defineProperty(instance, "webhooks", { + get: function webhooks() { + if (!instance._webhooks) { + instance._webhooks = WebhookListInstance(instance._version, instance._solution.chatServiceSid); + } + return instance._webhooks; + } + }); + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/conversations/v1/service/configuration/notification.ts b/rest/conversations/v1/service/configuration/notification.ts new file mode 100644 index 000000000..d5d45a618 --- /dev/null +++ b/rest/conversations/v1/service/configuration/notification.ts @@ -0,0 +1,514 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a NotificationInstance + */ +export interface NotificationContextUpdateOptions { + /** Weather the notification logging is enabled. */ + "logEnabled"?: boolean; + /** Whether to send a notification when a new message is added to a conversation. The default is `false`. */ + "newMessage.enabled"?: boolean; + /** The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. */ + "newMessage.template"?: string; + /** The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. */ + "newMessage.sound"?: string; + /** Whether the new message badge is enabled. The default is `false`. */ + "newMessage.badgeCountEnabled"?: boolean; + /** Whether to send a notification when a participant is added to a conversation. The default is `false`. */ + "addedToConversation.enabled"?: boolean; + /** The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. */ + "addedToConversation.template"?: string; + /** The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. */ + "addedToConversation.sound"?: string; + /** Whether to send a notification to a user when they are removed from a conversation. The default is `false`. */ + "removedFromConversation.enabled"?: boolean; + /** The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. */ + "removedFromConversation.template"?: string; + /** The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. */ + "removedFromConversation.sound"?: string; + /** Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. */ + "newMessage.withMedia.enabled"?: boolean; + /** The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. */ + "newMessage.withMedia.template"?: string; +} + +export interface NotificationContext { + + /** + * Fetch a NotificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + fetch(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise + + /** + * Fetch a NotificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a NotificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + update(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise; + /** + * Update a NotificationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + update(params: NotificationContextUpdateOptions, callback?: (error: Error | null, item?: NotificationInstance) => any): Promise; + + /** + * Update a NotificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a NotificationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + updateWithHttpInfo(params: NotificationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface NotificationContextSolution { + "chatServiceSid": string; +} + +export class NotificationContextImpl implements NotificationContext { + protected _solution: NotificationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, chatServiceSid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + this._solution = { chatServiceSid, }; + this._uri = `/Services/${chatServiceSid}/Configuration/Notifications`; + } + + fetch(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new NotificationInstance(operationVersion, payload, instance._solution.chatServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new NotificationInstance(operationVersion, response.body, instance._solution.chatServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: NotificationContextUpdateOptions | ((error: Error | null, item?: NotificationInstance) => any),callback?: (error: Error | null, item?: NotificationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["logEnabled"] !== undefined) + data["LogEnabled"] = serialize.bool(params["logEnabled"]); + if (params["newMessage.enabled"] !== undefined) + data["NewMessage.Enabled"] = serialize.bool(params["newMessage.enabled"]); + if (params["newMessage.template"] !== undefined) + data["NewMessage.Template"] = params["newMessage.template"]; + if (params["newMessage.sound"] !== undefined) + data["NewMessage.Sound"] = params["newMessage.sound"]; + if (params["newMessage.badgeCountEnabled"] !== undefined) + data["NewMessage.BadgeCountEnabled"] = serialize.bool(params["newMessage.badgeCountEnabled"]); + if (params["addedToConversation.enabled"] !== undefined) + data["AddedToConversation.Enabled"] = serialize.bool(params["addedToConversation.enabled"]); + if (params["addedToConversation.template"] !== undefined) + data["AddedToConversation.Template"] = params["addedToConversation.template"]; + if (params["addedToConversation.sound"] !== undefined) + data["AddedToConversation.Sound"] = params["addedToConversation.sound"]; + if (params["removedFromConversation.enabled"] !== undefined) + data["RemovedFromConversation.Enabled"] = serialize.bool(params["removedFromConversation.enabled"]); + if (params["removedFromConversation.template"] !== undefined) + data["RemovedFromConversation.Template"] = params["removedFromConversation.template"]; + if (params["removedFromConversation.sound"] !== undefined) + data["RemovedFromConversation.Sound"] = params["removedFromConversation.sound"]; + if (params["newMessage.withMedia.enabled"] !== undefined) + data["NewMessage.WithMedia.Enabled"] = serialize.bool(params["newMessage.withMedia.enabled"]); + if (params["newMessage.withMedia.template"] !== undefined) + data["NewMessage.WithMedia.Template"] = params["newMessage.withMedia.template"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NotificationInstance(operationVersion, payload, instance._solution.chatServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: NotificationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["logEnabled"] !== undefined) + data["LogEnabled"] = serialize.bool(params["logEnabled"]); + if (params["newMessage.enabled"] !== undefined) + data["NewMessage.Enabled"] = serialize.bool(params["newMessage.enabled"]); + if (params["newMessage.template"] !== undefined) + data["NewMessage.Template"] = params["newMessage.template"]; + if (params["newMessage.sound"] !== undefined) + data["NewMessage.Sound"] = params["newMessage.sound"]; + if (params["newMessage.badgeCountEnabled"] !== undefined) + data["NewMessage.BadgeCountEnabled"] = serialize.bool(params["newMessage.badgeCountEnabled"]); + if (params["addedToConversation.enabled"] !== undefined) + data["AddedToConversation.Enabled"] = serialize.bool(params["addedToConversation.enabled"]); + if (params["addedToConversation.template"] !== undefined) + data["AddedToConversation.Template"] = params["addedToConversation.template"]; + if (params["addedToConversation.sound"] !== undefined) + data["AddedToConversation.Sound"] = params["addedToConversation.sound"]; + if (params["removedFromConversation.enabled"] !== undefined) + data["RemovedFromConversation.Enabled"] = serialize.bool(params["removedFromConversation.enabled"]); + if (params["removedFromConversation.template"] !== undefined) + data["RemovedFromConversation.Template"] = params["removedFromConversation.template"]; + if (params["removedFromConversation.sound"] !== undefined) + data["RemovedFromConversation.Sound"] = params["removedFromConversation.sound"]; + if (params["newMessage.withMedia.enabled"] !== undefined) + data["NewMessage.WithMedia.Enabled"] = serialize.bool(params["newMessage.withMedia.enabled"]); + if (params["newMessage.withMedia.template"] !== undefined) + data["NewMessage.WithMedia.Template"] = params["newMessage.withMedia.template"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new NotificationInstance(operationVersion, response.body, instance._solution.chatServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface NotificationPayload extends NotificationResource {} + +interface NotificationResource { + account_sid: string; + chat_service_sid: string; + new_message: any; + added_to_conversation: any; + removed_from_conversation: any; + log_enabled: boolean; + url: string; +} + +export class NotificationInstance { + protected _solution: NotificationContextSolution; + protected _context?: NotificationContext; + + constructor(protected _version: V1, payload: NotificationResource, chatServiceSid: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.newMessage = (payload.new_message); + this.addedToConversation = (payload.added_to_conversation); + this.removedFromConversation = (payload.removed_from_conversation); + this.logEnabled = (payload.log_enabled); + this.url = (payload.url); + + this._solution = { chatServiceSid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this configuration. + */ + accountSid: string; + /** + * The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Configuration applies to. + */ + chatServiceSid: string; + /** + * The Push Notification configuration for New Messages. + */ + newMessage: any; + /** + * The Push Notification configuration for being added to a Conversation. + */ + addedToConversation: any; + /** + * The Push Notification configuration for being removed from a Conversation. + */ + removedFromConversation: any; + /** + * Weather the notification logging is enabled. + */ + logEnabled: boolean; + /** + * An absolute API resource URL for this configuration. + */ + url: string; + + private get _proxy(): NotificationContext { + this._context = this._context || new NotificationContextImpl(this._version, this._solution.chatServiceSid); + return this._context; + } + + /** + * Fetch a NotificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + fetch(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a NotificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a NotificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + update(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise; + /** + * Update a NotificationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + update(params: NotificationContextUpdateOptions, callback?: (error: Error | null, item?: NotificationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: NotificationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a NotificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a NotificationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + updateWithHttpInfo(params: NotificationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + newMessage: this.newMessage, + addedToConversation: this.addedToConversation, + removedFromConversation: this.removedFromConversation, + logEnabled: this.logEnabled, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface NotificationSolution { + chatServiceSid: string; +} + +export interface NotificationListInstance { + _version: V1; + _solution: NotificationSolution; + _uri: string; + + (): NotificationContext; + get(): NotificationContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NotificationListInstance(version: V1, chatServiceSid: string): NotificationListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + const instance = (() => instance.get()) as NotificationListInstance; + + instance.get = function get(): NotificationContext { + return new NotificationContextImpl(version, chatServiceSid); + } + + instance._version = version; + instance._solution = { chatServiceSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/conversations/v1/service/configuration/webhook.ts b/rest/conversations/v1/service/configuration/webhook.ts new file mode 100644 index 000000000..f52b6457e --- /dev/null +++ b/rest/conversations/v1/service/configuration/webhook.ts @@ -0,0 +1,462 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + */ +export type WebhookMethod = 'GET'|'POST'; + + + +/** + * Options to pass to update a WebhookInstance + */ +export interface WebhookContextUpdateOptions { + /** The absolute url the pre-event webhook request should be sent to. */ + "preWebhookUrl"?: string; + /** The absolute url the post-event webhook request should be sent to. */ + "postWebhookUrl"?: string; + /** The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. */ + "filters"?: Array; + /** The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. */ + "method"?: string; +} + +export interface WebhookContext { + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WebhookContextSolution { + "chatServiceSid": string; +} + +export class WebhookContextImpl implements WebhookContext { + protected _solution: WebhookContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, chatServiceSid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + this._solution = { chatServiceSid, }; + this._uri = `/Services/${chatServiceSid}/Configuration/Webhooks`; + } + + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.chatServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.chatServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: WebhookInstance) => any),callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["filters"] !== undefined) + data["Filters"] = serialize.map(params["filters"], (e: string) => (e)); + if (params["method"] !== undefined) + data["Method"] = params["method"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.chatServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["filters"] !== undefined) + data["Filters"] = serialize.map(params["filters"], (e: string) => (e)); + if (params["method"] !== undefined) + data["Method"] = params["method"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.chatServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WebhookPayload extends WebhookResource {} + +interface WebhookResource { + account_sid: string; + chat_service_sid: string; + pre_webhook_url: string; + post_webhook_url: string; + filters: Array; + method: WebhookMethod; + url: string; +} + +export class WebhookInstance { + protected _solution: WebhookContextSolution; + protected _context?: WebhookContext; + + constructor(protected _version: V1, payload: WebhookResource, chatServiceSid: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.preWebhookUrl = (payload.pre_webhook_url); + this.postWebhookUrl = (payload.post_webhook_url); + this.filters = (payload.filters); + this.method = payload.method; + this.url = (payload.url); + + this._solution = { chatServiceSid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this service. + */ + accountSid: string; + /** + * The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + */ + chatServiceSid: string; + /** + * The absolute url the pre-event webhook request should be sent to. + */ + preWebhookUrl: string; + /** + * The absolute url the post-event webhook request should be sent to. + */ + postWebhookUrl: string; + /** + * The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + */ + filters: Array; + method: WebhookMethod; + /** + * An absolute API resource URL for this webhook. + */ + url: string; + + private get _proxy(): WebhookContext { + this._context = this._context || new WebhookContextImpl(this._version, this._solution.chatServiceSid); + return this._context; + } + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + preWebhookUrl: this.preWebhookUrl, + postWebhookUrl: this.postWebhookUrl, + filters: this.filters, + method: this.method, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WebhookSolution { + chatServiceSid: string; +} + +export interface WebhookListInstance { + _version: V1; + _solution: WebhookSolution; + _uri: string; + + (): WebhookContext; + get(): WebhookContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WebhookListInstance(version: V1, chatServiceSid: string): WebhookListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WebhookListInstance; + + instance.get = function get(): WebhookContext { + return new WebhookContextImpl(version, chatServiceSid); + } + + instance._version = version; + instance._solution = { chatServiceSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/conversations/v1/service/conversation.ts b/rest/conversations/v1/service/conversation.ts new file mode 100644 index 000000000..eb5160c12 --- /dev/null +++ b/rest/conversations/v1/service/conversation.ts @@ -0,0 +1,1249 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { MessageListInstance } from "./conversation/message"; +import { ParticipantListInstance } from "./conversation/participant"; +import { WebhookListInstance } from "./conversation/webhook"; + + +/** + * Current state of this conversation. Can be either `initializing`, `active`, `inactive` or `closed` and defaults to `active` + */ +export type ConversationState = 'inactive'|'active'|'closed'|'initializing'; + +export type ConversationWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a ConversationInstance + */ +export interface ConversationContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ConversationWebhookEnabledType; +} + + +/** + * Options to pass to update a ConversationInstance + */ +export interface ConversationContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ConversationWebhookEnabledType; + /** The human-readable name of this conversation, limited to 256 characters. Optional. */ + "friendlyName"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. */ + "dateUpdated"?: Date; + /** An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. */ + "messagingServiceSid"?: string; + /** */ + "state"?: ConversationState; + /** ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. */ + "timers.inactive"?: string; + /** ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. */ + "timers.closed"?: string; + /** An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\\\'s `sid` in the URL. */ + "uniqueName"?: string; + /** The default email address that will be used when sending outbound emails in this conversation. */ + "bindings.email.address"?: string; + /** The default name that will be used when sending outbound emails in this conversation. */ + "bindings.email.name"?: string; +} + +/** + * Options to pass to create a ConversationInstance + */ +export interface ConversationListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ConversationWebhookEnabledType; + /** The human-readable name of this conversation, limited to 256 characters. Optional. */ + "friendlyName"?: string; + /** An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\\\'s `sid` in the URL. */ + "uniqueName"?: string; + /** An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. */ + "messagingServiceSid"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. */ + "dateUpdated"?: Date; + /** */ + "state"?: ConversationState; + /** ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. */ + "timers.inactive"?: string; + /** ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. */ + "timers.closed"?: string; + /** The default email address that will be used when sending outbound emails in this conversation. */ + "bindings.email.address"?: string; + /** The default name that will be used when sending outbound emails in this conversation. */ + "bindings.email.name"?: string; +} + +/** + * Options to pass to each + */ +export interface ConversationListInstanceEachOptions { + /** Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "startDate"?: string; + /** Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "endDate"?: string; + /** State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` */ + "state"?: ConversationState; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConversationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConversationListInstanceOptions { + /** Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "startDate"?: string; + /** Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "endDate"?: string; + /** State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` */ + "state"?: ConversationState; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConversationListInstancePageOptions { + /** Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "startDate"?: string; + /** Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. */ + "endDate"?: string; + /** State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` */ + "state"?: ConversationState; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ConversationContext { + messages: MessageListInstance; + participants: ParticipantListInstance; + webhooks: WebhookListInstance; + + /** + * Remove a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + remove(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + removeWithHttpInfo(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + + /** + * Fetch a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Update a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(params: ConversationContextUpdateOptions, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + /** + * Update a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConversationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConversationContextSolution { + "chatServiceSid": string; + "sid": string; +} + +export class ConversationContextImpl implements ConversationContext { + protected _solution: ConversationContextSolution; + protected _uri: string; + + protected _messages?: MessageListInstance; + protected _participants?: ParticipantListInstance; + protected _webhooks?: WebhookListInstance; + + constructor(protected _version: V1, chatServiceSid: string, sid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { chatServiceSid, sid, }; + this._uri = `/Services/${chatServiceSid}/Conversations/${sid}`; + } + + get messages(): MessageListInstance { + this._messages = this._messages || MessageListInstance(this._version, this._solution.chatServiceSid, this._solution.sid); + return this._messages; + } + + get participants(): ParticipantListInstance { + this._participants = this._participants || ParticipantListInstance(this._version, this._solution.chatServiceSid, this._solution.sid); + return this._participants; + } + + get webhooks(): WebhookListInstance { + this._webhooks = this._webhooks || WebhookListInstance(this._version, this._solution.chatServiceSid, this._solution.sid); + return this._webhooks; + } + + remove(params?: ConversationContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: ConversationContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ConversationContextUpdateOptions | ((error: Error | null, item?: ConversationInstance) => any),callback?: (error: Error | null, item?: ConversationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ConversationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConversationPayload extends TwilioResponsePayload { + conversations: ConversationResource[]; +} + +interface ConversationResource { + account_sid: string; + chat_service_sid: string; + messaging_service_sid: string; + sid: string; + friendly_name: string; + unique_name: string; + attributes: string; + state: ConversationState; + date_created: Date; + date_updated: Date; + timers: any; + url: string; + links: Record; + bindings: any; +} + +export class ConversationInstance { + protected _solution: ConversationContextSolution; + protected _context?: ConversationContext; + + constructor(protected _version: V1, payload: ConversationResource, chatServiceSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.messagingServiceSid = (payload.messaging_service_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.attributes = (payload.attributes); + this.state = payload.state; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.timers = (payload.timers); + this.url = (payload.url); + this.links = (payload.links); + this.bindings = (payload.bindings); + + this._solution = { chatServiceSid, sid: sid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + /** + * The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + */ + chatServiceSid: string; + /** + * The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + */ + messagingServiceSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The human-readable name of this conversation, limited to 256 characters. Optional. + */ + friendlyName: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\'s `sid` in the URL. + */ + uniqueName: string; + /** + * An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + attributes: string; + state: ConversationState; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + /** + * Timer date values representing state update for this conversation. + */ + timers: any; + /** + * An absolute API resource URL for this conversation. + */ + url: string; + /** + * Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + */ + links: Record; + bindings: any; + + private get _proxy(): ConversationContext { + this._context = this._context || new ConversationContextImpl(this._version, this._solution.chatServiceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + remove(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + removeWithHttpInfo(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Update a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(params: ConversationContextUpdateOptions, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConversationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the messages. + */ + messages(): MessageListInstance { + return this._proxy.messages; + } + + /** + * Access the participants. + */ + participants(): ParticipantListInstance { + return this._proxy.participants; + } + + /** + * Access the webhooks. + */ + webhooks(): WebhookListInstance { + return this._proxy.webhooks; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + messagingServiceSid: this.messagingServiceSid, + sid: this.sid, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + attributes: this.attributes, + state: this.state, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + timers: this.timers, + url: this.url, + links: this.links, + bindings: this.bindings, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConversationSolution { + chatServiceSid: string; +} + +export interface ConversationListInstance { + _version: V1; + _solution: ConversationSolution; + _uri: string; + + (sid: string, ): ConversationContext; + get(sid: string, ): ConversationContext; + + + + + + + + + /** + * Create a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + create(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Create a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + create(params: ConversationListInstanceCreateOptions, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + /** + * Create a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + createWithHttpInfo(params: ConversationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ConversationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + each(params: ConversationListInstanceEachOptions, callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConversationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConversationListInstanceEachOptions, callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConversationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConversationPage) => any): Promise; + /** + * Retrieve a single target page of ConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConversationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConversationInstance[]) => any): Promise; + list(params: ConversationListInstanceOptions, callback?: (error: Error | null, items: ConversationInstance[]) => any): Promise; + /** + * Lists ConversationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConversationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConversationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConversationPage) => any): Promise; + page(params: ConversationListInstancePageOptions, callback?: (error: Error | null, items: ConversationPage) => any): Promise; + /** + * Retrieve a single page of ConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConversationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConversationListInstance(version: V1, chatServiceSid: string): ConversationListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ConversationListInstance; + + instance.get = function get(sid, ): ConversationContext { + return new ConversationContextImpl(version, chatServiceSid, sid); + } + + instance._version = version; + instance._solution = { chatServiceSid, }; + instance._uri = `/Services/${chatServiceSid}/Conversations`; + + instance.create = function create(params?: ConversationListInstanceCreateOptions | ((error: Error | null, items: ConversationInstance) => any), callback?: (error: Error | null, items: ConversationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload, instance._solution.chatServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ConversationListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body, instance._solution.chatServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ConversationListInstancePageOptions | ((error: Error | null, items: ConversationPage) => any), callback?: (error: Error | null, items: ConversationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["startDate"] !== undefined) + data["StartDate"] = params["startDate"]; + if (params["endDate"] !== undefined) + data["EndDate"] = params["endDate"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConversationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConversationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConversationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConversationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["startDate"] !== undefined) + data["StartDate"] = params["startDate"]; + if (params["endDate"] !== undefined) + data["EndDate"] = params["endDate"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConversationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConversationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConversationPage extends Page { +/** +* Initialize the ConversationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ConversationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ConversationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConversationResource): ConversationInstance { + + return new ConversationInstance( + this._version, + payload, + this._solution.chatServiceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service/conversation/message.ts b/rest/conversations/v1/service/conversation/message.ts new file mode 100644 index 000000000..2013f3080 --- /dev/null +++ b/rest/conversations/v1/service/conversation/message.ts @@ -0,0 +1,1185 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { DeliveryReceiptListInstance } from "./message/deliveryReceipt"; + + +export type MessageOrderType = 'asc'|'desc'; + +export type MessageWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a MessageInstance + */ +export interface MessageContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; +} + + +/** + * Options to pass to update a MessageInstance + */ +export interface MessageContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; + /** The channel specific identifier of the message\\\'s author. Defaults to `system`. */ + "author"?: string; + /** The content of the message, can be up to 1,600 characters long. */ + "body"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. `null` if the message has not been edited. */ + "dateUpdated"?: Date; + /** A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** The subject of the message, can be up to 256 characters long. */ + "subject"?: string; +} + +/** + * Options to pass to create a MessageInstance + */ +export interface MessageListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; + /** The channel specific identifier of the message\\\'s author. Defaults to `system`. */ + "author"?: string; + /** The content of the message, can be up to 1,600 characters long. */ + "body"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. `null` if the message has not been edited. */ + "dateUpdated"?: Date; + /** A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** The Media SID to be attached to the new Message. */ + "mediaSid"?: string; + /** The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. */ + "contentSid"?: string; + /** A structurally valid JSON string that contains values to resolve Rich Content template variables. */ + "contentVariables"?: string; + /** The subject of the message, can be up to 256 characters long. */ + "subject"?: string; +} + +/** + * Options to pass to each + */ +export interface MessageListInstanceEachOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MessageInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MessageListInstanceOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MessageListInstancePageOptions { + /** The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MessageContext { + deliveryReceipts: DeliveryReceiptListInstance; + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + remove(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + removeWithHttpInfo(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MessageContextSolution { + "chatServiceSid": string; + "conversationSid": string; + "sid": string; +} + +export class MessageContextImpl implements MessageContext { + protected _solution: MessageContextSolution; + protected _uri: string; + + protected _deliveryReceipts?: DeliveryReceiptListInstance; + + constructor(protected _version: V1, chatServiceSid: string, conversationSid: string, sid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { chatServiceSid, conversationSid, sid, }; + this._uri = `/Services/${chatServiceSid}/Conversations/${conversationSid}/Messages/${sid}`; + } + + get deliveryReceipts(): DeliveryReceiptListInstance { + this._deliveryReceipts = this._deliveryReceipts || DeliveryReceiptListInstance(this._version, this._solution.chatServiceSid, this._solution.conversationSid, this._solution.sid); + return this._deliveryReceipts; + } + + remove(params?: MessageContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: MessageContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MessageContextUpdateOptions | ((error: Error | null, item?: MessageInstance) => any),callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["author"] !== undefined) + data["Author"] = params["author"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["subject"] !== undefined) + data["Subject"] = params["subject"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MessageContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["author"] !== undefined) + data["Author"] = params["author"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["subject"] !== undefined) + data["Subject"] = params["subject"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MessagePayload extends TwilioResponsePayload { + messages: MessageResource[]; +} + +interface MessageResource { + account_sid: string; + chat_service_sid: string; + conversation_sid: string; + sid: string; + index: number; + author: string; + body: string; + media: Array; + attributes: string; + participant_sid: string; + date_created: Date; + date_updated: Date; + delivery: any; + url: string; + links: Record; + content_sid: string; +} + +export class MessageInstance { + protected _solution: MessageContextSolution; + protected _context?: MessageContext; + + constructor(protected _version: V1, payload: MessageResource, chatServiceSid: string, conversationSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.conversationSid = (payload.conversation_sid); + this.sid = (payload.sid); + this.index = deserialize.integer(payload.index); + this.author = (payload.author); + this.body = (payload.body); + this.media = (payload.media); + this.attributes = (payload.attributes); + this.participantSid = (payload.participant_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.delivery = (payload.delivery); + this.url = (payload.url); + this.links = (payload.links); + this.contentSid = (payload.content_sid); + + this._solution = { chatServiceSid, conversationSid, sid: sid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this message. + */ + accountSid: string; + /** + * The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + */ + chatServiceSid: string; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + */ + conversationSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The index of the message within the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource). + */ + index: number; + /** + * The channel specific identifier of the message\'s author. Defaults to `system`. + */ + author: string; + /** + * The content of the message, can be up to 1,600 characters long. + */ + body: string; + /** + * An array of objects that describe the Message\'s media, if the message contains media. Each object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object\'s file size in bytes. If the Message has no media, this value is `null`. + */ + media: Array; + /** + * A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + attributes: string; + /** + * The unique ID of messages\'s author participant. Null in case of `system` sent message. + */ + participantSid: string; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. `null` if the message has not been edited. + */ + dateUpdated: Date; + /** + * An object that contains the summary of delivery statuses for the message to non-chat participants. + */ + delivery: any; + /** + * An absolute API resource URL for this message. + */ + url: string; + /** + * Contains an absolute API resource URL to access the delivery & read receipts of this message. + */ + links: Record; + /** + * The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template. + */ + contentSid: string; + + private get _proxy(): MessageContext { + this._context = this._context || new MessageContextImpl(this._version, this._solution.chatServiceSid, this._solution.conversationSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + remove(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + removeWithHttpInfo(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MessageInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the deliveryReceipts. + */ + deliveryReceipts(): DeliveryReceiptListInstance { + return this._proxy.deliveryReceipts; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + conversationSid: this.conversationSid, + sid: this.sid, + index: this.index, + author: this.author, + body: this.body, + media: this.media, + attributes: this.attributes, + participantSid: this.participantSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + delivery: this.delivery, + url: this.url, + links: this.links, + contentSid: this.contentSid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MessageSolution { + chatServiceSid: string; + conversationSid: string; +} + +export interface MessageListInstance { + _version: V1; + _solution: MessageSolution; + _uri: string; + + (sid: string, ): MessageContext; + get(sid: string, ): MessageContext; + + + + + + + + + /** + * Create a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Create a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Create a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MessageInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + each(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MessageInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single target page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MessageInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + list(params: MessageListInstanceOptions, callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + /** + * Lists MessageInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MessageListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MessagePage) => any): Promise; + page(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessageListInstance(version: V1, chatServiceSid: string, conversationSid: string): MessageListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MessageListInstance; + + instance.get = function get(sid, ): MessageContext { + return new MessageContextImpl(version, chatServiceSid, conversationSid, sid); + } + + instance._version = version; + instance._solution = { chatServiceSid, conversationSid, }; + instance._uri = `/Services/${chatServiceSid}/Conversations/${conversationSid}/Messages`; + + instance.create = function create(params?: MessageListInstanceCreateOptions | ((error: Error | null, items: MessageInstance) => any), callback?: (error: Error | null, items: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["author"] !== undefined) + data["Author"] = params["author"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["mediaSid"] !== undefined) + data["MediaSid"] = params["mediaSid"]; + if (params["contentSid"] !== undefined) + data["ContentSid"] = params["contentSid"]; + if (params["contentVariables"] !== undefined) + data["ContentVariables"] = params["contentVariables"]; + if (params["subject"] !== undefined) + data["Subject"] = params["subject"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.conversationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: MessageListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["author"] !== undefined) + data["Author"] = params["author"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["mediaSid"] !== undefined) + data["MediaSid"] = params["mediaSid"]; + if (params["contentSid"] !== undefined) + data["ContentSid"] = params["contentSid"]; + if (params["contentVariables"] !== undefined) + data["ContentVariables"] = params["contentVariables"]; + if (params["subject"] !== undefined) + data["Subject"] = params["subject"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.conversationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MessageListInstancePageOptions | ((error: Error | null, items: MessagePage) => any), callback?: (error: Error | null, items: MessagePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MessagePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MessagePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MessageListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MessagePage extends Page { +/** +* Initialize the MessagePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: MessageSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MessageInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MessageResource): MessageInstance { + + return new MessageInstance( + this._version, + payload, + this._solution.chatServiceSid, + this._solution.conversationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service/conversation/message/deliveryReceipt.ts b/rest/conversations/v1/service/conversation/message/deliveryReceipt.ts new file mode 100644 index 000000000..d9ce65501 --- /dev/null +++ b/rest/conversations/v1/service/conversation/message/deliveryReceipt.ts @@ -0,0 +1,628 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../../base/Page"; +import Response from "../../../../../../http/response"; +import V1 from "../../../../V1"; +const deserialize = require("../../../../../../base/deserialize"); +const serialize = require("../../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../../base/utility"; +import { ApiResponse } from "../../../../../../base/ApiResponse"; + + +/** + * The message delivery status, can be `read`, `failed`, `delivered`, `undelivered`, `sent` or null. + */ +export type DeliveryReceiptDeliveryStatus = 'read'|'failed'|'delivered'|'undelivered'|'sent'; + + + +/** + * Options to pass to each + */ +export interface DeliveryReceiptListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DeliveryReceiptInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DeliveryReceiptListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DeliveryReceiptListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface DeliveryReceiptContext { + + /** + * Fetch a DeliveryReceiptInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeliveryReceiptInstance + */ + fetch(callback?: (error: Error | null, item?: DeliveryReceiptInstance) => any): Promise + + /** + * Fetch a DeliveryReceiptInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeliveryReceiptInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DeliveryReceiptContextSolution { + "chatServiceSid": string; + "conversationSid": string; + "messageSid": string; + "sid": string; +} + +export class DeliveryReceiptContextImpl implements DeliveryReceiptContext { + protected _solution: DeliveryReceiptContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, chatServiceSid: string, conversationSid: string, messageSid: string, sid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + if (!isValidPathParam(messageSid)) { + throw new Error('Parameter \'messageSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { chatServiceSid, conversationSid, messageSid, sid, }; + this._uri = `/Services/${chatServiceSid}/Conversations/${conversationSid}/Messages/${messageSid}/Receipts/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: DeliveryReceiptInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DeliveryReceiptInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.messageSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new DeliveryReceiptInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.messageSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DeliveryReceiptPayload extends TwilioResponsePayload { + delivery_receipts: DeliveryReceiptResource[]; +} + +interface DeliveryReceiptResource { + account_sid: string; + chat_service_sid: string; + conversation_sid: string; + message_sid: string; + sid: string; + channel_message_sid: string; + participant_sid: string; + status: DeliveryReceiptDeliveryStatus; + error_code: number; + date_created: Date; + date_updated: Date; + url: string; +} + +export class DeliveryReceiptInstance { + protected _solution: DeliveryReceiptContextSolution; + protected _context?: DeliveryReceiptContext; + + constructor(protected _version: V1, payload: DeliveryReceiptResource, chatServiceSid: string, conversationSid: string, messageSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.conversationSid = (payload.conversation_sid); + this.messageSid = (payload.message_sid); + this.sid = (payload.sid); + this.channelMessageSid = (payload.channel_message_sid); + this.participantSid = (payload.participant_sid); + this.status = payload.status; + this.errorCode = deserialize.integer(payload.error_code); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { chatServiceSid, conversationSid, messageSid, sid: sid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + */ + accountSid: string; + /** + * The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Message resource is associated with. + */ + chatServiceSid: string; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + */ + conversationSid: string; + /** + * The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to + */ + messageSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * A messaging channel-specific identifier for the message delivered to participant e.g. `SMxx` for SMS, `WAxx` for Whatsapp etc. + */ + channelMessageSid: string; + /** + * The unique ID of the participant the delivery receipt belongs to. + */ + participantSid: string; + status: DeliveryReceiptDeliveryStatus; + /** + * The message [delivery error code](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors) for a `failed` status, + */ + errorCode: number; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. `null` if the delivery receipt has not been updated. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this delivery receipt. + */ + url: string; + + private get _proxy(): DeliveryReceiptContext { + this._context = this._context || new DeliveryReceiptContextImpl(this._version, this._solution.chatServiceSid, this._solution.conversationSid, this._solution.messageSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a DeliveryReceiptInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeliveryReceiptInstance + */ + fetch(callback?: (error: Error | null, item?: DeliveryReceiptInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DeliveryReceiptInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeliveryReceiptInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + conversationSid: this.conversationSid, + messageSid: this.messageSid, + sid: this.sid, + channelMessageSid: this.channelMessageSid, + participantSid: this.participantSid, + status: this.status, + errorCode: this.errorCode, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DeliveryReceiptSolution { + chatServiceSid: string; + conversationSid: string; + messageSid: string; +} + +export interface DeliveryReceiptListInstance { + _version: V1; + _solution: DeliveryReceiptSolution; + _uri: string; + + (sid: string, ): DeliveryReceiptContext; + get(sid: string, ): DeliveryReceiptContext; + + + + + + /** + * Streams DeliveryReceiptInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DeliveryReceiptInstance, done: (err?: Error) => void) => void): void; + each(params: DeliveryReceiptListInstanceEachOptions, callback?: (item: DeliveryReceiptInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DeliveryReceiptInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DeliveryReceiptInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DeliveryReceiptListInstanceEachOptions, callback?: (item: DeliveryReceiptInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DeliveryReceiptInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DeliveryReceiptPage) => any): Promise; + /** + * Retrieve a single target page of DeliveryReceiptInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists DeliveryReceiptInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DeliveryReceiptInstance[]) => any): Promise; + list(params: DeliveryReceiptListInstanceOptions, callback?: (error: Error | null, items: DeliveryReceiptInstance[]) => any): Promise; + /** + * Lists DeliveryReceiptInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: DeliveryReceiptListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of DeliveryReceiptInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DeliveryReceiptPage) => any): Promise; + page(params: DeliveryReceiptListInstancePageOptions, callback?: (error: Error | null, items: DeliveryReceiptPage) => any): Promise; + /** + * Retrieve a single page of DeliveryReceiptInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeliveryReceiptListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: DeliveryReceiptListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DeliveryReceiptListInstance(version: V1, chatServiceSid: string, conversationSid: string, messageSid: string): DeliveryReceiptListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + if (!isValidPathParam(messageSid)) { + throw new Error('Parameter \'messageSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as DeliveryReceiptListInstance; + + instance.get = function get(sid, ): DeliveryReceiptContext { + return new DeliveryReceiptContextImpl(version, chatServiceSid, conversationSid, messageSid, sid); + } + + instance._version = version; + instance._solution = { chatServiceSid, conversationSid, messageSid, }; + instance._uri = `/Services/${chatServiceSid}/Conversations/${conversationSid}/Messages/${messageSid}/Receipts`; + + instance.page = function page(params?: DeliveryReceiptListInstancePageOptions | ((error: Error | null, items: DeliveryReceiptPage) => any), callback?: (error: Error | null, items: DeliveryReceiptPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DeliveryReceiptPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DeliveryReceiptPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DeliveryReceiptPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DeliveryReceiptListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DeliveryReceiptPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DeliveryReceiptPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class DeliveryReceiptPage extends Page { +/** +* Initialize the DeliveryReceiptPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: DeliveryReceiptSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DeliveryReceiptInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DeliveryReceiptResource): DeliveryReceiptInstance { + + return new DeliveryReceiptInstance( + this._version, + payload, + this._solution.chatServiceSid, + this._solution.conversationSid, + this._solution.messageSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service/conversation/participant.ts b/rest/conversations/v1/service/conversation/participant.ts new file mode 100644 index 000000000..ecef5cd3b --- /dev/null +++ b/rest/conversations/v1/service/conversation/participant.ts @@ -0,0 +1,1149 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type ParticipantWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a ParticipantInstance + */ +export interface ParticipantContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ParticipantWebhookEnabledType; +} + + +/** + * Options to pass to update a ParticipantInstance + */ +export interface ParticipantContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ParticipantWebhookEnabledType; + /** The date on which this resource was created. */ + "dateCreated"?: Date; + /** The date on which this resource was last updated. */ + "dateUpdated"?: Date; + /** A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. */ + "identity"?: string; + /** An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. */ + "attributes"?: string; + /** The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. */ + "roleSid"?: string; + /** The address of the Twilio phone number that the participant is in contact with. \\\'null\\\' value will remove it. */ + "messagingBinding.proxyAddress"?: string; + /** The address of the Twilio phone number that is used in Group MMS. \\\'null\\\' value will remove it. */ + "messagingBinding.projectedAddress"?: string; + /** Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. */ + "lastReadMessageIndex"?: number; + /** Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. */ + "lastReadTimestamp"?: string; +} + +/** + * Options to pass to create a ParticipantInstance + */ +export interface ParticipantListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ParticipantWebhookEnabledType; + /** A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. */ + "identity"?: string; + /** The address of the participant\\\'s device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with `proxy_address`) is only null when the participant is interacting from an SDK endpoint (see the `identity` field). */ + "messagingBinding.address"?: string; + /** The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the `identity` field). */ + "messagingBinding.proxyAddress"?: string; + /** The date on which this resource was created. */ + "dateCreated"?: Date; + /** The date on which this resource was last updated. */ + "dateUpdated"?: Date; + /** An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. */ + "attributes"?: string; + /** The address of the Twilio phone number that is used in Group MMS. */ + "messagingBinding.projectedAddress"?: string; + /** The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. */ + "roleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface ParticipantListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ParticipantListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ParticipantListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ParticipantContext { + + /** + * Remove a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + remove(params: ParticipantContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + removeWithHttpInfo(params: ParticipantContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Update a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + /** + * Update a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ParticipantContextSolution { + "chatServiceSid": string; + "conversationSid": string; + "sid": string; +} + +export class ParticipantContextImpl implements ParticipantContext { + protected _solution: ParticipantContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, chatServiceSid: string, conversationSid: string, sid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { chatServiceSid, conversationSid, sid, }; + this._uri = `/Services/${chatServiceSid}/Conversations/${conversationSid}/Participants/${sid}`; + } + + remove(params?: ParticipantContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: ParticipantContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ParticipantContextUpdateOptions | ((error: Error | null, item?: ParticipantInstance) => any),callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["messagingBinding.proxyAddress"] !== undefined) + data["MessagingBinding.ProxyAddress"] = params["messagingBinding.proxyAddress"]; + if (params["messagingBinding.projectedAddress"] !== undefined) + data["MessagingBinding.ProjectedAddress"] = params["messagingBinding.projectedAddress"]; + if (params["lastReadMessageIndex"] !== undefined) + data["LastReadMessageIndex"] = params["lastReadMessageIndex"]; + if (params["lastReadTimestamp"] !== undefined) + data["LastReadTimestamp"] = params["lastReadTimestamp"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ParticipantContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["messagingBinding.proxyAddress"] !== undefined) + data["MessagingBinding.ProxyAddress"] = params["messagingBinding.proxyAddress"]; + if (params["messagingBinding.projectedAddress"] !== undefined) + data["MessagingBinding.ProjectedAddress"] = params["messagingBinding.projectedAddress"]; + if (params["lastReadMessageIndex"] !== undefined) + data["LastReadMessageIndex"] = params["lastReadMessageIndex"]; + if (params["lastReadTimestamp"] !== undefined) + data["LastReadTimestamp"] = params["lastReadTimestamp"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ParticipantPayload extends TwilioResponsePayload { + participants: ParticipantResource[]; +} + +interface ParticipantResource { + account_sid: string; + chat_service_sid: string; + conversation_sid: string; + sid: string; + identity: string; + attributes: string; + messaging_binding: any; + role_sid: string; + date_created: Date; + date_updated: Date; + url: string; + last_read_message_index: number; + last_read_timestamp: string; +} + +export class ParticipantInstance { + protected _solution: ParticipantContextSolution; + protected _context?: ParticipantContext; + + constructor(protected _version: V1, payload: ParticipantResource, chatServiceSid: string, conversationSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.conversationSid = (payload.conversation_sid); + this.sid = (payload.sid); + this.identity = (payload.identity); + this.attributes = (payload.attributes); + this.messagingBinding = (payload.messaging_binding); + this.roleSid = (payload.role_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.lastReadMessageIndex = deserialize.integer(payload.last_read_message_index); + this.lastReadTimestamp = (payload.last_read_timestamp); + + this._solution = { chatServiceSid, conversationSid, sid: sid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + */ + accountSid: string; + /** + * The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + */ + chatServiceSid: string; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + */ + conversationSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + */ + identity: string; + /** + * An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + */ + attributes: string; + /** + * Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + */ + messagingBinding: any; + /** + * The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + */ + roleSid: string; + /** + * The date on which this resource was created. + */ + dateCreated: Date; + /** + * The date on which this resource was last updated. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this participant. + */ + url: string; + /** + * Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + */ + lastReadMessageIndex: number; + /** + * Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + */ + lastReadTimestamp: string; + + private get _proxy(): ParticipantContext { + this._context = this._context || new ParticipantContextImpl(this._version, this._solution.chatServiceSid, this._solution.conversationSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + remove(params: ParticipantContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + removeWithHttpInfo(params: ParticipantContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Update a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + conversationSid: this.conversationSid, + sid: this.sid, + identity: this.identity, + attributes: this.attributes, + messagingBinding: this.messagingBinding, + roleSid: this.roleSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + lastReadMessageIndex: this.lastReadMessageIndex, + lastReadTimestamp: this.lastReadTimestamp, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ParticipantSolution { + chatServiceSid: string; + conversationSid: string; +} + +export interface ParticipantListInstance { + _version: V1; + _solution: ParticipantSolution; + _uri: string; + + (sid: string, ): ParticipantContext; + get(sid: string, ): ParticipantContext; + + + + + + + + + /** + * Create a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + create(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Create a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + create(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + /** + * Create a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + createWithHttpInfo(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ParticipantInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + each(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ParticipantInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + /** + * Retrieve a single target page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ParticipantInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise; + list(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise; + /** + * Lists ParticipantInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + page(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + /** + * Retrieve a single page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ParticipantListInstance(version: V1, chatServiceSid: string, conversationSid: string): ParticipantListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ParticipantListInstance; + + instance.get = function get(sid, ): ParticipantContext { + return new ParticipantContextImpl(version, chatServiceSid, conversationSid, sid); + } + + instance._version = version; + instance._solution = { chatServiceSid, conversationSid, }; + instance._uri = `/Services/${chatServiceSid}/Conversations/${conversationSid}/Participants`; + + instance.create = function create(params?: ParticipantListInstanceCreateOptions | ((error: Error | null, items: ParticipantInstance) => any), callback?: (error: Error | null, items: ParticipantInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["messagingBinding.address"] !== undefined) + data["MessagingBinding.Address"] = params["messagingBinding.address"]; + if (params["messagingBinding.proxyAddress"] !== undefined) + data["MessagingBinding.ProxyAddress"] = params["messagingBinding.proxyAddress"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["messagingBinding.projectedAddress"] !== undefined) + data["MessagingBinding.ProjectedAddress"] = params["messagingBinding.projectedAddress"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.conversationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ParticipantListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["messagingBinding.address"] !== undefined) + data["MessagingBinding.Address"] = params["messagingBinding.address"]; + if (params["messagingBinding.proxyAddress"] !== undefined) + data["MessagingBinding.ProxyAddress"] = params["messagingBinding.proxyAddress"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["messagingBinding.projectedAddress"] !== undefined) + data["MessagingBinding.ProjectedAddress"] = params["messagingBinding.projectedAddress"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.conversationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ParticipantPage) => any), callback?: (error: Error | null, items: ParticipantPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ParticipantPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ParticipantPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ParticipantPage extends Page { +/** +* Initialize the ParticipantPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ParticipantSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ParticipantInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ParticipantResource): ParticipantInstance { + + return new ParticipantInstance( + this._version, + payload, + this._solution.chatServiceSid, + this._solution.conversationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service/conversation/webhook.ts b/rest/conversations/v1/service/conversation/webhook.ts new file mode 100644 index 000000000..d4e28b099 --- /dev/null +++ b/rest/conversations/v1/service/conversation/webhook.ts @@ -0,0 +1,999 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type WebhookMethod = 'get'|'post'; + +/** + * The target of this webhook: `webhook`, `studio`, `trigger` + */ +export type WebhookTarget = 'webhook'|'trigger'|'studio'; + + + + +/** + * Options to pass to update a WebhookInstance + */ +export interface WebhookContextUpdateOptions { + /** The absolute url the webhook request should be sent to. */ + "configuration.url"?: string; + /** */ + "configuration.method"?: WebhookMethod; + /** The list of events, firing webhook event for this Conversation. */ + "configuration.filters"?: Array; + /** The list of keywords, firing webhook event for this Conversation. */ + "configuration.triggers"?: Array; + /** The studio flow SID, where the webhook should be sent to. */ + "configuration.flowSid"?: string; +} + +/** + * Options to pass to create a WebhookInstance + */ +export interface WebhookListInstanceCreateOptions { + /** */ + "target": WebhookTarget; + /** The absolute url the webhook request should be sent to. */ + "configuration.url"?: string; + /** */ + "configuration.method"?: WebhookMethod; + /** The list of events, firing webhook event for this Conversation. */ + "configuration.filters"?: Array; + /** The list of keywords, firing webhook event for this Conversation. */ + "configuration.triggers"?: Array; + /** The studio flow SID, where the webhook should be sent to. */ + "configuration.flowSid"?: string; + /** The message index for which and it\\\'s successors the webhook will be replayed. Not set by default */ + "configuration.replayAfter"?: number; +} + +/** + * Options to pass to each + */ +export interface WebhookListInstanceEachOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: WebhookInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface WebhookListInstanceOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface WebhookListInstancePageOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface WebhookContext { + + /** + * Remove a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WebhookContextSolution { + "chatServiceSid": string; + "conversationSid": string; + "sid": string; +} + +export class WebhookContextImpl implements WebhookContext { + protected _solution: WebhookContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, chatServiceSid: string, conversationSid: string, sid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { chatServiceSid, conversationSid, sid, }; + this._uri = `/Services/${chatServiceSid}/Conversations/${conversationSid}/Webhooks/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: WebhookInstance) => any),callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.conversationSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WebhookPayload extends TwilioResponsePayload { + webhooks: WebhookResource[]; +} + +interface WebhookResource { + sid: string; + account_sid: string; + chat_service_sid: string; + conversation_sid: string; + target: string; + url: string; + configuration: any; + date_created: Date; + date_updated: Date; +} + +export class WebhookInstance { + protected _solution: WebhookContextSolution; + protected _context?: WebhookContext; + + constructor(protected _version: V1, payload: WebhookResource, chatServiceSid: string, conversationSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.conversationSid = (payload.conversation_sid); + this.target = (payload.target); + this.url = (payload.url); + this.configuration = (payload.configuration); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { chatServiceSid, conversationSid, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + /** + * The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + */ + chatServiceSid: string; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + */ + conversationSid: string; + /** + * The target of this webhook: `webhook`, `studio`, `trigger` + */ + target: string; + /** + * An absolute API resource URL for this webhook. + */ + url: string; + /** + * The configuration of this webhook. Is defined based on target. + */ + configuration: any; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + + private get _proxy(): WebhookContext { + this._context = this._context || new WebhookContextImpl(this._version, this._solution.chatServiceSid, this._solution.conversationSid, this._solution.sid); + return this._context; + } + + /** + * Remove a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + conversationSid: this.conversationSid, + target: this.target, + url: this.url, + configuration: this.configuration, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WebhookSolution { + chatServiceSid: string; + conversationSid: string; +} + +export interface WebhookListInstance { + _version: V1; + _solution: WebhookSolution; + _uri: string; + + (sid: string, ): WebhookContext; + get(sid: string, ): WebhookContext; + + + + + + + + + /** + * Create a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + create(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + /** + * Create a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + createWithHttpInfo(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams WebhookInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + each(params: WebhookListInstanceEachOptions, callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + /** + * Streams WebhookInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: WebhookListInstanceEachOptions, callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of WebhookInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: WebhookPage) => any): Promise; + /** + * Retrieve a single target page of WebhookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists WebhookInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: WebhookInstance[]) => any): Promise; + list(params: WebhookListInstanceOptions, callback?: (error: Error | null, items: WebhookInstance[]) => any): Promise; + /** + * Lists WebhookInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: WebhookListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of WebhookInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: WebhookPage) => any): Promise; + page(params: WebhookListInstancePageOptions, callback?: (error: Error | null, items: WebhookPage) => any): Promise; + /** + * Retrieve a single page of WebhookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: WebhookListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WebhookListInstance(version: V1, chatServiceSid: string, conversationSid: string): WebhookListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as WebhookListInstance; + + instance.get = function get(sid, ): WebhookContext { + return new WebhookContextImpl(version, chatServiceSid, conversationSid, sid); + } + + instance._version = version; + instance._solution = { chatServiceSid, conversationSid, }; + instance._uri = `/Services/${chatServiceSid}/Conversations/${conversationSid}/Webhooks`; + + instance.create = function create(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, items: WebhookInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["target"] === null || params["target"] === undefined) { + throw new Error('Required parameter "params[\'target\']" missing.'); + } + + let data: any = {}; + + + + data["Target"] = params["target"]; + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.replayAfter"] !== undefined) + data["Configuration.ReplayAfter"] = params["configuration.replayAfter"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.conversationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["target"] === null || params["target"] === undefined) { + throw new Error('Required parameter "params[\'target\']" missing.'); + } + + let data: any = {}; + + + + data["Target"] = params["target"]; + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.replayAfter"] !== undefined) + data["Configuration.ReplayAfter"] = params["configuration.replayAfter"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.conversationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: WebhookListInstancePageOptions | ((error: Error | null, items: WebhookPage) => any), callback?: (error: Error | null, items: WebhookPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new WebhookPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: WebhookPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new WebhookPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: WebhookListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebhookPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebhookPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class WebhookPage extends Page { +/** +* Initialize the WebhookPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: WebhookSolution) { + super(version, response, solution); + } + + /** + * Build an instance of WebhookInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: WebhookResource): WebhookInstance { + + return new WebhookInstance( + this._version, + payload, + this._solution.chatServiceSid, + this._solution.conversationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service/conversationWithParticipants.ts b/rest/conversations/v1/service/conversationWithParticipants.ts new file mode 100644 index 000000000..16bc41215 --- /dev/null +++ b/rest/conversations/v1/service/conversationWithParticipants.ts @@ -0,0 +1,376 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * Current state of this conversation. Can be either `initializing`, `active`, `inactive` or `closed` and defaults to `active` + */ +export type ConversationWithParticipantsState = 'initializing'|'inactive'|'active'|'closed'; + +export type ConversationWithParticipantsWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to create a ConversationWithParticipantsInstance + */ +export interface ConversationWithParticipantsListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ConversationWithParticipantsWebhookEnabledType; + /** The human-readable name of this conversation, limited to 256 characters. Optional. */ + "friendlyName"?: string; + /** An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\\\'s `sid` in the URL. */ + "uniqueName"?: string; + /** The date that this resource was created. */ + "dateCreated"?: Date; + /** The date that this resource was last updated. */ + "dateUpdated"?: Date; + /** The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. */ + "messagingServiceSid"?: string; + /** An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. */ + "attributes"?: string; + /** */ + "state"?: ConversationWithParticipantsState; + /** ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. */ + "timers.inactive"?: string; + /** ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. */ + "timers.closed"?: string; + /** The default email address that will be used when sending outbound emails in this conversation. */ + "bindings.email.address"?: string; + /** The default name that will be used when sending outbound emails in this conversation. */ + "bindings.email.name"?: string; + /** The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. */ + "participant"?: Array; +} + + +export interface ConversationWithParticipantsSolution { + chatServiceSid: string; +} + +export interface ConversationWithParticipantsListInstance { + _version: V1; + _solution: ConversationWithParticipantsSolution; + _uri: string; + + + + /** + * Create a ConversationWithParticipantsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationWithParticipantsInstance + */ + create(callback?: (error: Error | null, item?: ConversationWithParticipantsInstance) => any): Promise; + /** + * Create a ConversationWithParticipantsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationWithParticipantsInstance + */ + create(params: ConversationWithParticipantsListInstanceCreateOptions, callback?: (error: Error | null, item?: ConversationWithParticipantsInstance) => any): Promise; + + /** + * Create a ConversationWithParticipantsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationWithParticipantsInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ConversationWithParticipantsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationWithParticipantsInstance with HTTP metadata + */ + createWithHttpInfo(params: ConversationWithParticipantsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConversationWithParticipantsListInstance(version: V1, chatServiceSid: string): ConversationWithParticipantsListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + const instance = {} as ConversationWithParticipantsListInstance; + + instance._version = version; + instance._solution = { chatServiceSid, }; + instance._uri = `/Services/${chatServiceSid}/ConversationWithParticipants`; + + instance.create = function create(params?: ConversationWithParticipantsListInstanceCreateOptions | ((error: Error | null, items: ConversationWithParticipantsInstance) => any), callback?: (error: Error | null, items: ConversationWithParticipantsInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + if (params["participant"] !== undefined) + data["Participant"] = serialize.map(params["participant"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationWithParticipantsInstance(operationVersion, payload, instance._solution.chatServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ConversationWithParticipantsListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["timers.inactive"] !== undefined) + data["Timers.Inactive"] = params["timers.inactive"]; + if (params["timers.closed"] !== undefined) + data["Timers.Closed"] = params["timers.closed"]; + if (params["bindings.email.address"] !== undefined) + data["Bindings.Email.Address"] = params["bindings.email.address"]; + if (params["bindings.email.name"] !== undefined) + data["Bindings.Email.Name"] = params["bindings.email.name"]; + if (params["participant"] !== undefined) + data["Participant"] = serialize.map(params["participant"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationWithParticipantsInstance(operationVersion, response.body, instance._solution.chatServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ConversationWithParticipantsPayload extends ConversationWithParticipantsResource {} + +interface ConversationWithParticipantsResource { + account_sid: string; + chat_service_sid: string; + messaging_service_sid: string; + sid: string; + friendly_name: string; + unique_name: string; + attributes: string; + state: ConversationWithParticipantsState; + date_created: Date; + date_updated: Date; + timers: any; + links: Record; + bindings: any; + url: string; +} + +export class ConversationWithParticipantsInstance { + + constructor(protected _version: V1, payload: ConversationWithParticipantsResource, chatServiceSid: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.messagingServiceSid = (payload.messaging_service_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.attributes = (payload.attributes); + this.state = payload.state; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.timers = (payload.timers); + this.links = (payload.links); + this.bindings = (payload.bindings); + this.url = (payload.url); + + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + /** + * The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + */ + chatServiceSid: string; + /** + * The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + */ + messagingServiceSid: string; + /** + * A 34 character string that uniquely identifies this resource. + */ + sid: string; + /** + * The human-readable name of this conversation, limited to 256 characters. Optional. + */ + friendlyName: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource\'s `sid` in the URL. + */ + uniqueName: string; + /** + * An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + attributes: string; + state: ConversationWithParticipantsState; + /** + * The date that this resource was created. + */ + dateCreated: Date; + /** + * The date that this resource was last updated. + */ + dateUpdated: Date; + /** + * Timer date values representing state update for this conversation. + */ + timers: any; + /** + * Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + */ + links: Record; + bindings: any; + /** + * An absolute API resource URL for this conversation. + */ + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + messagingServiceSid: this.messagingServiceSid, + sid: this.sid, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + attributes: this.attributes, + state: this.state, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + timers: this.timers, + links: this.links, + bindings: this.bindings, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/conversations/v1/service/participantConversation.ts b/rest/conversations/v1/service/participantConversation.ts new file mode 100644 index 000000000..0c88b24a8 --- /dev/null +++ b/rest/conversations/v1/service/participantConversation.ts @@ -0,0 +1,511 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The current state of this User Conversation. One of `inactive`, `active` or `closed`. + */ +export type ParticipantConversationState = 'inactive'|'active'|'closed'; + + +/** + * Options to pass to each + */ +export interface ParticipantConversationListInstanceEachOptions { + /** A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. */ + "identity"?: string; + /** A unique string identifier for the conversation participant who\'s not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. */ + "address"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ParticipantConversationListInstanceOptions { + /** A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. */ + "identity"?: string; + /** A unique string identifier for the conversation participant who\'s not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. */ + "address"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ParticipantConversationListInstancePageOptions { + /** A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. */ + "identity"?: string; + /** A unique string identifier for the conversation participant who\'s not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. */ + "address"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface ParticipantConversationSolution { + chatServiceSid: string; +} + +export interface ParticipantConversationListInstance { + _version: V1; + _solution: ParticipantConversationSolution; + _uri: string; + + + + + /** + * Streams ParticipantConversationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void): void; + each(params: ParticipantConversationListInstanceEachOptions, callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ParticipantConversationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ParticipantConversationListInstanceEachOptions, callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ParticipantConversationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise; + /** + * Retrieve a single target page of ParticipantConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ParticipantConversationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ParticipantConversationInstance[]) => any): Promise; + list(params: ParticipantConversationListInstanceOptions, callback?: (error: Error | null, items: ParticipantConversationInstance[]) => any): Promise; + /** + * Lists ParticipantConversationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ParticipantConversationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ParticipantConversationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise; + page(params: ParticipantConversationListInstancePageOptions, callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise; + /** + * Retrieve a single page of ParticipantConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ParticipantConversationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ParticipantConversationListInstance(version: V1, chatServiceSid: string): ParticipantConversationListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + const instance = {} as ParticipantConversationListInstance; + + instance._version = version; + instance._solution = { chatServiceSid, }; + instance._uri = `/Services/${chatServiceSid}/ParticipantConversations`; + + instance.page = function page(params?: ParticipantConversationListInstancePageOptions | ((error: Error | null, items: ParticipantConversationPage) => any), callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["address"] !== undefined) + data["Address"] = params["address"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ParticipantConversationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ParticipantConversationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ParticipantConversationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["address"] !== undefined) + data["Address"] = params["address"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantConversationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantConversationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ParticipantConversationPayload extends TwilioResponsePayload { + conversations: ParticipantConversationResource[]; +} + +interface ParticipantConversationResource { + account_sid: string; + chat_service_sid: string; + participant_sid: string; + participant_user_sid: string; + participant_identity: string; + participant_messaging_binding: any; + conversation_sid: string; + conversation_unique_name: string; + conversation_friendly_name: string; + conversation_attributes: string; + conversation_date_created: Date; + conversation_date_updated: Date; + conversation_created_by: string; + conversation_state: ParticipantConversationState; + conversation_timers: any; + links: Record; +} + +export class ParticipantConversationInstance { + + constructor(protected _version: V1, payload: ParticipantConversationResource, chatServiceSid: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.participantSid = (payload.participant_sid); + this.participantUserSid = (payload.participant_user_sid); + this.participantIdentity = (payload.participant_identity); + this.participantMessagingBinding = (payload.participant_messaging_binding); + this.conversationSid = (payload.conversation_sid); + this.conversationUniqueName = (payload.conversation_unique_name); + this.conversationFriendlyName = (payload.conversation_friendly_name); + this.conversationAttributes = (payload.conversation_attributes); + this.conversationDateCreated = deserialize.iso8601DateTime(payload.conversation_date_created); + this.conversationDateUpdated = deserialize.iso8601DateTime(payload.conversation_date_updated); + this.conversationCreatedBy = (payload.conversation_created_by); + this.conversationState = payload.conversation_state; + this.conversationTimers = (payload.conversation_timers); + this.links = (payload.links); + + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + /** + * The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + */ + chatServiceSid: string; + /** + * The unique ID of the [Participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). + */ + participantSid: string; + /** + * The unique string that identifies the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). + */ + participantUserSid: string; + /** + * A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + */ + participantIdentity: string; + /** + * Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + */ + participantMessagingBinding: any; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) this Participant belongs to. + */ + conversationSid: string; + /** + * An application-defined string that uniquely identifies the Conversation resource. + */ + conversationUniqueName: string; + /** + * The human-readable name of this conversation, limited to 256 characters. Optional. + */ + conversationFriendlyName: string; + /** + * An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + conversationAttributes: string; + /** + * The date that this conversation was created, given in ISO 8601 format. + */ + conversationDateCreated: Date; + /** + * The date that this conversation was last updated, given in ISO 8601 format. + */ + conversationDateUpdated: Date; + /** + * Identity of the creator of this Conversation. + */ + conversationCreatedBy: string; + conversationState: ParticipantConversationState; + /** + * Timer date values representing state update for this conversation. + */ + conversationTimers: any; + /** + * Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + */ + links: Record; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + participantSid: this.participantSid, + participantUserSid: this.participantUserSid, + participantIdentity: this.participantIdentity, + participantMessagingBinding: this.participantMessagingBinding, + conversationSid: this.conversationSid, + conversationUniqueName: this.conversationUniqueName, + conversationFriendlyName: this.conversationFriendlyName, + conversationAttributes: this.conversationAttributes, + conversationDateCreated: this.conversationDateCreated, + conversationDateUpdated: this.conversationDateUpdated, + conversationCreatedBy: this.conversationCreatedBy, + conversationState: this.conversationState, + conversationTimers: this.conversationTimers, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class ParticipantConversationPage extends Page { +/** +* Initialize the ParticipantConversationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ParticipantConversationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ParticipantConversationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ParticipantConversationResource): ParticipantConversationInstance { + + return new ParticipantConversationInstance( + this._version, + payload, + this._solution.chatServiceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service/role.ts b/rest/conversations/v1/service/role.ts new file mode 100644 index 000000000..10bf2742b --- /dev/null +++ b/rest/conversations/v1/service/role.ts @@ -0,0 +1,921 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The type of role. Can be: `conversation` for [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) roles or `service` for [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) roles. + */ +export type RoleRoleType = 'conversation'|'service'; + + + + +/** + * Options to pass to update a RoleInstance + */ +export interface RoleContextUpdateOptions { + /** A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role\\\'s `type`. */ + "permission": Array; +} + +/** + * Options to pass to create a RoleInstance + */ +export interface RoleListInstanceCreateOptions { + /** A descriptive string that you create to describe the new resource. It can be up to 64 characters long. */ + "friendlyName": string; + /** */ + "type": RoleRoleType; + /** A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role\\\'s `type`. */ + "permission": Array; +} + +/** + * Options to pass to each + */ +export interface RoleListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoleInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoleListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoleListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoleContext { + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoleContextSolution { + "chatServiceSid": string; + "sid": string; +} + +export class RoleContextImpl implements RoleContext { + protected _solution: RoleContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, chatServiceSid: string, sid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { chatServiceSid, sid, }; + this._uri = `/Services/${chatServiceSid}/Roles/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RolePayload extends TwilioResponsePayload { + roles: RoleResource[]; +} + +interface RoleResource { + sid: string; + account_sid: string; + chat_service_sid: string; + friendly_name: string; + type: RoleRoleType; + permissions: Array; + date_created: Date; + date_updated: Date; + url: string; +} + +export class RoleInstance { + protected _solution: RoleContextSolution; + protected _context?: RoleContext; + + constructor(protected _version: V1, payload: RoleResource, chatServiceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.permissions = (payload.permissions); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { chatServiceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Role resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Role resource. + */ + accountSid: string; + /** + * The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Role resource is associated with. + */ + chatServiceSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + type: RoleRoleType; + /** + * An array of the permissions the role has been granted. + */ + permissions: Array; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this user role. + */ + url: string; + + private get _proxy(): RoleContext { + this._context = this._context || new RoleContextImpl(this._version, this._solution.chatServiceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: RoleInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + friendlyName: this.friendlyName, + type: this.type, + permissions: this.permissions, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoleSolution { + chatServiceSid: string; +} + +export interface RoleListInstance { + _version: V1; + _solution: RoleSolution; + _uri: string; + + (sid: string, ): RoleContext; + get(sid: string, ): RoleContext; + + + + + + + + + /** + * Create a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Create a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams RoleInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + each(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoleInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single target page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RoleInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + list(params: RoleListInstanceOptions, callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + /** + * Lists RoleInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RoleListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RolePage) => any): Promise; + page(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoleListInstance(version: V1, chatServiceSid: string): RoleListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RoleListInstance; + + instance.get = function get(sid, ): RoleContext { + return new RoleContextImpl(version, chatServiceSid, sid); + } + + instance._version = version; + instance._solution = { chatServiceSid, }; + instance._uri = `/Services/${chatServiceSid}/Roles`; + + instance.create = function create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.chatServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.chatServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RoleListInstancePageOptions | ((error: Error | null, items: RolePage) => any), callback?: (error: Error | null, items: RolePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RolePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RolePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoleListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RolePage extends Page { +/** +* Initialize the RolePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: RoleSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoleInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoleResource): RoleInstance { + + return new RoleInstance( + this._version, + payload, + this._solution.chatServiceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service/user.ts b/rest/conversations/v1/service/user.ts new file mode 100644 index 000000000..d5b6c0989 --- /dev/null +++ b/rest/conversations/v1/service/user.ts @@ -0,0 +1,1076 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { UserConversationListInstance } from "./user/userConversation"; + + +export type UserWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a UserInstance + */ +export interface UserContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserWebhookEnabledType; +} + + +/** + * Options to pass to update a UserInstance + */ +export interface UserContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserWebhookEnabledType; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. */ + "attributes"?: string; + /** The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. */ + "roleSid"?: string; +} + +/** + * Options to pass to create a UserInstance + */ +export interface UserListInstanceCreateOptions { + /** The application-defined string that uniquely identifies the resource\\\'s User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. */ + "identity": string; + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserWebhookEnabledType; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. */ + "attributes"?: string; + /** The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. */ + "roleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface UserListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserContext { + userConversations: UserConversationListInstance; + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + remove(params: UserContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + removeWithHttpInfo(params: UserContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserContextSolution { + "chatServiceSid": string; + "sid": string; +} + +export class UserContextImpl implements UserContext { + protected _solution: UserContextSolution; + protected _uri: string; + + protected _userConversations?: UserConversationListInstance; + + constructor(protected _version: V1, chatServiceSid: string, sid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { chatServiceSid, sid, }; + this._uri = `/Services/${chatServiceSid}/Users/${sid}`; + } + + get userConversations(): UserConversationListInstance { + this._userConversations = this._userConversations || UserConversationListInstance(this._version, this._solution.chatServiceSid, this._solution.sid); + return this._userConversations; + } + + remove(params?: UserContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: UserContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserContextUpdateOptions | ((error: Error | null, item?: UserInstance) => any),callback?: (error: Error | null, item?: UserInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserPayload extends TwilioResponsePayload { + users: UserResource[]; +} + +interface UserResource { + sid: string; + account_sid: string; + chat_service_sid: string; + role_sid: string; + identity: string; + friendly_name: string; + attributes: string; + is_online: boolean; + is_notifiable: boolean; + date_created: Date; + date_updated: Date; + url: string; + links: Record; +} + +export class UserInstance { + protected _solution: UserContextSolution; + protected _context?: UserContext; + + constructor(protected _version: V1, payload: UserResource, chatServiceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.roleSid = (payload.role_sid); + this.identity = (payload.identity); + this.friendlyName = (payload.friendly_name); + this.attributes = (payload.attributes); + this.isOnline = (payload.is_online); + this.isNotifiable = (payload.is_notifiable); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { chatServiceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the User resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User resource. + */ + accountSid: string; + /** + * The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the User resource is associated with. + */ + chatServiceSid: string; + /** + * The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) assigned to the user. + */ + roleSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + */ + identity: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + */ + attributes: string; + /** + * Whether the User is actively connected to this Conversations Service and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service\'s `reachability_enabled` is `false`, if the User has never been online for this Conversations Service, even if the Service\'s `reachability_enabled` is `true`. + */ + isOnline: boolean; + /** + * Whether the User has a potentially valid Push Notification registration (APN or GCM) for this Conversations Service. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service\'s `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service\'s `reachability_enabled` is `true`. + */ + isNotifiable: boolean; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this user. + */ + url: string; + links: Record; + + private get _proxy(): UserContext { + this._context = this._context || new UserContextImpl(this._version, this._solution.chatServiceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + remove(params: UserContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + removeWithHttpInfo(params: UserContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the userConversations. + */ + userConversations(): UserConversationListInstance { + return this._proxy.userConversations; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + roleSid: this.roleSid, + identity: this.identity, + friendlyName: this.friendlyName, + attributes: this.attributes, + isOnline: this.isOnline, + isNotifiable: this.isNotifiable, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserSolution { + chatServiceSid: string; +} + +export interface UserListInstance { + _version: V1; + _solution: UserSolution; + _uri: string; + + (sid: string, ): UserContext; + get(sid: string, ): UserContext; + + + + + + + + + /** + * Create a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Create a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams UserInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + each(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single target page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + list(params: UserListInstanceOptions, callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + /** + * Lists UserInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserPage) => any): Promise; + page(params: UserListInstancePageOptions, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserListInstance(version: V1, chatServiceSid: string): UserListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as UserListInstance; + + instance.get = function get(sid, ): UserContext { + return new UserContextImpl(version, chatServiceSid, sid); + } + + instance._version = version; + instance._solution = { chatServiceSid, }; + instance._uri = `/Services/${chatServiceSid}/Users`; + + instance.create = function create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: UserInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.chatServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.chatServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: UserListInstancePageOptions | ((error: Error | null, items: UserPage) => any), callback?: (error: Error | null, items: UserPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserPage extends Page { +/** +* Initialize the UserPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: UserSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserResource): UserInstance { + + return new UserInstance( + this._version, + payload, + this._solution.chatServiceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/service/user/userConversation.ts b/rest/conversations/v1/service/user/userConversation.ts new file mode 100644 index 000000000..4b5557622 --- /dev/null +++ b/rest/conversations/v1/service/user/userConversation.ts @@ -0,0 +1,909 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The Notification Level of this User Conversation. One of `default` or `muted`. + */ +export type UserConversationNotificationLevel = 'default'|'muted'; + +/** + * The current state of this User Conversation. One of `inactive`, `active` or `closed`. + */ +export type UserConversationState = 'inactive'|'active'|'closed'; + + + + +/** + * Options to pass to update a UserConversationInstance + */ +export interface UserConversationContextUpdateOptions { + /** */ + "notificationLevel"?: UserConversationNotificationLevel; + /** The date of the last message read in conversation by the user, given in ISO 8601 format. */ + "lastReadTimestamp"?: Date; + /** The index of the last Message in the Conversation that the Participant has read. */ + "lastReadMessageIndex"?: number; +} + +/** + * Options to pass to each + */ +export interface UserConversationListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserConversationListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserConversationListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserConversationContext { + + /** + * Remove a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + fetch(callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise + + /** + * Fetch a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + update(callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise; + /** + * Update a UserConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + update(params: UserConversationContextUpdateOptions, callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise; + + /** + * Update a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserConversationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserConversationContextSolution { + "chatServiceSid": string; + "userSid": string; + "conversationSid": string; +} + +export class UserConversationContextImpl implements UserConversationContext { + protected _solution: UserConversationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, chatServiceSid: string, userSid: string, conversationSid: string) { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + this._solution = { chatServiceSid, userSid, conversationSid, }; + this._uri = `/Services/${chatServiceSid}/Users/${userSid}/Conversations/${conversationSid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserConversationInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.userSid, instance._solution.conversationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserConversationInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.userSid, instance._solution.conversationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserConversationContextUpdateOptions | ((error: Error | null, item?: UserConversationInstance) => any),callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["notificationLevel"] !== undefined) + data["NotificationLevel"] = params["notificationLevel"]; + if (params["lastReadTimestamp"] !== undefined) + data["LastReadTimestamp"] = serialize.iso8601DateTime(params["lastReadTimestamp"]); + if (params["lastReadMessageIndex"] !== undefined) + data["LastReadMessageIndex"] = params["lastReadMessageIndex"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserConversationInstance(operationVersion, payload, instance._solution.chatServiceSid, instance._solution.userSid, instance._solution.conversationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserConversationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["notificationLevel"] !== undefined) + data["NotificationLevel"] = params["notificationLevel"]; + if (params["lastReadTimestamp"] !== undefined) + data["LastReadTimestamp"] = serialize.iso8601DateTime(params["lastReadTimestamp"]); + if (params["lastReadMessageIndex"] !== undefined) + data["LastReadMessageIndex"] = params["lastReadMessageIndex"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserConversationInstance(operationVersion, response.body, instance._solution.chatServiceSid, instance._solution.userSid, instance._solution.conversationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserConversationPayload extends TwilioResponsePayload { + conversations: UserConversationResource[]; +} + +interface UserConversationResource { + account_sid: string; + chat_service_sid: string; + conversation_sid: string; + unread_messages_count: number; + last_read_message_index: number; + participant_sid: string; + user_sid: string; + friendly_name: string; + conversation_state: UserConversationState; + timers: any; + attributes: string; + date_created: Date; + date_updated: Date; + created_by: string; + notification_level: UserConversationNotificationLevel; + unique_name: string; + url: string; + links: Record; +} + +export class UserConversationInstance { + protected _solution: UserConversationContextSolution; + protected _context?: UserConversationContext; + + constructor(protected _version: V1, payload: UserConversationResource, chatServiceSid: string, userSid: string, conversationSid?: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.conversationSid = (payload.conversation_sid); + this.unreadMessagesCount = deserialize.integer(payload.unread_messages_count); + this.lastReadMessageIndex = deserialize.integer(payload.last_read_message_index); + this.participantSid = (payload.participant_sid); + this.userSid = (payload.user_sid); + this.friendlyName = (payload.friendly_name); + this.conversationState = payload.conversation_state; + this.timers = (payload.timers); + this.attributes = (payload.attributes); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + this.notificationLevel = payload.notification_level; + this.uniqueName = (payload.unique_name); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { chatServiceSid, userSid, conversationSid: conversationSid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + /** + * The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + */ + chatServiceSid: string; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this User Conversation. + */ + conversationSid: string; + /** + * The number of unread Messages in the Conversation for the Participant. + */ + unreadMessagesCount: number; + /** + * The index of the last Message in the Conversation that the Participant has read. + */ + lastReadMessageIndex: number; + /** + * The unique ID of the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) the user conversation belongs to. + */ + participantSid: string; + /** + * The unique string that identifies the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). + */ + userSid: string; + /** + * The human-readable name of this conversation, limited to 256 characters. Optional. + */ + friendlyName: string; + conversationState: UserConversationState; + /** + * Timer date values representing state update for this conversation. + */ + timers: any; + /** + * An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + attributes: string; + /** + * The date that this conversation was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this conversation was last updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * Identity of the creator of this Conversation. + */ + createdBy: string; + notificationLevel: UserConversationNotificationLevel; + /** + * An application-defined string that uniquely identifies the Conversation resource. It can be used to address the resource in place of the resource\'s `conversation_sid` in the URL. + */ + uniqueName: string; + url: string; + /** + * Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + */ + links: Record; + + private get _proxy(): UserConversationContext { + this._context = this._context || new UserConversationContextImpl(this._version, this._solution.chatServiceSid, this._solution.userSid, this._solution.conversationSid); + return this._context; + } + + /** + * Remove a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + fetch(callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + update(callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise; + /** + * Update a UserConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + update(params: UserConversationContextUpdateOptions, callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserConversationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + conversationSid: this.conversationSid, + unreadMessagesCount: this.unreadMessagesCount, + lastReadMessageIndex: this.lastReadMessageIndex, + participantSid: this.participantSid, + userSid: this.userSid, + friendlyName: this.friendlyName, + conversationState: this.conversationState, + timers: this.timers, + attributes: this.attributes, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + notificationLevel: this.notificationLevel, + uniqueName: this.uniqueName, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserConversationSolution { + chatServiceSid: string; + userSid: string; +} + +export interface UserConversationListInstance { + _version: V1; + _solution: UserConversationSolution; + _uri: string; + + (conversationSid: string, ): UserConversationContext; + get(conversationSid: string, ): UserConversationContext; + + + + + + + + + + /** + * Streams UserConversationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void): void; + each(params: UserConversationListInstanceEachOptions, callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserConversationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserConversationListInstanceEachOptions, callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserConversationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserConversationPage) => any): Promise; + /** + * Retrieve a single target page of UserConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserConversationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserConversationInstance[]) => any): Promise; + list(params: UserConversationListInstanceOptions, callback?: (error: Error | null, items: UserConversationInstance[]) => any): Promise; + /** + * Lists UserConversationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserConversationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserConversationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserConversationPage) => any): Promise; + page(params: UserConversationListInstancePageOptions, callback?: (error: Error | null, items: UserConversationPage) => any): Promise; + /** + * Retrieve a single page of UserConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserConversationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserConversationListInstance(version: V1, chatServiceSid: string, userSid: string): UserConversationListInstance { + if (!isValidPathParam(chatServiceSid)) { + throw new Error('Parameter \'chatServiceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + const instance = ((conversationSid, ) => instance.get(conversationSid, )) as UserConversationListInstance; + + instance.get = function get(conversationSid, ): UserConversationContext { + return new UserConversationContextImpl(version, chatServiceSid, userSid, conversationSid); + } + + instance._version = version; + instance._solution = { chatServiceSid, userSid, }; + instance._uri = `/Services/${chatServiceSid}/Users/${userSid}/Conversations`; + + instance.page = function page(params?: UserConversationListInstancePageOptions | ((error: Error | null, items: UserConversationPage) => any), callback?: (error: Error | null, items: UserConversationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserConversationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserConversationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserConversationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserConversationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserConversationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserConversationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserConversationPage extends Page { +/** +* Initialize the UserConversationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: UserConversationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserConversationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserConversationResource): UserConversationInstance { + + return new UserConversationInstance( + this._version, + payload, + this._solution.chatServiceSid, + this._solution.userSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/user.ts b/rest/conversations/v1/user.ts new file mode 100644 index 000000000..cd3fc3b7d --- /dev/null +++ b/rest/conversations/v1/user.ts @@ -0,0 +1,1065 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { UserConversationListInstance } from "./user/userConversation"; + + +export type UserWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a UserInstance + */ +export interface UserContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserWebhookEnabledType; +} + + +/** + * Options to pass to update a UserInstance + */ +export interface UserContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserWebhookEnabledType; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. */ + "attributes"?: string; + /** The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. */ + "roleSid"?: string; +} + +/** + * Options to pass to create a UserInstance + */ +export interface UserListInstanceCreateOptions { + /** The application-defined string that uniquely identifies the resource\\\'s User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. */ + "identity": string; + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserWebhookEnabledType; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. */ + "attributes"?: string; + /** The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. */ + "roleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface UserListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserContext { + userConversations: UserConversationListInstance; + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + remove(params: UserContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + removeWithHttpInfo(params: UserContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserContextSolution { + "sid": string; +} + +export class UserContextImpl implements UserContext { + protected _solution: UserContextSolution; + protected _uri: string; + + protected _userConversations?: UserConversationListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Users/${sid}`; + } + + get userConversations(): UserConversationListInstance { + this._userConversations = this._userConversations || UserConversationListInstance(this._version, this._solution.sid); + return this._userConversations; + } + + remove(params?: UserContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: UserContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserContextUpdateOptions | ((error: Error | null, item?: UserInstance) => any),callback?: (error: Error | null, item?: UserInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserPayload extends TwilioResponsePayload { + users: UserResource[]; +} + +interface UserResource { + sid: string; + account_sid: string; + chat_service_sid: string; + role_sid: string; + identity: string; + friendly_name: string; + attributes: string; + is_online: boolean; + is_notifiable: boolean; + date_created: Date; + date_updated: Date; + url: string; + links: Record; +} + +export class UserInstance { + protected _solution: UserContextSolution; + protected _context?: UserContext; + + constructor(protected _version: V1, payload: UserResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.roleSid = (payload.role_sid); + this.identity = (payload.identity); + this.friendlyName = (payload.friendly_name); + this.attributes = (payload.attributes); + this.isOnline = (payload.is_online); + this.isNotifiable = (payload.is_notifiable); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the User resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User resource. + */ + accountSid: string; + /** + * The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the User resource is associated with. + */ + chatServiceSid: string; + /** + * The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) assigned to the user. + */ + roleSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + */ + identity: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + */ + attributes: string; + /** + * Whether the User is actively connected to this Conversations Service and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service\'s `reachability_enabled` is `false`, if the User has never been online for this Conversations Service, even if the Service\'s `reachability_enabled` is `true`. + */ + isOnline: boolean; + /** + * Whether the User has a potentially valid Push Notification registration (APN or GCM) for this Conversations Service. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service\'s `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service\'s `reachability_enabled` is `true`. + */ + isNotifiable: boolean; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * An absolute API resource URL for this user. + */ + url: string; + links: Record; + + private get _proxy(): UserContext { + this._context = this._context || new UserContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + remove(params: UserContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + removeWithHttpInfo(params: UserContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the userConversations. + */ + userConversations(): UserConversationListInstance { + return this._proxy.userConversations; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + roleSid: this.roleSid, + identity: this.identity, + friendlyName: this.friendlyName, + attributes: this.attributes, + isOnline: this.isOnline, + isNotifiable: this.isNotifiable, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserSolution { +} + +export interface UserListInstance { + _version: V1; + _solution: UserSolution; + _uri: string; + + (sid: string, ): UserContext; + get(sid: string, ): UserContext; + + + + + + + + + /** + * Create a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Create a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams UserInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + each(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single target page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + list(params: UserListInstanceOptions, callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + /** + * Lists UserInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserPage) => any): Promise; + page(params: UserListInstancePageOptions, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserListInstance(version: V1): UserListInstance { + const instance = ((sid, ) => instance.get(sid, )) as UserListInstance; + + instance.get = function get(sid, ): UserContext { + return new UserContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Users`; + + instance.create = function create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: UserInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: UserListInstancePageOptions | ((error: Error | null, items: UserPage) => any), callback?: (error: Error | null, items: UserPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserPage extends Page { +/** +* Initialize the UserPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: UserSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserResource): UserInstance { + + return new UserInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v1/user/userConversation.ts b/rest/conversations/v1/user/userConversation.ts new file mode 100644 index 000000000..3a53d56a9 --- /dev/null +++ b/rest/conversations/v1/user/userConversation.ts @@ -0,0 +1,898 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Conversations + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The Notification Level of this User Conversation. One of `default` or `muted`. + */ +export type UserConversationNotificationLevel = 'default'|'muted'; + +/** + * The current state of this User Conversation. One of `inactive`, `active` or `closed`. + */ +export type UserConversationState = 'inactive'|'active'|'closed'; + + + + +/** + * Options to pass to update a UserConversationInstance + */ +export interface UserConversationContextUpdateOptions { + /** */ + "notificationLevel"?: UserConversationNotificationLevel; + /** The date of the last message read in conversation by the user, given in ISO 8601 format. */ + "lastReadTimestamp"?: Date; + /** The index of the last Message in the Conversation that the Participant has read. */ + "lastReadMessageIndex"?: number; +} + +/** + * Options to pass to each + */ +export interface UserConversationListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserConversationListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserConversationListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserConversationContext { + + /** + * Remove a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + fetch(callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise + + /** + * Fetch a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + update(callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise; + /** + * Update a UserConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + update(params: UserConversationContextUpdateOptions, callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise; + + /** + * Update a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserConversationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserConversationContextSolution { + "userSid": string; + "conversationSid": string; +} + +export class UserConversationContextImpl implements UserConversationContext { + protected _solution: UserConversationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, userSid: string, conversationSid: string) { + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + if (!isValidPathParam(conversationSid)) { + throw new Error('Parameter \'conversationSid\' is not valid.'); + } + + this._solution = { userSid, conversationSid, }; + this._uri = `/Users/${userSid}/Conversations/${conversationSid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserConversationInstance(operationVersion, payload, instance._solution.userSid, instance._solution.conversationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserConversationInstance(operationVersion, response.body, instance._solution.userSid, instance._solution.conversationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserConversationContextUpdateOptions | ((error: Error | null, item?: UserConversationInstance) => any),callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["notificationLevel"] !== undefined) + data["NotificationLevel"] = params["notificationLevel"]; + if (params["lastReadTimestamp"] !== undefined) + data["LastReadTimestamp"] = serialize.iso8601DateTime(params["lastReadTimestamp"]); + if (params["lastReadMessageIndex"] !== undefined) + data["LastReadMessageIndex"] = params["lastReadMessageIndex"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserConversationInstance(operationVersion, payload, instance._solution.userSid, instance._solution.conversationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserConversationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["notificationLevel"] !== undefined) + data["NotificationLevel"] = params["notificationLevel"]; + if (params["lastReadTimestamp"] !== undefined) + data["LastReadTimestamp"] = serialize.iso8601DateTime(params["lastReadTimestamp"]); + if (params["lastReadMessageIndex"] !== undefined) + data["LastReadMessageIndex"] = params["lastReadMessageIndex"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserConversationInstance(operationVersion, response.body, instance._solution.userSid, instance._solution.conversationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserConversationPayload extends TwilioResponsePayload { + conversations: UserConversationResource[]; +} + +interface UserConversationResource { + account_sid: string; + chat_service_sid: string; + conversation_sid: string; + unread_messages_count: number; + last_read_message_index: number; + participant_sid: string; + user_sid: string; + friendly_name: string; + conversation_state: UserConversationState; + timers: any; + attributes: string; + date_created: Date; + date_updated: Date; + created_by: string; + notification_level: UserConversationNotificationLevel; + unique_name: string; + url: string; + links: Record; +} + +export class UserConversationInstance { + protected _solution: UserConversationContextSolution; + protected _context?: UserConversationContext; + + constructor(protected _version: V1, payload: UserConversationResource, userSid: string, conversationSid?: string) { + + this.accountSid = (payload.account_sid); + this.chatServiceSid = (payload.chat_service_sid); + this.conversationSid = (payload.conversation_sid); + this.unreadMessagesCount = deserialize.integer(payload.unread_messages_count); + this.lastReadMessageIndex = deserialize.integer(payload.last_read_message_index); + this.participantSid = (payload.participant_sid); + this.userSid = (payload.user_sid); + this.friendlyName = (payload.friendly_name); + this.conversationState = payload.conversation_state; + this.timers = (payload.timers); + this.attributes = (payload.attributes); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + this.notificationLevel = payload.notification_level; + this.uniqueName = (payload.unique_name); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { userSid, conversationSid: conversationSid, }; + } + + /** + * The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + */ + accountSid: string; + /** + * The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + */ + chatServiceSid: string; + /** + * The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this User Conversation. + */ + conversationSid: string; + /** + * The number of unread Messages in the Conversation for the Participant. + */ + unreadMessagesCount: number; + /** + * The index of the last Message in the Conversation that the Participant has read. + */ + lastReadMessageIndex: number; + /** + * The unique ID of the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) the user conversation belongs to. + */ + participantSid: string; + /** + * The unique string that identifies the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). + */ + userSid: string; + /** + * The human-readable name of this conversation, limited to 256 characters. Optional. + */ + friendlyName: string; + conversationState: UserConversationState; + /** + * Timer date values representing state update for this conversation. + */ + timers: any; + /** + * An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + */ + attributes: string; + /** + * The date that this conversation was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this conversation was last updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * Identity of the creator of this Conversation. + */ + createdBy: string; + notificationLevel: UserConversationNotificationLevel; + /** + * An application-defined string that uniquely identifies the Conversation resource. It can be used to address the resource in place of the resource\'s `conversation_sid` in the URL. + */ + uniqueName: string; + url: string; + /** + * Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + */ + links: Record; + + private get _proxy(): UserConversationContext { + this._context = this._context || new UserConversationContextImpl(this._version, this._solution.userSid, this._solution.conversationSid); + return this._context; + } + + /** + * Remove a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + fetch(callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + update(callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise; + /** + * Update a UserConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance + */ + update(params: UserConversationContextUpdateOptions, callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserConversationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserConversationInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserConversationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + chatServiceSid: this.chatServiceSid, + conversationSid: this.conversationSid, + unreadMessagesCount: this.unreadMessagesCount, + lastReadMessageIndex: this.lastReadMessageIndex, + participantSid: this.participantSid, + userSid: this.userSid, + friendlyName: this.friendlyName, + conversationState: this.conversationState, + timers: this.timers, + attributes: this.attributes, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + notificationLevel: this.notificationLevel, + uniqueName: this.uniqueName, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserConversationSolution { + userSid: string; +} + +export interface UserConversationListInstance { + _version: V1; + _solution: UserConversationSolution; + _uri: string; + + (conversationSid: string, ): UserConversationContext; + get(conversationSid: string, ): UserConversationContext; + + + + + + + + + + /** + * Streams UserConversationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void): void; + each(params: UserConversationListInstanceEachOptions, callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserConversationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserConversationListInstanceEachOptions, callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserConversationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserConversationPage) => any): Promise; + /** + * Retrieve a single target page of UserConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserConversationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserConversationInstance[]) => any): Promise; + list(params: UserConversationListInstanceOptions, callback?: (error: Error | null, items: UserConversationInstance[]) => any): Promise; + /** + * Lists UserConversationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserConversationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserConversationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserConversationPage) => any): Promise; + page(params: UserConversationListInstancePageOptions, callback?: (error: Error | null, items: UserConversationPage) => any): Promise; + /** + * Retrieve a single page of UserConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserConversationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserConversationListInstance(version: V1, userSid: string): UserConversationListInstance { + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + const instance = ((conversationSid, ) => instance.get(conversationSid, )) as UserConversationListInstance; + + instance.get = function get(conversationSid, ): UserConversationContext { + return new UserConversationContextImpl(version, userSid, conversationSid); + } + + instance._version = version; + instance._solution = { userSid, }; + instance._uri = `/Users/${userSid}/Conversations`; + + instance.page = function page(params?: UserConversationListInstancePageOptions | ((error: Error | null, items: UserConversationPage) => any), callback?: (error: Error | null, items: UserConversationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserConversationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserConversationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserConversationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserConversationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserConversationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserConversationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserConversationPage extends Page { +/** +* Initialize the UserConversationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: UserConversationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserConversationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserConversationResource): UserConversationInstance { + + return new UserConversationInstance( + this._version, + payload, + this._solution.userSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v2/action.ts b/rest/conversations/v2/action.ts new file mode 100644 index 000000000..9f16f4346 --- /dev/null +++ b/rest/conversations/v2/action.ts @@ -0,0 +1,480 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Conversation Orchestrator + * Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Lifecycle status of an Action. + */ +export type ConversationsV2ActionStatus = 'PENDING'|'COMPLETED'|'FAILED'; + +/** + * Channel type for a Communication address. + */ +export type ConversationsV2Channel = 'VOICE'|'SMS'|'RCS'|'WHATSAPP'|'CHAT'; + +/** + * Content for a SEND_MESSAGE action. + */ +export class ConversationsV2SendMessageContent { + /** + * Plain text message body. + */ + "text"?: string; + /** + * Content template ID (HX... format). When provided, the template is rendered with the variables map and sent to the recipient. + */ + "contentId"?: string; + /** + * Variables to substitute into the content template. + */ + "variables"?: { [key: string]: string; }; + /** + * URLs of media attachments to include with the message. + */ + "mediaUrls"?: Array; + + constructor(payload) { + this.text = payload["text"]; + this.contentId = payload["contentId"]; + this.variables = payload["variables"]; + this.mediaUrls = payload["mediaUrls"]; + } +} + + +/** + * Identifies a participant for an Action. Supports three resolution modes: 1. participantId + channel: Resolves address from participant\'s registered addresses 2. participantId only: Resolves when participant has exactly one address 3. address + channel: Uses explicit address + */ +export class ConversationsV2SendMessageParticipant { + /** + * Participant ID to resolve address from. + */ + "participantId"?: string; + /** + * Explicit address formatted according to channel type. + */ + "address"?: string; + "channel"?: ConversationsV2Channel; + + constructor(payload) { + this.participantId = payload["participantId"]; + this.address = payload["address"]; + this.channel = payload["channel"]; + } +} + + +export class ConversationsV2SendMessagePayload { + "from": ConversationsV2SendMessageParticipant; + /** + * The recipients of this action. + */ + "to": Array; + "content": ConversationsV2SendMessageContent; + /** + * Channel-specific parameters forwarded as-is to the downstream sending service. Allows passing backend-specific fields without requiring API changes. + */ + "channelSettings"?: { [key: string]: any; }; + + constructor(payload) { + this.from = payload["from"]; + this.to = payload["to"]; + this.content = payload["content"]; + this.channelSettings = payload["channelSettings"]; + } +} + + +export class CreateConversationActionRequest { + /** + * Action type discriminator. Accepted values: SEND_MESSAGE. + */ + "type": string; + "payload": ConversationsV2SendMessagePayload; + + constructor(payload) { + this.type = payload["type"]; + this.payload = payload["payload"]; + } +} + + + + +/** + * Options to pass to create a ActionInstance + */ +export interface ActionListInstanceCreateOptions { + /** The action to perform. */ + "createConversationActionRequest": CreateConversationActionRequest; +} + +export interface ActionContext { + + /** + * Fetch a ActionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActionInstance + */ + fetch(callback?: (error: Error | null, item?: ActionInstance) => any): Promise + + /** + * Fetch a ActionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ActionContextSolution { + "conversationId": string; + "actionId": string; +} + +export class ActionContextImpl implements ActionContext { + protected _solution: ActionContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, conversationId: string, actionId: string) { + if (!isValidPathParam(conversationId)) { + throw new Error('Parameter \'conversationId\' is not valid.'); + } + + if (!isValidPathParam(actionId)) { + throw new Error('Parameter \'actionId\' is not valid.'); + } + + this._solution = { conversationId, actionId, }; + this._uri = `/Conversations/${conversationId}/Actions/${actionId}`; + } + + fetch(callback?: (error: Error | null, item?: ActionInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ActionInstance(operationVersion, payload, instance._solution.conversationId, instance._solution.actionId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ActionInstance(operationVersion, response.body, instance._solution.conversationId, instance._solution.actionId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + + +interface ActionResource { + id: string; + type: string; + status: ConversationsV2ActionStatus; + conversationId: string; + related: { [key: string]: string; }; + createdAt: Date; + updatedAt: Date; + completedAt: Date; +} + +export class ActionInstance { + protected _solution: ActionContextSolution; + protected _context?: ActionContext; + + constructor(protected _version: V2, _payload: ActionResource, conversationId: string, actionId?: string) { + const payload = _payload; + this.id = (payload.id); + this.type = (payload.type); + this.status = payload.status; + this.conversationId = (payload.conversationId); + this.related = (payload.related); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + this.completedAt = deserialize.iso8601DateTime(payload.completedAt); + + this._solution = { conversationId, actionId: actionId, }; + } + + /** + * Unique identifier for this Action. + */ + id: string; + /** + * The type of action. Accepted values: SEND_MESSAGE. + */ + type: string; + status: ConversationsV2ActionStatus; + /** + * The conversation this action belongs to. + */ + conversationId: string; + /** + * Named identifiers from downstream. For SEND_MESSAGE: - messageSid: The downstream message SID (present when PENDING or COMPLETED) - communicationId: The Communication ID (present when COMPLETED) + */ + related: { [key: string]: string; }; + /** + * Timestamp when the action was created. + */ + createdAt: Date; + /** + * Timestamp when the action was last updated. + */ + updatedAt: Date; + /** + * Timestamp when the action reached a terminal status. + */ + completedAt: Date; + + private get _proxy(): ActionContext { + this._context = this._context || new ActionContextImpl(this._version, this._solution.conversationId, this._solution.actionId); + return this._context; + } + + /** + * Fetch a ActionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActionInstance + */ + fetch(callback?: (error: Error | null, item?: ActionInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ActionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + type: this.type, + status: this.status, + conversationId: this.conversationId, + related: this.related, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + completedAt: this.completedAt, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ActionSolution { + conversationId: string; +} + +export interface ActionListInstance { + _version: V2; + _solution: ActionSolution; + _uri: string; + + (actionId: string, ): ActionContext; + get(actionId: string, ): ActionContext; + + + + + /** + * Create a ActionInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActionInstance + */ + create(params: CreateConversationActionRequest, headers?: any, callback?: (error: Error | null, item?: ActionInstance) => any): Promise; + + /** + * Create a ActionInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActionInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateConversationActionRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ActionListInstance(version: V2, conversationId: string): ActionListInstance { + if (!isValidPathParam(conversationId)) { + throw new Error('Parameter \'conversationId\' is not valid.'); + } + + const instance = ((actionId, ) => instance.get(actionId, )) as ActionListInstance; + + instance.get = function get(actionId, ): ActionContext { + return new ActionContextImpl(version, conversationId, actionId); + } + + instance._version = version; + instance._solution = { conversationId, }; + instance._uri = `/Conversations/${conversationId}/Actions`; + + instance.create = function create(params: CreateConversationActionRequest, headers?: any, callback?: (error: Error | null, items: ActionInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ActionInstance(operationVersion, payload, instance._solution.conversationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateConversationActionRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ActionInstance(operationVersion, response.body, instance._solution.conversationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/conversations/v2/communication.ts b/rest/conversations/v2/communication.ts new file mode 100644 index 000000000..e5c0b8a18 --- /dev/null +++ b/rest/conversations/v2/communication.ts @@ -0,0 +1,910 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Conversation Orchestrator + * Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class ContentTranscriptionTranscription { + "channel"?: number; + "confidence"?: number; + "engine"?: string; + + constructor(payload) { + this.channel = payload["channel"]; + this.confidence = payload["confidence"]; + this.engine = payload["engine"]; + } +} + + +/** + * Channel type for a Communication address. + */ +export type ConversationsV2Channel = 'VOICE'|'SMS'|'RCS'|'WHATSAPP'|'CHAT'; + +/** + * Transcription metadata. + */ +export class ConversationsV2ContentTranscriptionTranscription { + /** + * Audio channel identifier (0 for inbound, 1 for outbound). + */ + "channel"?: number; + /** + * Overall confidence score for the transcription (0.0-1.0). + */ + "confidence"?: number; + /** + * Transcription engine used. + */ + "engine"?: string; + /** + * Word-level transcription data with timing information. + */ + "words"?: Array; + + constructor(payload) { + this.channel = payload["channel"]; + this.confidence = payload["confidence"]; + this.engine = payload["engine"]; + this.words = payload["words"]; + } +} + + +export class ConversationsV2ContentTranscriptionTranscriptionWords { + /** + * The transcribed word. + */ + "text": string; + /** + * Start timestamp of this word. + */ + "startTime"?: Date; + /** + * End timestamp of this word. + */ + "endTime"?: Date; + + constructor(payload) { + this.text = payload["text"]; + this.startTime = payload["startTime"]; + this.endTime = payload["endTime"]; + } +} + + +export class ConversationsV2ParticipantAddress { + /** + * The address value formatted according to channel type: - SMS/VOICE: E.164 phone number (such as \"+18005550100\") - WHATSAPP: Phone number with whatsapp prefix (such as \"whatsapp:+18005550100\") - RCS: Sender ID or phone number with rcs prefix (such as \"rcs:brand_acme_agent\" or \"rcs:+18005550100\") - CHAT: Customer-defined string identifier + */ + "address": string; + "channel": ConversationsV2Channel; + /** + * Participant ID associated with this address. + */ + "participantId"?: string; + + constructor(payload) { + this.address = payload["address"]; + this.channel = payload["channel"]; + this.participantId = payload["participantId"]; + } +} + + +/** + * Delivery status of a Communication to a recipient. + */ +export type ConversationsV2RecipientDeliveryStatus = 'INITIATED'|'IN_PROGRESS'|'DELIVERED'|'COMPLETED'|'FAILED'; + +export class CreateCommunicationInConversationRequest { + "author": CreateCommunicationInConversationRequestAuthor; + "content": CreateCommunicationInConversationRequestContent; + "channelId"?: string; + "recipients": Array; + /** + * Timestamp when this Communication occurred. If omitted, the server uses the current time. + */ + "occurredAt"?: Date; + + constructor(payload) { + this.author = payload["author"]; + this.content = payload["content"]; + this.channelId = payload["channelId"]; + this.recipients = payload["recipients"]; + this.occurredAt = payload["occurredAt"]; + } +} + + +export class CreateCommunicationInConversationRequestAuthor { + "address": string; + /** + * Channel type for a Communication address. + */ + "channel": string; + "participantId"?: string; + + constructor(payload) { + this.address = payload["address"]; + this.channel = payload["channel"]; + this.participantId = payload["participantId"]; + } +} + + +/** + * The content of the Communication. + */ +export class CreateCommunicationInConversationRequestContent { + "type": string; + "text": string; + "transcription"?: ContentTranscriptionTranscription; + + constructor(payload) { + this.type = payload["type"]; + this.text = payload["text"]; + this.transcription = payload["transcription"]; + } +} + + +/** + * The content of the Communication using type field for discrimination. + */ +export class ListCommunicationByConversation200ResponseCommunicationsContent { + /** + * Content type discriminator. + */ + "type": string; + /** + * Transcribed text. + */ + "text": string; + "transcription"?: ConversationsV2ContentTranscriptionTranscription; + + constructor(payload) { + this.type = payload["type"]; + this.text = payload["text"]; + this.transcription = payload["transcription"]; + } +} + + +export class ListCommunicationByConversation200ResponseCommunicationsRecipients { + /** + * The address value formatted according to channel type: - SMS/VOICE: E.164 phone number (such as \"+18005550100\") - WHATSAPP: Phone number with whatsapp prefix (such as \"whatsapp:+18005550100\") - RCS: Sender ID or phone number with rcs prefix (such as \"rcs:brand_acme_agent\" or \"rcs:+18005550100\") - CHAT: Customer-defined string identifier + */ + "address": string; + "channel": ConversationsV2Channel; + /** + * Participant ID associated with this address. + */ + "participantId"?: string; + "deliveryStatus"?: ConversationsV2RecipientDeliveryStatus; + + constructor(payload) { + this.address = payload["address"]; + this.channel = payload["channel"]; + this.participantId = payload["participantId"]; + this.deliveryStatus = payload["deliveryStatus"]; + } +} + + + + +/** + * Options to pass to create a CommunicationInstance + */ +export interface CommunicationListInstanceCreateOptions { + /** */ + "createCommunicationInConversationRequest"?: CreateCommunicationInConversationRequest; +} + +/** + * Options to pass to each + */ +export interface CommunicationListInstanceEachOptions { + /** Resource identifier to filter communications */ + "channelId"?: string; + /** Maximum number of items to return */ + "pageSize"?: number; + /** Page token for pagination */ + "pageToken"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CommunicationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CommunicationListInstanceOptions { + /** Resource identifier to filter communications */ + "channelId"?: string; + /** Maximum number of items to return */ + "pageSize"?: number; + /** Page token for pagination */ + "pageToken"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CommunicationListInstancePageOptions { + /** Resource identifier to filter communications */ + "channelId"?: string; + /** Maximum number of items to return */ + "pageSize"?: number; + /** Page token for pagination */ + "pageToken"?: string; +} + + +export interface CommunicationContext { + + /** + * Fetch a CommunicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommunicationInstance + */ + fetch(callback?: (error: Error | null, item?: CommunicationInstance) => any): Promise + + /** + * Fetch a CommunicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommunicationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CommunicationContextSolution { + "conversationId": string; + "id": string; +} + +export class CommunicationContextImpl implements CommunicationContext { + protected _solution: CommunicationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, conversationId: string, id: string) { + if (!isValidPathParam(conversationId)) { + throw new Error('Parameter \'conversationId\' is not valid.'); + } + + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { conversationId, id, }; + this._uri = `/Conversations/${conversationId}/Communications/${id}`; + } + + fetch(callback?: (error: Error | null, item?: CommunicationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CommunicationInstance(operationVersion, payload, instance._solution.conversationId, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CommunicationInstance(operationVersion, response.body, instance._solution.conversationId, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CommunicationPayload extends TokenPaginationPayload { + communications: CommunicationResource[]; +} + +interface CommunicationResource { + id: string; + conversationId: string; + accountId: string; + author: ConversationsV2ParticipantAddress; + content: ListCommunicationByConversation200ResponseCommunicationsContent; + channelId: string; + resourceId: string; + recipients: Array; + createdAt: Date; + updatedAt: Date; + occurredAt: Date; +} + +export class CommunicationInstance { + protected _solution: CommunicationContextSolution; + protected _context?: CommunicationContext; + + constructor(protected _version: V2, _payload: CommunicationResource, conversationId: string, id?: string) { + const payload = _payload; + this.id = (payload.id); + this.conversationId = (payload.conversationId); + this.accountId = (payload.accountId); + this.author = payload.author !== null && payload.author !== undefined ? new ConversationsV2ParticipantAddress(payload.author) : null; + this.content = payload.content !== null && payload.content !== undefined ? new ListCommunicationByConversation200ResponseCommunicationsContent(payload.content) : null; + this.channelId = (payload.channelId); + this.resourceId = (payload.resourceId); + this.recipients = payload.recipients !== null && payload.recipients !== undefined ? payload.recipients.map( + (payload: any) => new ListCommunicationByConversation200ResponseCommunicationsRecipients(payload) + ) : null; + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + this.occurredAt = deserialize.iso8601DateTime(payload.occurredAt); + + this._solution = { conversationId, id: id, }; + } + + /** + * Communication ID. + */ + id: string; + /** + * Conversation ID. + */ + conversationId: string; + /** + * Account ID. + */ + accountId: string; + author: ConversationsV2ParticipantAddress; + content: ListCommunicationByConversation200ResponseCommunicationsContent; + /** + * Channel-specific reference ID. + */ + channelId: string; + /** + * External resource identifier for this Communication (e.g. MessageSid for SMS/RCS/WhatsApp, TranscriptionSid + MessageIndex for Voice). When set, used for Communication deduplication/uniqueness within a Conversation. + */ + resourceId: string; + /** + * Communication recipients. + */ + recipients: Array; + /** + * Timestamp when this Communication was created. + */ + createdAt: Date; + /** + * Timestamp when this Communication was last updated. + */ + updatedAt: Date; + /** + * ISO 8601 timestamp when the communication occurred. + */ + occurredAt: Date; + + private get _proxy(): CommunicationContext { + this._context = this._context || new CommunicationContextImpl(this._version, this._solution.conversationId, this._solution.id); + return this._context; + } + + /** + * Fetch a CommunicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommunicationInstance + */ + fetch(callback?: (error: Error | null, item?: CommunicationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CommunicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommunicationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + conversationId: this.conversationId, + accountId: this.accountId, + author: this.author, + content: this.content, + channelId: this.channelId, + resourceId: this.resourceId, + recipients: this.recipients, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + occurredAt: this.occurredAt, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CommunicationSolution { + conversationId: string; +} + +export interface CommunicationListInstance { + _version: V2; + _solution: CommunicationSolution; + _uri: string; + + (id: string, ): CommunicationContext; + get(id: string, ): CommunicationContext; + + + + + /** + * Create a CommunicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommunicationInstance + */ + create(callback?: (error: Error | null, item?: CommunicationInstance) => any): Promise; + /** + * Create a CommunicationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommunicationInstance + */ + create(params: CreateCommunicationInConversationRequest, headers?: any, callback?: (error: Error | null, item?: CommunicationInstance) => any): Promise; + + /** + * Create a CommunicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommunicationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a CommunicationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommunicationInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateCommunicationInConversationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CommunicationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommunicationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CommunicationInstance, done: (err?: Error) => void) => void): void; + each(params: CommunicationListInstanceEachOptions, callback?: (item: CommunicationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CommunicationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommunicationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CommunicationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CommunicationListInstanceEachOptions, callback?: (item: CommunicationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CommunicationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CommunicationPage) => any): Promise; + /** + * Retrieve a single target page of CommunicationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CommunicationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommunicationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CommunicationInstance[]) => any): Promise; + list(params: CommunicationListInstanceOptions, callback?: (error: Error | null, items: CommunicationInstance[]) => any): Promise; + /** + * Lists CommunicationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommunicationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CommunicationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CommunicationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommunicationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CommunicationPage) => any): Promise; + page(params: CommunicationListInstancePageOptions, callback?: (error: Error | null, items: CommunicationPage) => any): Promise; + /** + * Retrieve a single page of CommunicationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommunicationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CommunicationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CommunicationListInstance(version: V2, conversationId: string): CommunicationListInstance { + if (!isValidPathParam(conversationId)) { + throw new Error('Parameter \'conversationId\' is not valid.'); + } + + const instance = ((id, ) => instance.get(id, )) as CommunicationListInstance; + + instance.get = function get(id, ): CommunicationContext { + return new CommunicationContextImpl(version, conversationId, id); + } + + instance._version = version; + instance._solution = { conversationId, }; + instance._uri = `/Conversations/${conversationId}/Communications`; + + instance.create = function create(params?: CreateCommunicationInConversationRequest | ((error: Error | null, items: CommunicationInstance) => any), headers?: any, callback?: (error: Error | null, items: CommunicationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as CreateCommunicationInConversationRequest; + } else { + params = params || {} as Partial as CreateCommunicationInConversationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CommunicationInstance(operationVersion, payload, instance._solution.conversationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: CreateCommunicationInConversationRequest | ((error: Error | null, items: ApiResponse) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as CreateCommunicationInConversationRequest; + } else { + params = params || {} as Partial as CreateCommunicationInConversationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CommunicationInstance(operationVersion, response.body, instance._solution.conversationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CommunicationListInstancePageOptions | ((error: Error | null, items: CommunicationPage) => any), callback?: (error: Error | null, items: CommunicationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["channelId"] !== undefined) + data["channelId"] = params["channelId"]; + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CommunicationPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CommunicationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CommunicationPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CommunicationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["channelId"] !== undefined) + data["channelId"] = params["channelId"]; + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CommunicationPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CommunicationPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CommunicationPage extends TokenPage { +/** +* Initialize the CommunicationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, uri: string, params: any, solution: CommunicationSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of CommunicationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CommunicationResource): CommunicationInstance { + + return new CommunicationInstance( + this._version, + payload, + this._solution.conversationId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v2/configuration.ts b/rest/conversations/v2/configuration.ts new file mode 100644 index 000000000..dec1a2cab --- /dev/null +++ b/rest/conversations/v2/configuration.ts @@ -0,0 +1,1540 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Conversation Orchestrator + * Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Defines a capture rule with from and to addresses. Supports wildcard `*` for omnidirectional matching. + */ +export class ConversationsV2CaptureRule { + /** + * The from address. Use `*` for wildcard to match any from address. + */ + "from": string; + /** + * The to address. Use `*` for wildcard to match any to address. + */ + "to": string; + /** + * Additional matching criteria for the capture rule. For voice calls, can include `callType` (`PSTN`, `SIP`, and similar). + */ + "metadata"?: { [key: string]: string; }; + + constructor(payload) { + this.from = payload["from"]; + this.to = payload["to"]; + this.metadata = payload["metadata"]; + } +} + + +/** + * Configuration settings for a specific channel type. + */ +export class ConversationsV2ChannelSetting { + "statusTimeouts"?: ConversationsV2StatusTimeouts; + /** + * Array of capture rules with from/to addresses and optional metadata. Use `*` for wildcard matching in either direction. + */ + "captureRules"?: Array; + + constructor(payload) { + this.statusTimeouts = payload["statusTimeouts"]; + this.captureRules = payload["captureRules"]; + } +} + + +/** + * Type of Conversation grouping strategy: - `GROUP_BY_PROFILE`: Groups Communications by resolved Profile from the Memory Store. A Profile is looked up or created for `CUSTOMER` Participant types. All Communications from the same Profile are in the same Conversation, regardless of address or channel. - `GROUP_BY_PARTICIPANT_ADDRESSES`: Groups Communications by Participant addresses across all channels. A customer using +18005550100 will be in the same Conversation whether they contact by SMS, WhatsApp, or RCS. - `GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE`: Groups Communications by both Participant addresses AND channel. A customer using +18005550100 by SMS will be in a different Conversation than the same customer by Voice. + */ +export type ConversationsV2ConversationGroupingType = 'GROUP_BY_PROFILE'|'GROUP_BY_PARTICIPANT_ADDRESSES'|'GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE'; + +/** + * Configuration for Conversations V1 bridge. When set, messaging channels route through Conversations V1. Use this to integrate with existing Conversations V1 applications. + */ +export class ConversationsV2ConversationsV1Bridge { + /** + * The Conversations V1 Service SID (IS prefix). One configuration per V1 Service SID. + */ + "serviceId": string; + + constructor(payload) { + this.serviceId = payload["serviceId"]; + } +} + + +/** + * Default webhook configuration for Conversation-level events under this Configuration. + */ +export class ConversationsV2StatusCallbackConfig { + /** + * Destination URL for webhooks. + */ + "url": string; + /** + * HTTP method used to invoke the webhook URL. + */ + "method"?: string; + + constructor(payload) { + this.url = payload["url"]; + this.method = payload["method"]; + } +} + + +/** + * Timeout settings for channel status transitions. + */ +export class ConversationsV2StatusTimeouts { + /** + * Inactivity timeout in minutes. + */ + "inactive"?: number; + /** + * Close timeout in minutes. + */ + "closed"?: number; + + constructor(payload) { + this.inactive = payload["inactive"]; + this.closed = payload["closed"]; + } +} + + +export class CreateConfigurationRequest { + /** + * A human-readable name for the configuration. Limited to 32 characters. + */ + "displayName": string; + /** + * Human-readable description for the configuration. + */ + "description": string; + /** + * Type of Conversation grouping strategy: - `GROUP_BY_PROFILE`: Groups Communications by resolved Profile from the Memory Store. A Profile is looked up or created for `CUSTOMER` Participant types. All Communications from the same Profile are in the same Conversation, regardless of address or channel. - `GROUP_BY_PARTICIPANT_ADDRESSES`: Groups Communications by Participant addresses across all channels. A customer using +18005550100 will be in the same Conversation whether they contact by SMS, WhatsApp, or RCS. - `GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE`: Groups Communications by both Participant addresses AND channel. A customer using +18005550100 by SMS will be in a different Conversation than the same customer by Voice. + */ + "conversationGroupingType": string; + /** + * The memory store ID that Conversation Orchestrator uses for profile resolution. + */ + "memoryStoreId": string; + "channelSettings"?: { [key: string]: CreateConfigurationRequestChannelSettingsValue; }; + /** + * A list of webhook configurations. + */ + "statusCallbacks"?: Array; + /** + * A list of Conversational Intelligence configuration IDs. + */ + "intelligenceConfigurationIds"?: Array; + /** + * Whether memory extraction is enabled for conversations under this configuration. Defaults to false. + */ + "memoryExtractionEnabled"?: boolean; + "conversationsV1Bridge"?: CreateConfigurationRequestConversationsV1Bridge; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + this.conversationGroupingType = payload["conversationGroupingType"]; + this.memoryStoreId = payload["memoryStoreId"]; + this.channelSettings = payload["channelSettings"]; + this.statusCallbacks = payload["statusCallbacks"]; + this.intelligenceConfigurationIds = payload["intelligenceConfigurationIds"]; + this.memoryExtractionEnabled = payload["memoryExtractionEnabled"]; + this.conversationsV1Bridge = payload["conversationsV1Bridge"]; + } +} + + +export class CreateConfigurationRequestChannelSettingsValue { + "statusTimeouts"?: CreateConfigurationRequestChannelSettingsValueStatusTimeouts; + "captureRules"?: Array; + + constructor(payload) { + this.statusTimeouts = payload["statusTimeouts"]; + this.captureRules = payload["captureRules"]; + } +} + + +export class CreateConfigurationRequestChannelSettingsValueCaptureRules { + /** + * The from address. Use \'*\' for wildcard. + */ + "from": string; + /** + * The to address. Use \'*\' for wildcard. + */ + "to": string; + "metadata"?: { [key: string]: string; }; + + constructor(payload) { + this.from = payload["from"]; + this.to = payload["to"]; + this.metadata = payload["metadata"]; + } +} + + +export class CreateConfigurationRequestChannelSettingsValueStatusTimeouts { + /** + * The inactivity timeout in minutes. For more information, see [Conversation lifecycle](/docs/platform/conversations/concepts/lifecycle). + */ + "inactive"?: number; + /** + * The close timeout in minutes. For more information, see [Conversation lifecycle](/docs/platform/conversations/concepts/lifecycle). + */ + "closed"?: number; + + constructor(payload) { + this.inactive = payload["inactive"]; + this.closed = payload["closed"]; + } +} + + +/** + * Configuration for Conversations V1 bridge. When set, messaging channels route through Conversations V1. Use this to integrate with existing Conversations V1 applications. + */ +export class CreateConfigurationRequestConversationsV1Bridge { + /** + * The Conversations V1 Service SID (IS prefix). One configuration per V1 Service SID. + */ + "serviceId": string; + + constructor(payload) { + this.serviceId = payload["serviceId"]; + } +} + + +export class CreateConfigurationRequestStatusCallbacks { + /** + * The destination URL for webhooks. + */ + "url": string; + /** + * The HTTP method used to invoke the webhook URL. + */ + "method"?: string; + + constructor(payload) { + this.url = payload["url"]; + this.method = payload["method"]; + } +} + + +export class UpdateConfigurationRequest { + /** + * A human-readable name for the configuration. Limited to 32 characters. + */ + "displayName"?: string; + /** + * Human-readable description for the configuration. + */ + "description": string; + /** + * Type of Conversation grouping strategy: - `GROUP_BY_PROFILE`: Groups Communications by resolved Profile from the Memory Store. A Profile is looked up or created for `CUSTOMER` Participant types. All Communications from the same Profile are in the same Conversation, regardless of address or channel. - `GROUP_BY_PARTICIPANT_ADDRESSES`: Groups Communications by Participant addresses across all channels. A customer using +18005550100 will be in the same Conversation whether they contact by SMS, WhatsApp, or RCS. - `GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE`: Groups Communications by both Participant addresses AND channel. A customer using +18005550100 by SMS will be in a different Conversation than the same customer by Voice. + */ + "conversationGroupingType": string; + /** + * The Memory Store ID for profile resolution. + */ + "memoryStoreId": string; + "channelSettings": { [key: string]: UpdateConfigurationRequestChannelSettingsValue; }; + "statusCallbacks"?: Array; + /** + * A list of Conversational Intelligence configuration IDs. + */ + "intelligenceConfigurationIds"?: Array; + /** + * Whether memory extraction is enabled for conversations under this configuration. Defaults to false. + */ + "memoryExtractionEnabled"?: boolean; + "conversationsV1Bridge"?: CreateConfigurationRequestConversationsV1Bridge; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + this.conversationGroupingType = payload["conversationGroupingType"]; + this.memoryStoreId = payload["memoryStoreId"]; + this.channelSettings = payload["channelSettings"]; + this.statusCallbacks = payload["statusCallbacks"]; + this.intelligenceConfigurationIds = payload["intelligenceConfigurationIds"]; + this.memoryExtractionEnabled = payload["memoryExtractionEnabled"]; + this.conversationsV1Bridge = payload["conversationsV1Bridge"]; + } +} + + +export class UpdateConfigurationRequestChannelSettingsValue { + "statusTimeouts"?: UpdateConfigurationRequestChannelSettingsValueStatusTimeouts; + "captureRules"?: Array; + + constructor(payload) { + this.statusTimeouts = payload["statusTimeouts"]; + this.captureRules = payload["captureRules"]; + } +} + + +export class UpdateConfigurationRequestChannelSettingsValueCaptureRules { + "from": string; + "to": string; + "metadata"?: { [key: string]: string; }; + + constructor(payload) { + this.from = payload["from"]; + this.to = payload["to"]; + this.metadata = payload["metadata"]; + } +} + + +export class UpdateConfigurationRequestChannelSettingsValueStatusTimeouts { + "inactive"?: number; + "closed"?: number; + + constructor(payload) { + this.inactive = payload["inactive"]; + this.closed = payload["closed"]; + } +} + + +export class UpdateConfigurationRequestStatusCallbacks { + "url": string; + "method"?: string; + + constructor(payload) { + this.url = payload["url"]; + this.method = payload["method"]; + } +} + + + +/** + * Options to pass to remove a ConfigurationInstance + */ +export interface ConfigurationContextRemoveOptions { + /** Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. */ + "idempotencyKey"?: string; +} + + +/** + * Options to pass to update a ConfigurationInstance + */ +export interface ConfigurationContextUpdateOptions { + /** Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. */ + "idempotencyKey"?: string; + /** The configuration to update */ + "updateConfigurationRequest"?: UpdateConfigurationRequest; +} + +/** + * Options to pass to create a ConfigurationInstance + */ +export interface ConfigurationListInstanceCreateOptions { + /** Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. */ + "idempotencyKey"?: string; + /** The configuration to create */ + "createConfigurationRequest"?: CreateConfigurationRequest; +} + +/** + * Options to pass to each + */ +export interface ConfigurationListInstanceEachOptions { + /** Maximum number of items to return in a single response */ + "pageSize"?: number; + /** A URL-safe, base64-encoded token representing the page of results to return */ + "pageToken"?: string; + /** Filter configurations by Memory Store ID */ + "memoryStoreId"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConfigurationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConfigurationListInstanceOptions { + /** Maximum number of items to return in a single response */ + "pageSize"?: number; + /** A URL-safe, base64-encoded token representing the page of results to return */ + "pageToken"?: string; + /** Filter configurations by Memory Store ID */ + "memoryStoreId"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConfigurationListInstancePageOptions { + /** Maximum number of items to return in a single response */ + "pageSize"?: number; + /** A URL-safe, base64-encoded token representing the page of results to return */ + "pageToken"?: string; + /** Filter configurations by Memory Store ID */ + "memoryStoreId"?: string; +} + + +export interface ConfigurationContext { + + /** + * Remove a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + remove(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Remove a ConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + remove(params: ConfigurationContextRemoveOptions, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + /** + * Remove a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + removeWithHttpInfo(params: ConfigurationContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Update a ConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(params: UpdateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConfigurationContextSolution { + "id": string; +} + +export class ConfigurationContextImpl implements ConfigurationContext { + protected _solution: ConfigurationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/ControlPlane/Configurations/${id}`; + } + + remove(params?: ConfigurationContextRemoveOptions | ((error: Error | null, item?: ConfigurationInstance) => any),callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["idempotencyKey"] !== undefined) headers["Idempotency-Key"] = params["idempotencyKey"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "delete", params: data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: ConfigurationContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["idempotencyKey"] !== undefined) headers["Idempotency-Key"] = params["idempotencyKey"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation that returns a response model + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UpdateConfigurationRequest | ((error: Error | null, item?: ConfigurationInstance) => any), headers?: any,callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as UpdateConfigurationRequest; + } else { + params = params || {} as Partial as UpdateConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UpdateConfigurationRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as UpdateConfigurationRequest; + } else { + params = params || {} as Partial as UpdateConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for ConversationsV2CaptureRule + */ +export interface ConversationsV2CaptureRule { + from: string; + to: string; + metadata?: { [key: string]: string; }; +} + +/** + * Nested model for ConversationsV2ChannelSetting + */ +export interface ConversationsV2ChannelSetting { + statusTimeouts?: ConversationsV2StatusTimeouts; + captureRules?: Array; +} + +/** + * Nested model for ConversationsV2ConversationsV1Bridge + */ +export interface ConversationsV2ConversationsV1Bridge { + serviceId: string; +} + +/** + * Nested model for ConversationsV2StatusCallbackConfig + */ +export interface ConversationsV2StatusCallbackConfig { + url: string; + method?: string; +} + +/** + * Nested model for ConversationsV2StatusTimeouts + */ +export interface ConversationsV2StatusTimeouts { + inactive?: number; + closed?: number; +} + +/** + * Nested model for CreateConfigurationRequest + */ +export interface CreateConfigurationRequest { + displayName: string; + description: string; + conversationGroupingType: string; + memoryStoreId: string; + channelSettings?: { [key: string]: CreateConfigurationRequestChannelSettingsValue; }; + statusCallbacks?: Array; + intelligenceConfigurationIds?: Array; + memoryExtractionEnabled?: boolean; + conversationsV1Bridge?: CreateConfigurationRequestConversationsV1Bridge; +} + +/** + * Nested model for CreateConfigurationRequestChannelSettingsValue + */ +export interface CreateConfigurationRequestChannelSettingsValue { + statusTimeouts?: CreateConfigurationRequestChannelSettingsValueStatusTimeouts; + captureRules?: Array; +} + +/** + * Nested model for CreateConfigurationRequestChannelSettingsValueCaptureRules + */ +export interface CreateConfigurationRequestChannelSettingsValueCaptureRules { + from: string; + to: string; + metadata?: { [key: string]: string; }; +} + +/** + * Nested model for CreateConfigurationRequestChannelSettingsValueStatusTimeouts + */ +export interface CreateConfigurationRequestChannelSettingsValueStatusTimeouts { + inactive?: number; + closed?: number; +} + +/** + * Nested model for CreateConfigurationRequestConversationsV1Bridge + */ +export interface CreateConfigurationRequestConversationsV1Bridge { + serviceId: string; +} + +/** + * Nested model for CreateConfigurationRequestStatusCallbacks + */ +export interface CreateConfigurationRequestStatusCallbacks { + url: string; + method?: string; +} + +/** + * Nested model for UpdateConfigurationRequest + */ +export interface UpdateConfigurationRequest { + displayName?: string; + description: string; + conversationGroupingType: string; + memoryStoreId: string; + channelSettings: { [key: string]: UpdateConfigurationRequestChannelSettingsValue; }; + statusCallbacks?: Array; + intelligenceConfigurationIds?: Array; + memoryExtractionEnabled?: boolean; + conversationsV1Bridge?: CreateConfigurationRequestConversationsV1Bridge; +} + +/** + * Nested model for UpdateConfigurationRequestChannelSettingsValue + */ +export interface UpdateConfigurationRequestChannelSettingsValue { + statusTimeouts?: UpdateConfigurationRequestChannelSettingsValueStatusTimeouts; + captureRules?: Array; +} + +/** + * Nested model for UpdateConfigurationRequestChannelSettingsValueCaptureRules + */ +export interface UpdateConfigurationRequestChannelSettingsValueCaptureRules { + from: string; + to: string; + metadata?: { [key: string]: string; }; +} + +/** + * Nested model for UpdateConfigurationRequestChannelSettingsValueStatusTimeouts + */ +export interface UpdateConfigurationRequestChannelSettingsValueStatusTimeouts { + inactive?: number; + closed?: number; +} + +/** + * Nested model for UpdateConfigurationRequestStatusCallbacks + */ +export interface UpdateConfigurationRequestStatusCallbacks { + url: string; + method?: string; +} + + + + interface ConfigurationPayload extends TokenPaginationPayload { + configurations: ConfigurationResource[]; +} + +/** + * Response model for ListConfiguration200ResponseConfigurations operations + */ +interface ListConfiguration200ResponseConfigurations_ResponseResource { + id: string; + displayName: string; + description: string; + conversationGroupingType: ConversationsV2ConversationGroupingType; + memoryStoreId: string; + channelSettings?: { [key: string]: ConversationsV2ChannelSetting; }; + statusCallbacks?: Array; + intelligenceConfigurationIds?: Array; + memoryExtractionEnabled?: boolean; + conversationsV1Bridge?: ConversationsV2ConversationsV1Bridge; + createdAt?: Date; + updatedAt?: Date; + version?: number; +} + +/** + * Response model for CreateConfiguration202Response operations + */ +interface CreateConfiguration202Response_ResponseResource { + statusUrl: string; + related?: { [key: string]: string; }; +} + +/** + * Union type for all possible response models + */ +type ConfigurationResource = ListConfiguration200ResponseConfigurations_ResponseResource | CreateConfiguration202Response_ResponseResource; + +/** + * Slim response for an accepted long-running operation. + */ +export class ConfigurationInstance { + protected _solution: ConfigurationContextSolution; + protected _context?: ConfigurationContext; + + constructor(protected _version: V2, _payload: ConfigurationResource, id?: string) { + const payload: any = _payload; + this.id = (payload.id); + this.displayName = (payload.displayName); + this.description = (payload.description); + this.conversationGroupingType = payload.conversationGroupingType; + this.memoryStoreId = (payload.memoryStoreId); + this.channelSettings = payload.channelSettings; + this.statusCallbacks = payload.statusCallbacks !== null && payload.statusCallbacks !== undefined ? payload.statusCallbacks.map( + (payload: any) => new ConversationsV2StatusCallbackConfig(payload) + ) : null; + this.intelligenceConfigurationIds = (payload.intelligenceConfigurationIds); + this.memoryExtractionEnabled = (payload.memoryExtractionEnabled); + this.conversationsV1Bridge = payload.conversationsV1Bridge !== null && payload.conversationsV1Bridge !== undefined ? new ConversationsV2ConversationsV1Bridge(payload.conversationsV1Bridge) : null; + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + this.version = (payload.version); + this.statusUrl = (payload.statusUrl); + this.related = (payload.related); + + this._solution = { id: id, }; + } + + /** + * Configuration ID. + */ + id?: string; + /** + * A human-readable name for the configuration. Limited to 32 characters. + */ + displayName?: string; + /** + * Human-readable description for the Configuration. Allows spaces and special characters, typically limited to a paragraph of text. This serves as a descriptive field rather than just a name. + */ + description?: string; + conversationGroupingType?: ConversationsV2ConversationGroupingType; + /** + * Memory Store ID for Profile resolution. + */ + memoryStoreId?: string; + /** + * Channel-specific configuration settings by channel type. Keys should be valid channel types (`VOICE`, `SMS`, `RCS`, `WHATSAPP`, `CHAT`). + */ + channelSettings?: { [key: string]: ConversationsV2ChannelSetting; }; + /** + * List of default webhook configurations applied to Conversations under this Configuration. + */ + statusCallbacks?: Array; + /** + * A list of Conversational Intelligence configuration IDs. + */ + intelligenceConfigurationIds?: Array; + /** + * Whether memory extraction is enabled for conversations under this configuration. Defaults to false. + */ + memoryExtractionEnabled?: boolean; + conversationsV1Bridge?: ConversationsV2ConversationsV1Bridge; + /** + * Timestamp when this Configuration was created. + */ + createdAt?: Date; + /** + * Timestamp when this Configuration was last updated. + */ + updatedAt?: Date; + /** + * Version number used for optimistic locking. + */ + version?: number; + /** + * URL to poll for operation status. + */ + statusUrl?: string; + /** + * Named resource identifiers associated with this operation. Keys depend on the operation type: - config-create, config-update, config-delete: configurationId - conversation-delete: conversationId + */ + related?: { [key: string]: string; }; + + private get _proxy(): ConfigurationContext { + this._context = this._context || new ConfigurationContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Remove a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + remove(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Remove a ConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + remove(params: ConfigurationContextRemoveOptions, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + removeWithHttpInfo(params: ConfigurationContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Update a ConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(params: UpdateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + displayName: this.displayName, + description: this.description, + conversationGroupingType: this.conversationGroupingType, + memoryStoreId: this.memoryStoreId, + channelSettings: this.channelSettings, + statusCallbacks: this.statusCallbacks, + intelligenceConfigurationIds: this.intelligenceConfigurationIds, + memoryExtractionEnabled: this.memoryExtractionEnabled, + conversationsV1Bridge: this.conversationsV1Bridge, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + version: this.version, + statusUrl: this.statusUrl, + related: this.related, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConfigurationSolution { +} + +export interface ConfigurationListInstance { + _version: V2; + _solution: ConfigurationSolution; + _uri: string; + + (id: string, ): ConfigurationContext; + get(id: string, ): ConfigurationContext; + + + + + + + + + /** + * Create a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + create(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Create a ConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + create(params: CreateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + /** + * Create a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ConfigurationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConfigurationInstance, done: (err?: Error) => void) => void): void; + each(params: ConfigurationListInstanceEachOptions, callback?: (item: ConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConfigurationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConfigurationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConfigurationListInstanceEachOptions, callback?: (item: ConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConfigurationPage) => any): Promise; + /** + * Retrieve a single target page of ConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConfigurationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConfigurationInstance[]) => any): Promise; + list(params: ConfigurationListInstanceOptions, callback?: (error: Error | null, items: ConfigurationInstance[]) => any): Promise; + /** + * Lists ConfigurationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConfigurationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConfigurationPage) => any): Promise; + page(params: ConfigurationListInstancePageOptions, callback?: (error: Error | null, items: ConfigurationPage) => any): Promise; + /** + * Retrieve a single page of ConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConfigurationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConfigurationListInstance(version: V2): ConfigurationListInstance { + const instance = ((id, ) => instance.get(id, )) as ConfigurationListInstance; + + instance.get = function get(id, ): ConfigurationContext { + return new ConfigurationContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ControlPlane/Configurations`; + + instance.create = function create(params?: CreateConfigurationRequest | ((error: Error | null, items: ConfigurationInstance) => any), headers?: any, callback?: (error: Error | null, items: ConfigurationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as CreateConfigurationRequest; + } else { + params = params || {} as Partial as CreateConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: CreateConfigurationRequest | ((error: Error | null, items: ApiResponse) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as CreateConfigurationRequest; + } else { + params = params || {} as Partial as CreateConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ConfigurationListInstancePageOptions | ((error: Error | null, items: ConfigurationPage) => any), callback?: (error: Error | null, items: ConfigurationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["memoryStoreId"] !== undefined) + data["memoryStoreId"] = params["memoryStoreId"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConfigurationPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConfigurationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConfigurationPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConfigurationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["memoryStoreId"] !== undefined) + data["memoryStoreId"] = params["memoryStoreId"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConfigurationPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConfigurationPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConfigurationPage extends TokenPage { +/** +* Initialize the ConfigurationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, uri: string, params: any, solution: ConfigurationSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of ConfigurationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConfigurationResource): ConfigurationInstance { + + return new ConfigurationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v2/conversation.ts b/rest/conversations/v2/conversation.ts new file mode 100644 index 000000000..a904e8991 --- /dev/null +++ b/rest/conversations/v2/conversation.ts @@ -0,0 +1,1640 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Conversation Orchestrator + * Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class ConversationsV2Address { + "channel": ConversationsV2Channel; + /** + * The address value formatted according to channel type: - SMS/VOICE: E.164 phone number (such as \"+18005550100\") - WHATSAPP: Phone number with whatsapp prefix (such as \"whatsapp:+18005550100\") - RCS: Sender ID or phone number with rcs prefix (such as \"rcs:brand_acme_agent\" or \"rcs:+18005550100\") - CHAT: Customer-defined string identifier + */ + "address": string; + /** + * Channel-specific ID for correlating Communications. + */ + "channelId"?: string; + + constructor(payload) { + this.channel = payload["channel"]; + this.address = payload["address"]; + this.channelId = payload["channelId"]; + } +} + + +/** + * Channel type for a Communication address. + */ +export type ConversationsV2Channel = 'VOICE'|'SMS'|'RCS'|'WHATSAPP'|'CHAT'; + +/** + * Type of Conversation grouping strategy: - `GROUP_BY_PROFILE`: Groups Communications by resolved Profile from the Memory Store. A Profile is looked up or created for `CUSTOMER` Participant types. All Communications from the same Profile are in the same Conversation, regardless of address or channel. - `GROUP_BY_PARTICIPANT_ADDRESSES`: Groups Communications by Participant addresses across all channels. A customer using +18005550100 will be in the same Conversation whether they contact by SMS, WhatsApp, or RCS. - `GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE`: Groups Communications by both Participant addresses AND channel. A customer using +18005550100 by SMS will be in a different Conversation than the same customer by Voice. + */ +export type ConversationsV2ConversationGroupingType = 'GROUP_BY_PROFILE'|'GROUP_BY_PARTICIPANT_ADDRESSES'|'GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE'; + +/** + * Lifecycle status of a Conversation. + */ +export type ConversationsV2ConversationStatus = 'ACTIVE'|'INACTIVE'|'CLOSED'; + +/** + * Configuration for Conversations V1 bridge. When set, messaging channels route through Conversations V1. Use this to integrate with existing Conversations V1 applications. + */ +export class ConversationsV2ConversationsV1Bridge { + /** + * The Conversations V1 Service SID (IS prefix). One configuration per V1 Service SID. + */ + "serviceId": string; + + constructor(payload) { + this.serviceId = payload["serviceId"]; + } +} + + +export class ConversationsV2Participant { + /** + * Participant ID. + */ + "id": string; + /** + * Conversation ID. + */ + "conversationId": string; + /** + * Account ID. + */ + "accountId": string; + /** + * Participant display name. + */ + "name": string; + "type"?: ConversationsV2ParticipantType; + /** + * Profile ID. Note: This field is only resolved for `CUSTOMER` participant types, not for `HUMAN_AGENT` or `AI_AGENT` participants. + */ + "profileId"?: string; + /** + * Communication addresses for this Participant. Address format varies by channel: - SMS/VOICE: E.164 phone number (such as \"+18005550100\") - EMAIL: Email address (such as \"user@example.com\") - WHATSAPP: Phone number with whatsapp prefix (such as \"whatsapp:+18005550100\") - RCS: Sender ID or phone number with rcs prefix (such as \"rcs:brand_acme_agent\" or \"rcs:+18005550100\") + */ + "addresses"?: Array; + /** + * Timestamp when this Participant was created. + */ + "createdAt"?: Date; + /** + * Timestamp when this Participant was last updated. + */ + "updatedAt"?: Date; + + constructor(payload) { + this.id = payload["id"]; + this.conversationId = payload["conversationId"]; + this.accountId = payload["accountId"]; + this.name = payload["name"]; + this.type = payload["type"]; + this.profileId = payload["profileId"]; + this.addresses = payload["addresses"]; + this.createdAt = payload["createdAt"]; + this.updatedAt = payload["updatedAt"]; + } +} + + +/** + * Type of Participant in the Conversation. + */ +export type ConversationsV2ParticipantType = 'HUMAN_AGENT'|'CUSTOMER'|'AI_AGENT'|'AGENT'|'UNKNOWN'; + +/** + * Default webhook configuration for Conversation-level events under this Configuration. + */ +export class ConversationsV2StatusCallbackConfig { + /** + * Destination URL for webhooks. + */ + "url": string; + /** + * HTTP method used to invoke the webhook URL. + */ + "method"?: string; + + constructor(payload) { + this.url = payload["url"]; + this.method = payload["method"]; + } +} + + +export class CreateConversationWithConfigRequest { + /** + * The ID of an existing configuration. + */ + "configurationId": string; + /** + * The name of the conversation. + */ + "name"?: string; + "configuration"?: CreateConversationWithConfigRequestConfiguration; + /** + * Optional list of Participants to create with the Conversation. + */ + "participants"?: Array; + + constructor(payload) { + this.configurationId = payload["configurationId"]; + this.name = payload["name"]; + this.configuration = payload["configuration"]; + this.participants = payload["participants"]; + } +} + + +/** + * Conversation configuration settings. + */ +export class CreateConversationWithConfigRequestConfiguration { + /** + * A list of Conversational Intelligence configuration IDs. + */ + "intelligenceConfigurationIds"?: Array; + + constructor(payload) { + this.intelligenceConfigurationIds = payload["intelligenceConfigurationIds"]; + } +} + + +export class CreateConversationWithConfigRequestParticipants { + /** + * Display name for the Participant. + */ + "name"?: string; + /** + * Type of Participant in the Conversation. + */ + "type"?: string; + /** + * Resolved profile ID. + */ + "profileId"?: string; + /** + * List of Communication addresses for the Participant. + */ + "addresses"?: Array; + + constructor(payload) { + this.name = payload["name"]; + this.type = payload["type"]; + this.profileId = payload["profileId"]; + this.addresses = payload["addresses"]; + } +} + + +export class CreateConversationWithConfigRequestParticipantsAddresses { + /** + * Channel type for a Communication address. + */ + "channel": string; + "address": string; + "channelId"?: string; + + constructor(payload) { + this.channel = payload["channel"]; + this.address = payload["address"]; + this.channelId = payload["channelId"]; + } +} + + +/** + * Full configuration settings for this Conversation. + */ +export class ListConversationByAccount200ResponseConversationsConfiguration { + /** + * A human-readable name for the configuration. Limited to 32 characters. + */ + "displayName"?: string; + /** + * Human-readable description for the Configuration. + */ + "description"?: string; + "conversationGroupingType"?: ConversationsV2ConversationGroupingType; + /** + * Memory Store ID for Profile resolution. + */ + "memoryStoreId"?: string; + /** + * Channel-specific parameters forwarded as-is to the downstream sending service. Allows passing backend-specific fields without requiring API changes. + */ + "channelSettings"?: { [key: string]: any; }; + /** + * List of default webhook configurations applied to Conversations under this Configuration. + */ + "statusCallbacks"?: Array; + /** + * List of Intelligence Configuration IDs configured for this Configuration. + */ + "intelligenceConfigurationIds"?: Array; + /** + * Whether memory extraction is enabled for conversations under this configuration. Defaults to false. + */ + "memoryExtractionEnabled"?: boolean; + "conversationsV1Bridge"?: ConversationsV2ConversationsV1Bridge; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + this.conversationGroupingType = payload["conversationGroupingType"]; + this.memoryStoreId = payload["memoryStoreId"]; + this.channelSettings = payload["channelSettings"]; + this.statusCallbacks = payload["statusCallbacks"]; + this.intelligenceConfigurationIds = payload["intelligenceConfigurationIds"]; + this.memoryExtractionEnabled = payload["memoryExtractionEnabled"]; + this.conversationsV1Bridge = payload["conversationsV1Bridge"]; + } +} + + +export class PatchConversationByIdRequest { + /** + * The name of the Conversation. + */ + "name"?: string; + /** + * Lifecycle status of a Conversation. + */ + "status"?: string; + "configuration"?: PatchConversationByIdRequestConfiguration; + + constructor(payload) { + this.name = payload["name"]; + this.status = payload["status"]; + this.configuration = payload["configuration"]; + } +} + + +/** + * Partial configuration update for an existing conversation. Only statusCallbacks can be modified. + */ +export class PatchConversationByIdRequestConfiguration { + /** + * List of webhook configurations for this conversation. Send an empty array to clear all callbacks and stop webhook delivery. + */ + "statusCallbacks"?: Array; + + constructor(payload) { + this.statusCallbacks = payload["statusCallbacks"]; + } +} + + +export class UpdateConversationByIdRequest { + /** + * The name of the Conversation. + */ + "name"?: string; + /** + * Lifecycle status of a Conversation. + */ + "status": string; + + constructor(payload) { + this.name = payload["name"]; + this.status = payload["status"]; + } +} + + + +/** + * Options to pass to remove a ConversationInstance + */ +export interface ConversationContextRemoveOptions { + /** Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. */ + "idempotencyKey"?: string; +} + + +/** + * Options to pass to patch a ConversationInstance + */ +export interface ConversationContextPatchOptions { + /** The conversation fields to update */ + "patchConversationByIdRequest"?: PatchConversationByIdRequest; +} + +/** + * Options to pass to update a ConversationInstance + */ +export interface ConversationContextUpdateOptions { + /** The conversation to update */ + "updateConversationByIdRequest"?: UpdateConversationByIdRequest; +} + +/** + * Options to pass to create a ConversationInstance + */ +export interface ConversationListInstanceCreateOptions { + /** */ + "createConversationWithConfigRequest"?: CreateConversationWithConfigRequest; +} + +/** + * Options to pass to each + */ +export interface ConversationListInstanceEachOptions { + /** Filters for specific statuses */ + "status"?: Array<'ACTIVE' | 'INACTIVE' | 'CLOSED'>; + /** The resource identifier (such as callSid or messageSid) to filter conversations. */ + "channelId"?: string; + /** Maximum number of items to return in a single response */ + "pageSize"?: number; + /** A URL-safe, base64-encoded token representing the page of results to return */ + "pageToken"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConversationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConversationListInstanceOptions { + /** Filters for specific statuses */ + "status"?: Array<'ACTIVE' | 'INACTIVE' | 'CLOSED'>; + /** The resource identifier (such as callSid or messageSid) to filter conversations. */ + "channelId"?: string; + /** Maximum number of items to return in a single response */ + "pageSize"?: number; + /** A URL-safe, base64-encoded token representing the page of results to return */ + "pageToken"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConversationListInstancePageOptions { + /** Filters for specific statuses */ + "status"?: Array<'ACTIVE' | 'INACTIVE' | 'CLOSED'>; + /** The resource identifier (such as callSid or messageSid) to filter conversations. */ + "channelId"?: string; + /** Maximum number of items to return in a single response */ + "pageSize"?: number; + /** A URL-safe, base64-encoded token representing the page of results to return */ + "pageToken"?: string; +} + + +export interface ConversationContext { + + /** + * Remove a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + remove(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Remove a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + remove(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + /** + * Remove a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + removeWithHttpInfo(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + + /** + * Fetch a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Patch a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + patch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Patch a ConversationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + patch(params: PatchConversationByIdRequest, headers?: any, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + /** + * Patch a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + patchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Patch a ConversationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + patchWithHttpInfo(params: PatchConversationByIdRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Update a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Update a ConversationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(params: UpdateConversationByIdRequest, headers?: any, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + /** + * Update a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConversationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateConversationByIdRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConversationContextSolution { + "id": string; +} + +export class ConversationContextImpl implements ConversationContext { + protected _solution: ConversationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/Conversations/${id}`; + } + + remove(params?: ConversationContextRemoveOptions | ((error: Error | null, item?: ConversationInstance) => any),callback?: (error: Error | null, item?: ConversationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["idempotencyKey"] !== undefined) headers["Idempotency-Key"] = params["idempotencyKey"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "delete", params: data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: ConversationContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["idempotencyKey"] !== undefined) headers["Idempotency-Key"] = params["idempotencyKey"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation that returns a response model + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patch(params?: PatchConversationByIdRequest | ((error: Error | null, item?: ConversationInstance) => any), headers?: any,callback?: (error: Error | null, item?: ConversationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as PatchConversationByIdRequest; + } else { + params = params || {} as Partial as PatchConversationByIdRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.patch({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patchWithHttpInfo(params?: PatchConversationByIdRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as PatchConversationByIdRequest; + } else { + params = params || {} as Partial as PatchConversationByIdRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.patchWithResponseInfo({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UpdateConversationByIdRequest | ((error: Error | null, item?: ConversationInstance) => any), headers?: any,callback?: (error: Error | null, item?: ConversationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as UpdateConversationByIdRequest; + } else { + params = params || {} as Partial as UpdateConversationByIdRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UpdateConversationByIdRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as UpdateConversationByIdRequest; + } else { + params = params || {} as Partial as UpdateConversationByIdRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for ConversationsV2Address + */ +export interface ConversationsV2Address { + channel: ConversationsV2Channel; + address: string; + channelId?: string; +} + +/** + * Nested model for ConversationsV2ConversationsV1Bridge + */ +export interface ConversationsV2ConversationsV1Bridge { + serviceId: string; +} + +/** + * Nested model for ConversationsV2Participant + */ +export interface ConversationsV2Participant { + id: string; + conversationId: string; + accountId: string; + name: string; + type?: ConversationsV2ParticipantType; + profileId?: string; + addresses?: Array; + createdAt?: Date; + updatedAt?: Date; +} + +/** + * Nested model for ConversationsV2StatusCallbackConfig + */ +export interface ConversationsV2StatusCallbackConfig { + url: string; + method?: string; +} + +/** + * Nested model for CreateConversationWithConfigRequest + */ +export interface CreateConversationWithConfigRequest { + configurationId: string; + name?: string; + configuration?: CreateConversationWithConfigRequestConfiguration; + participants?: Array; +} + +/** + * Nested model for CreateConversationWithConfigRequestConfiguration + */ +export interface CreateConversationWithConfigRequestConfiguration { + intelligenceConfigurationIds?: Array; +} + +/** + * Nested model for CreateConversationWithConfigRequestParticipants + */ +export interface CreateConversationWithConfigRequestParticipants { + name?: string; + type?: string; + profileId?: string; + addresses?: Array; +} + +/** + * Nested model for CreateConversationWithConfigRequestParticipantsAddresses + */ +export interface CreateConversationWithConfigRequestParticipantsAddresses { + channel: string; + address: string; + channelId?: string; +} + +/** + * Nested model for ListConversationByAccount200ResponseConversationsConfiguration + */ +export interface ListConversationByAccount200ResponseConversationsConfiguration { + displayName?: string; + description?: string; + conversationGroupingType?: ConversationsV2ConversationGroupingType; + memoryStoreId?: string; + channelSettings?: { [key: string]: any; }; + statusCallbacks?: Array; + intelligenceConfigurationIds?: Array; + memoryExtractionEnabled?: boolean; + conversationsV1Bridge?: ConversationsV2ConversationsV1Bridge; +} + +/** + * Nested model for PatchConversationByIdRequest + */ +export interface PatchConversationByIdRequest { + name?: string; + status?: string; + configuration?: PatchConversationByIdRequestConfiguration; +} + +/** + * Nested model for PatchConversationByIdRequestConfiguration + */ +export interface PatchConversationByIdRequestConfiguration { + statusCallbacks?: Array; +} + +/** + * Nested model for UpdateConversationByIdRequest + */ +export interface UpdateConversationByIdRequest { + name?: string; + status: string; +} + + + + interface ConversationPayload extends TokenPaginationPayload { + conversations: ConversationResource[]; +} + +/** + * Response model for CreateConfiguration202Response operations + */ +interface CreateConfiguration202Response_ResponseResource { + statusUrl: string; + related?: { [key: string]: string; }; +} + +/** + * Response model for ListConversationByAccount200ResponseConversations operations + */ +interface ListConversationByAccount200ResponseConversations_ResponseResource { + id: string; + accountId: string; + configurationId: string; + status?: ConversationsV2ConversationStatus; + name?: string; + createdAt?: Date; + updatedAt?: Date; + configuration?: ListConversationByAccount200ResponseConversationsConfiguration; + participants?: Array; +} + +/** + * Union type for all possible response models + */ +type ConversationResource = CreateConfiguration202Response_ResponseResource | ListConversationByAccount200ResponseConversations_ResponseResource; + +export class ConversationInstance { + protected _solution: ConversationContextSolution; + protected _context?: ConversationContext; + + constructor(protected _version: V2, _payload: ConversationResource, id?: string) { + const payload: any = _payload; + this.statusUrl = (payload.statusUrl); + this.related = (payload.related); + this.id = (payload.id); + this.accountId = (payload.accountId); + this.configurationId = (payload.configurationId); + this.status = payload.status; + this.name = (payload.name); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + this.configuration = payload.configuration !== null && payload.configuration !== undefined ? new ListConversationByAccount200ResponseConversationsConfiguration(payload.configuration) : null; + this.participants = payload.participants !== null && payload.participants !== undefined ? payload.participants.map( + (payload: any) => new ConversationsV2Participant(payload) + ) : null; + + this._solution = { id: id, }; + } + + /** + * URL to poll for operation status. + */ + statusUrl?: string; + /** + * Named resource identifiers associated with this operation. Keys depend on the operation type: - config-create, config-update, config-delete: configurationId - conversation-delete: conversationId + */ + related?: { [key: string]: string; }; + /** + * Conversation ID. + */ + id?: string; + /** + * Account ID. + */ + accountId?: string; + /** + * Configuration ID. + */ + configurationId?: string; + status?: ConversationsV2ConversationStatus; + /** + * Conversation name. + */ + name?: string; + /** + * Timestamp when this Conversation was created. + */ + createdAt?: Date; + /** + * Timestamp when this Conversation was last updated. + */ + updatedAt?: Date; + configuration?: ListConversationByAccount200ResponseConversationsConfiguration; + /** + * Participants in this Conversation. + */ + participants?: Array; + + private get _proxy(): ConversationContext { + this._context = this._context || new ConversationContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Remove a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + remove(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Remove a ConversationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + remove(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ConversationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + removeWithHttpInfo(params: ConversationContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Patch a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + patch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Patch a ConversationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + patch(params: PatchConversationByIdRequest, headers?: any, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + patch(params?: any, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + { + return this._proxy.patch(params, callback); + } + + /** + * Patch a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + patchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Patch a ConversationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + patchWithHttpInfo(params: PatchConversationByIdRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + patchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.patchWithHttpInfo(params, callback); + } + + /** + * Update a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Update a ConversationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + update(params: UpdateConversationByIdRequest, headers?: any, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConversationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateConversationByIdRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + statusUrl: this.statusUrl, + related: this.related, + id: this.id, + accountId: this.accountId, + configurationId: this.configurationId, + status: this.status, + name: this.name, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + configuration: this.configuration, + participants: this.participants, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConversationSolution { +} + +export interface ConversationListInstance { + _version: V2; + _solution: ConversationSolution; + _uri: string; + + (id: string, ): ConversationContext; + get(id: string, ): ConversationContext; + + + + + + + + + + + /** + * Create a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + create(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + /** + * Create a ConversationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + create(params: CreateConversationWithConfigRequest, headers?: any, callback?: (error: Error | null, item?: ConversationInstance) => any): Promise; + + /** + * Create a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ConversationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateConversationWithConfigRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ConversationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + each(params: ConversationListInstanceEachOptions, callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConversationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConversationListInstanceEachOptions, callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConversationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConversationPage) => any): Promise; + /** + * Retrieve a single target page of ConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConversationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConversationInstance[]) => any): Promise; + list(params: ConversationListInstanceOptions, callback?: (error: Error | null, items: ConversationInstance[]) => any): Promise; + /** + * Lists ConversationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConversationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConversationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConversationPage) => any): Promise; + page(params: ConversationListInstancePageOptions, callback?: (error: Error | null, items: ConversationPage) => any): Promise; + /** + * Retrieve a single page of ConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConversationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConversationListInstance(version: V2): ConversationListInstance { + const instance = ((id, ) => instance.get(id, )) as ConversationListInstance; + + instance.get = function get(id, ): ConversationContext { + return new ConversationContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Conversations`; + + instance.create = function create(params?: CreateConversationWithConfigRequest | ((error: Error | null, items: ConversationInstance) => any), headers?: any, callback?: (error: Error | null, items: ConversationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as CreateConversationWithConfigRequest; + } else { + params = params || {} as Partial as CreateConversationWithConfigRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: CreateConversationWithConfigRequest | ((error: Error | null, items: ApiResponse) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as CreateConversationWithConfigRequest; + } else { + params = params || {} as Partial as CreateConversationWithConfigRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ConversationListInstancePageOptions | ((error: Error | null, items: ConversationPage) => any), callback?: (error: Error | null, items: ConversationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["status"] = serialize.map(params["status"], (e: string) => (e)); + if (params["channelId"] !== undefined) + data["channelId"] = params["channelId"]; + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConversationPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConversationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConversationPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConversationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["status"] = serialize.map(params["status"], (e: string) => (e)); + if (params["channelId"] !== undefined) + data["channelId"] = params["channelId"]; + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConversationPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConversationPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConversationPage extends TokenPage { +/** +* Initialize the ConversationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, uri: string, params: any, solution: ConversationSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of ConversationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConversationResource): ConversationInstance { + + return new ConversationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/conversations/v2/operation.ts b/rest/conversations/v2/operation.ts new file mode 100644 index 000000000..86a2c57a3 --- /dev/null +++ b/rest/conversations/v2/operation.ts @@ -0,0 +1,313 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Conversation Orchestrator + * Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Lifecycle status of a long-running operation. + */ +export type ConversationsV2OperationStatusValue = 'PENDING'|'COMPLETED'|'FAILED'; + +/** + * Error details if the operation failed. Follows RFC 9457 Problem Details. + */ +export class FetchOperationStatus200ResponseError { + /** + * A URI reference that identifies the problem type. + */ + "type"?: string; + /** + * A short, human-readable summary of the problem type. + */ + "title"?: string; + /** + * The HTTP status code for this occurrence of the problem. + */ + "status"?: number; + /** + * A human-readable explanation specific to this occurrence. + */ + "detail"?: string; + /** + * A URI reference that identifies the specific occurrence of the problem. + */ + "instance"?: string; + + constructor(payload) { + this.type = payload["type"]; + this.title = payload["title"]; + this.status = payload["status"]; + this.detail = payload["detail"]; + this.instance = payload["instance"]; + } +} + + + + +export interface OperationContext { + + /** + * Fetch a OperationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance + */ + fetch(callback?: (error: Error | null, item?: OperationInstance) => any): Promise + + /** + * Fetch a OperationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OperationContextSolution { + "id": string; +} + +export class OperationContextImpl implements OperationContext { + protected _solution: OperationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/ControlPlane/Operations/${id}`; + } + + fetch(callback?: (error: Error | null, item?: OperationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OperationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new OperationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + + +interface OperationResource { + operationId: string; + status: ConversationsV2OperationStatusValue; + createdAt: Date; + completedAt: Date; + statusUrl: string; + error: FetchOperationStatus200ResponseError; + related: { [key: string]: string; }; +} + +/** + * Status of a long-running operation. + */ +export class OperationInstance { + protected _solution: OperationContextSolution; + protected _context?: OperationContext; + + constructor(protected _version: V2, _payload: OperationResource, id?: string) { + const payload = _payload; + this.operationId = (payload.operationId); + this.status = payload.status; + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.completedAt = deserialize.iso8601DateTime(payload.completedAt); + this.statusUrl = (payload.statusUrl); + this.error = payload.error !== null && payload.error !== undefined ? new FetchOperationStatus200ResponseError(payload.error) : null; + this.related = (payload.related); + + this._solution = { id: id, }; + } + + /** + * Unique identifier for the long-running operation. + */ + operationId: string; + status: ConversationsV2OperationStatusValue; + /** + * Timestamp when the operation was created. + */ + createdAt: Date; + /** + * Timestamp when the operation completed. Only present for completed or failed operations. + */ + completedAt: Date; + /** + * URL to poll for operation status. + */ + statusUrl: string; + error: FetchOperationStatus200ResponseError; + /** + * Named resource identifiers associated with this operation. Keys depend on the operation type: - config-create, config-update, config-delete: configurationId - conversation-delete: conversationId + */ + related: { [key: string]: string; }; + + private get _proxy(): OperationContext { + this._context = this._context || new OperationContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Fetch a OperationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance + */ + fetch(callback?: (error: Error | null, item?: OperationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a OperationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + operationId: this.operationId, + status: this.status, + createdAt: this.createdAt, + completedAt: this.completedAt, + statusUrl: this.statusUrl, + error: this.error, + related: this.related, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OperationSolution { +} + +export interface OperationListInstance { + _version: V2; + _solution: OperationSolution; + _uri: string; + + (id: string, ): OperationContext; + get(id: string, ): OperationContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OperationListInstance(version: V2): OperationListInstance { + const instance = ((id, ) => instance.get(id, )) as OperationListInstance; + + instance.get = function get(id, ): OperationContext { + return new OperationContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/conversations/v2/participant.ts b/rest/conversations/v2/participant.ts new file mode 100644 index 000000000..e3646d201 --- /dev/null +++ b/rest/conversations/v2/participant.ts @@ -0,0 +1,946 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Conversation Orchestrator + * Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class ConversationsV2Address { + "channel": ConversationsV2Channel; + /** + * The address value formatted according to channel type: - SMS/VOICE: E.164 phone number (such as \"+18005550100\") - WHATSAPP: Phone number with whatsapp prefix (such as \"whatsapp:+18005550100\") - RCS: Sender ID or phone number with rcs prefix (such as \"rcs:brand_acme_agent\" or \"rcs:+18005550100\") - CHAT: Customer-defined string identifier + */ + "address": string; + /** + * Channel-specific ID for correlating Communications. + */ + "channelId"?: string; + + constructor(payload) { + this.channel = payload["channel"]; + this.address = payload["address"]; + this.channelId = payload["channelId"]; + } +} + + +/** + * Channel type for a Communication address. + */ +export type ConversationsV2Channel = 'VOICE'|'SMS'|'RCS'|'WHATSAPP'|'CHAT'; + +/** + * Type of Participant in the Conversation. + */ +export type ConversationsV2ParticipantType = 'HUMAN_AGENT'|'CUSTOMER'|'AI_AGENT'|'AGENT'|'UNKNOWN'; + +export class CreateConversationWithConfigRequestParticipantsAddresses { + /** + * Channel type for a Communication address. + */ + "channel": string; + "address": string; + "channelId"?: string; + + constructor(payload) { + this.channel = payload["channel"]; + this.address = payload["address"]; + this.channelId = payload["channelId"]; + } +} + + +export class CreateParticipantInConversationRequest { + "name"?: string; + /** + * Type of Participant in the Conversation. + */ + "type"?: string; + "profileId"?: string; + "addresses": Array; + + constructor(payload) { + this.name = payload["name"]; + this.type = payload["type"]; + this.profileId = payload["profileId"]; + this.addresses = payload["addresses"]; + } +} + + +export class UpdateParticipantInConversationRequest { + "name"?: string; + /** + * Type of Participant in the Conversation. + */ + "type"?: string; + "profileId"?: string; + "addresses"?: Array; + + constructor(payload) { + this.name = payload["name"]; + this.type = payload["type"]; + this.profileId = payload["profileId"]; + this.addresses = payload["addresses"]; + } +} + + + + +/** + * Options to pass to update a ParticipantInstance + */ +export interface ParticipantContextUpdateOptions { + /** */ + "updateParticipantInConversationRequest"?: UpdateParticipantInConversationRequest; +} + +/** + * Options to pass to create a ParticipantInstance + */ +export interface ParticipantListInstanceCreateOptions { + /** */ + "createParticipantInConversationRequest"?: CreateParticipantInConversationRequest; +} + +/** + * Options to pass to each + */ +export interface ParticipantListInstanceEachOptions { + /** Maximum number of items to return */ + "pageSize"?: number; + /** Page token for pagination */ + "pageToken"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ParticipantListInstanceOptions { + /** Maximum number of items to return */ + "pageSize"?: number; + /** Page token for pagination */ + "pageToken"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ParticipantListInstancePageOptions { + /** Maximum number of items to return */ + "pageSize"?: number; + /** Page token for pagination */ + "pageToken"?: string; +} + + +export interface ParticipantContext { + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Update a ParticipantInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(params: UpdateParticipantInConversationRequest, headers?: any, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + /** + * Update a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ParticipantInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateParticipantInConversationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ParticipantContextSolution { + "conversationId": string; + "id": string; +} + +export class ParticipantContextImpl implements ParticipantContext { + protected _solution: ParticipantContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, conversationId: string, id: string) { + if (!isValidPathParam(conversationId)) { + throw new Error('Parameter \'conversationId\' is not valid.'); + } + + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { conversationId, id, }; + this._uri = `/Conversations/${conversationId}/Participants/${id}`; + } + + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.conversationId, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.conversationId, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UpdateParticipantInConversationRequest | ((error: Error | null, item?: ParticipantInstance) => any), headers?: any,callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as UpdateParticipantInConversationRequest; + } else { + params = params || {} as Partial as UpdateParticipantInConversationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.conversationId, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UpdateParticipantInConversationRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as UpdateParticipantInConversationRequest; + } else { + params = params || {} as Partial as UpdateParticipantInConversationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.conversationId, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ParticipantPayload extends TokenPaginationPayload { + participants: ParticipantResource[]; +} + +interface ParticipantResource { + id: string; + conversationId: string; + accountId: string; + name: string; + type: ConversationsV2ParticipantType; + profileId: string; + addresses: Array; + createdAt: Date; + updatedAt: Date; +} + +export class ParticipantInstance { + protected _solution: ParticipantContextSolution; + protected _context?: ParticipantContext; + + constructor(protected _version: V2, _payload: ParticipantResource, conversationId: string, id?: string) { + const payload = _payload; + this.id = (payload.id); + this.conversationId = (payload.conversationId); + this.accountId = (payload.accountId); + this.name = (payload.name); + this.type = payload.type; + this.profileId = (payload.profileId); + this.addresses = payload.addresses !== null && payload.addresses !== undefined ? payload.addresses.map( + (payload: any) => new ConversationsV2Address(payload) + ) : null; + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + + this._solution = { conversationId, id: id, }; + } + + /** + * Participant ID. + */ + id: string; + /** + * Conversation ID. + */ + conversationId: string; + /** + * Account ID. + */ + accountId: string; + /** + * Participant display name. + */ + name: string; + type: ConversationsV2ParticipantType; + /** + * Profile ID. Note: This field is only resolved for `CUSTOMER` participant types, not for `HUMAN_AGENT` or `AI_AGENT` participants. + */ + profileId: string; + /** + * Communication addresses for this Participant. Address format varies by channel: - SMS/VOICE: E.164 phone number (such as \"+18005550100\") - EMAIL: Email address (such as \"user@example.com\") - WHATSAPP: Phone number with whatsapp prefix (such as \"whatsapp:+18005550100\") - RCS: Sender ID or phone number with rcs prefix (such as \"rcs:brand_acme_agent\" or \"rcs:+18005550100\") + */ + addresses: Array; + /** + * Timestamp when this Participant was created. + */ + createdAt: Date; + /** + * Timestamp when this Participant was last updated. + */ + updatedAt: Date; + + private get _proxy(): ParticipantContext { + this._context = this._context || new ParticipantContextImpl(this._version, this._solution.conversationId, this._solution.id); + return this._context; + } + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Update a ParticipantInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(params: UpdateParticipantInConversationRequest, headers?: any, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ParticipantInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateParticipantInConversationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + conversationId: this.conversationId, + accountId: this.accountId, + name: this.name, + type: this.type, + profileId: this.profileId, + addresses: this.addresses, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ParticipantSolution { + conversationId: string; +} + +export interface ParticipantListInstance { + _version: V2; + _solution: ParticipantSolution; + _uri: string; + + (id: string, ): ParticipantContext; + get(id: string, ): ParticipantContext; + + + + + + + /** + * Create a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + create(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + /** + * Create a ParticipantInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + create(params: CreateParticipantInConversationRequest, headers?: any, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise; + + /** + * Create a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ParticipantInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateParticipantInConversationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ParticipantInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + each(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ParticipantInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + /** + * Retrieve a single target page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ParticipantInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise; + list(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise; + /** + * Lists ParticipantInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + page(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + /** + * Retrieve a single page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ParticipantListInstance(version: V2, conversationId: string): ParticipantListInstance { + if (!isValidPathParam(conversationId)) { + throw new Error('Parameter \'conversationId\' is not valid.'); + } + + const instance = ((id, ) => instance.get(id, )) as ParticipantListInstance; + + instance.get = function get(id, ): ParticipantContext { + return new ParticipantContextImpl(version, conversationId, id); + } + + instance._version = version; + instance._solution = { conversationId, }; + instance._uri = `/Conversations/${conversationId}/Participants`; + + instance.create = function create(params?: CreateParticipantInConversationRequest | ((error: Error | null, items: ParticipantInstance) => any), headers?: any, callback?: (error: Error | null, items: ParticipantInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as CreateParticipantInConversationRequest; + } else { + params = params || {} as Partial as CreateParticipantInConversationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.conversationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: CreateParticipantInConversationRequest | ((error: Error | null, items: ApiResponse) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as CreateParticipantInConversationRequest; + } else { + params = params || {} as Partial as CreateParticipantInConversationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.conversationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ParticipantPage) => any), callback?: (error: Error | null, items: ParticipantPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ParticipantPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ParticipantPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ParticipantPage extends TokenPage { +/** +* Initialize the ParticipantPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, uri: string, params: any, solution: ParticipantSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of ParticipantInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ParticipantResource): ParticipantInstance { + + return new ParticipantInstance( + this._version, + payload, + this._solution.conversationId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/events/V1.ts b/rest/events/V1.ts new file mode 100644 index 000000000..b259b35f9 --- /dev/null +++ b/rest/events/V1.ts @@ -0,0 +1,65 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Events + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import EventsBase from "../EventsBase"; +import Version from "../../base/Version"; +import { EventTypeListInstance } from "./v1/eventType"; +import { SchemaListInstance } from "./v1/schema"; +import { SinkListInstance } from "./v1/sink"; +import { SubscriptionListInstance } from "./v1/subscription"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Events + * + * @param domain - The Twilio (Twilio.Events) domain + */ + constructor(domain: EventsBase) { + super(domain, "v1"); + } + + /** eventTypes - { Twilio.Events.V1.EventTypeListInstance } resource */ + protected _eventTypes?: EventTypeListInstance; + /** schemas - { Twilio.Events.V1.SchemaListInstance } resource */ + protected _schemas?: SchemaListInstance; + /** sinks - { Twilio.Events.V1.SinkListInstance } resource */ + protected _sinks?: SinkListInstance; + /** subscriptions - { Twilio.Events.V1.SubscriptionListInstance } resource */ + protected _subscriptions?: SubscriptionListInstance; + + /** Getter for eventTypes resource */ + get eventTypes(): EventTypeListInstance { + this._eventTypes = this._eventTypes || EventTypeListInstance(this); + return this._eventTypes; + } + + /** Getter for schemas resource */ + get schemas(): SchemaListInstance { + this._schemas = this._schemas || SchemaListInstance(this); + return this._schemas; + } + + /** Getter for sinks resource */ + get sinks(): SinkListInstance { + this._sinks = this._sinks || SinkListInstance(this); + return this._sinks; + } + + /** Getter for subscriptions resource */ + get subscriptions(): SubscriptionListInstance { + this._subscriptions = this._subscriptions || SubscriptionListInstance(this); + return this._subscriptions; + } + +} diff --git a/rest/events/v1/eventType.ts b/rest/events/v1/eventType.ts new file mode 100644 index 000000000..c88069a53 --- /dev/null +++ b/rest/events/v1/eventType.ts @@ -0,0 +1,579 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Events + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface EventTypeListInstanceEachOptions { + /** A string parameter filtering the results to return only the Event Types using a given schema. */ + "schemaId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EventTypeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EventTypeListInstanceOptions { + /** A string parameter filtering the results to return only the Event Types using a given schema. */ + "schemaId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EventTypeListInstancePageOptions { + /** A string parameter filtering the results to return only the Event Types using a given schema. */ + "schemaId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EventTypeContext { + + /** + * Fetch a EventTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventTypeInstance + */ + fetch(callback?: (error: Error | null, item?: EventTypeInstance) => any): Promise + + /** + * Fetch a EventTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EventTypeContextSolution { + "type": string; +} + +export class EventTypeContextImpl implements EventTypeContext { + protected _solution: EventTypeContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, type: string) { + if (!isValidPathParam(type)) { + throw new Error('Parameter \'type\' is not valid.'); + } + + this._solution = { type, }; + this._uri = `/Types/${type}`; + } + + fetch(callback?: (error: Error | null, item?: EventTypeInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EventTypeInstance(operationVersion, payload, instance._solution.type)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new EventTypeInstance(operationVersion, response.body, instance._solution.type) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EventTypePayload extends TwilioResponsePayload { + types: EventTypeResource[]; +} + +interface EventTypeResource { + type: string; + schema_id: string; + date_created: Date; + date_updated: Date; + description: string; + status: string; + documentation_url: string; + url: string; + links: Record; +} + +export class EventTypeInstance { + protected _solution: EventTypeContextSolution; + protected _context?: EventTypeContext; + + constructor(protected _version: V1, payload: EventTypeResource, type?: string) { + + this.type = (payload.type); + this.schemaId = (payload.schema_id); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.description = (payload.description); + this.status = (payload.status); + this.documentationUrl = (payload.documentation_url); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { type: type, }; + } + + /** + * A string that uniquely identifies this Event Type. + */ + type: string; + /** + * A string that uniquely identifies the Schema this Event Type adheres to. + */ + schemaId: string; + /** + * The date that this Event Type was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Event Type was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * A human readable description for this Event Type. + */ + description: string; + /** + * A string that describes how this Event Type can be used. For example: `available`, `deprecated`, `restricted`, `discontinued`. When the status is `available`, the Event Type can be used normally. + */ + status: string; + /** + * The URL to the documentation or to the most relevant Twilio Changelog entry of this Event Type. + */ + documentationUrl: string; + /** + * The URL of this resource. + */ + url: string; + links: Record; + + private get _proxy(): EventTypeContext { + this._context = this._context || new EventTypeContextImpl(this._version, this._solution.type); + return this._context; + } + + /** + * Fetch a EventTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventTypeInstance + */ + fetch(callback?: (error: Error | null, item?: EventTypeInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EventTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + type: this.type, + schemaId: this.schemaId, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + description: this.description, + status: this.status, + documentationUrl: this.documentationUrl, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EventTypeSolution { +} + +export interface EventTypeListInstance { + _version: V1; + _solution: EventTypeSolution; + _uri: string; + + (type: string, ): EventTypeContext; + get(type: string, ): EventTypeContext; + + + + + + /** + * Streams EventTypeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EventTypeInstance, done: (err?: Error) => void) => void): void; + each(params: EventTypeListInstanceEachOptions, callback?: (item: EventTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EventTypeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EventTypeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EventTypeListInstanceEachOptions, callback?: (item: EventTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EventTypeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EventTypePage) => any): Promise; + /** + * Retrieve a single target page of EventTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists EventTypeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EventTypeInstance[]) => any): Promise; + list(params: EventTypeListInstanceOptions, callback?: (error: Error | null, items: EventTypeInstance[]) => any): Promise; + /** + * Lists EventTypeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: EventTypeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of EventTypeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EventTypePage) => any): Promise; + page(params: EventTypeListInstancePageOptions, callback?: (error: Error | null, items: EventTypePage) => any): Promise; + /** + * Retrieve a single page of EventTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: EventTypeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EventTypeListInstance(version: V1): EventTypeListInstance { + const instance = ((type, ) => instance.get(type, )) as EventTypeListInstance; + + instance.get = function get(type, ): EventTypeContext { + return new EventTypeContextImpl(version, type); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Types`; + + instance.page = function page(params?: EventTypeListInstancePageOptions | ((error: Error | null, items: EventTypePage) => any), callback?: (error: Error | null, items: EventTypePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["schemaId"] !== undefined) + data["SchemaId"] = params["schemaId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EventTypePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EventTypePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EventTypePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EventTypeListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["schemaId"] !== undefined) + data["SchemaId"] = params["schemaId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EventTypePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EventTypePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EventTypePage extends Page { +/** +* Initialize the EventTypePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: EventTypeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EventTypeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EventTypeResource): EventTypeInstance { + + return new EventTypeInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/events/v1/schema.ts b/rest/events/v1/schema.ts new file mode 100644 index 000000000..461ceee04 --- /dev/null +++ b/rest/events/v1/schema.ts @@ -0,0 +1,277 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Events + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { SchemaVersionListInstance } from "./schema/schemaVersion"; + + + + +export interface SchemaContext { + versions: SchemaVersionListInstance; + + /** + * Fetch a SchemaInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SchemaInstance + */ + fetch(callback?: (error: Error | null, item?: SchemaInstance) => any): Promise + + /** + * Fetch a SchemaInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SchemaInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SchemaContextSolution { + "id": string; +} + +export class SchemaContextImpl implements SchemaContext { + protected _solution: SchemaContextSolution; + protected _uri: string; + + protected _versions?: SchemaVersionListInstance; + + constructor(protected _version: V1, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/Schemas/${id}`; + } + + get versions(): SchemaVersionListInstance { + this._versions = this._versions || SchemaVersionListInstance(this._version, this._solution.id); + return this._versions; + } + + fetch(callback?: (error: Error | null, item?: SchemaInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SchemaInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new SchemaInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SchemaPayload extends SchemaResource {} + +interface SchemaResource { + id: string; + url: string; + links: Record; + latest_version_date_created: Date; + latest_version: number; +} + +export class SchemaInstance { + protected _solution: SchemaContextSolution; + protected _context?: SchemaContext; + + constructor(protected _version: V1, payload: SchemaResource, id?: string) { + + this.id = (payload.id); + this.url = (payload.url); + this.links = (payload.links); + this.latestVersionDateCreated = deserialize.iso8601DateTime(payload.latest_version_date_created); + this.latestVersion = deserialize.integer(payload.latest_version); + + this._solution = { id: id, }; + } + + /** + * The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + */ + id: string; + /** + * The URL of this resource. + */ + url: string; + /** + * Contains a dictionary of URL links to nested resources of this schema. + */ + links: Record; + /** + * The date that the latest schema version was created, given in ISO 8601 format. + */ + latestVersionDateCreated: Date; + /** + * The latest version published of this schema. + */ + latestVersion: number; + + private get _proxy(): SchemaContext { + this._context = this._context || new SchemaContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Fetch a SchemaInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SchemaInstance + */ + fetch(callback?: (error: Error | null, item?: SchemaInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SchemaInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SchemaInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the versions. + */ + versions(): SchemaVersionListInstance { + return this._proxy.versions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + url: this.url, + links: this.links, + latestVersionDateCreated: this.latestVersionDateCreated, + latestVersion: this.latestVersion, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SchemaSolution { +} + +export interface SchemaListInstance { + _version: V1; + _solution: SchemaSolution; + _uri: string; + + (id: string, ): SchemaContext; + get(id: string, ): SchemaContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SchemaListInstance(version: V1): SchemaListInstance { + const instance = ((id, ) => instance.get(id, )) as SchemaListInstance; + + instance.get = function get(id, ): SchemaContext { + return new SchemaContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/events/v1/schema/schemaVersion.ts b/rest/events/v1/schema/schemaVersion.ts new file mode 100644 index 000000000..24478a45d --- /dev/null +++ b/rest/events/v1/schema/schemaVersion.ts @@ -0,0 +1,552 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Events + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface SchemaVersionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SchemaVersionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SchemaVersionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SchemaVersionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SchemaVersionContext { + + /** + * Fetch a SchemaVersionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SchemaVersionInstance + */ + fetch(callback?: (error: Error | null, item?: SchemaVersionInstance) => any): Promise + + /** + * Fetch a SchemaVersionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SchemaVersionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SchemaVersionContextSolution { + "id": string; + "schemaVersion": number; +} + +export class SchemaVersionContextImpl implements SchemaVersionContext { + protected _solution: SchemaVersionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, id: string, schemaVersion: number) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + if (!isValidPathParam(schemaVersion)) { + throw new Error('Parameter \'schemaVersion\' is not valid.'); + } + + this._solution = { id, schemaVersion, }; + this._uri = `/Schemas/${id}/Versions/${schemaVersion}`; + } + + fetch(callback?: (error: Error | null, item?: SchemaVersionInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SchemaVersionInstance(operationVersion, payload, instance._solution.id, instance._solution.schemaVersion)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new SchemaVersionInstance(operationVersion, response.body, instance._solution.id, instance._solution.schemaVersion) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SchemaVersionPayload extends TwilioResponsePayload { + schema_versions: SchemaVersionResource[]; +} + +interface SchemaVersionResource { + id: string; + schema_version: number; + date_created: Date; + url: string; + raw: string; +} + +export class SchemaVersionInstance { + protected _solution: SchemaVersionContextSolution; + protected _context?: SchemaVersionContext; + + constructor(protected _version: V1, payload: SchemaVersionResource, id: string, schemaVersion?: number) { + + this.id = (payload.id); + this.schemaVersion = deserialize.integer(payload.schema_version); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + this.raw = (payload.raw); + + this._solution = { id, schemaVersion: schemaVersion, }; + } + + /** + * The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + */ + id: string; + /** + * The version of this schema. + */ + schemaVersion: number; + /** + * The date the schema version was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The URL of this resource. + */ + url: string; + raw: string; + + private get _proxy(): SchemaVersionContext { + this._context = this._context || new SchemaVersionContextImpl(this._version, this._solution.id, this._solution.schemaVersion); + return this._context; + } + + /** + * Fetch a SchemaVersionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SchemaVersionInstance + */ + fetch(callback?: (error: Error | null, item?: SchemaVersionInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SchemaVersionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SchemaVersionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + schemaVersion: this.schemaVersion, + dateCreated: this.dateCreated, + url: this.url, + raw: this.raw, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SchemaVersionSolution { + id: string; +} + +export interface SchemaVersionListInstance { + _version: V1; + _solution: SchemaVersionSolution; + _uri: string; + + (schemaVersion: number, ): SchemaVersionContext; + get(schemaVersion: number, ): SchemaVersionContext; + + + + + + /** + * Streams SchemaVersionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SchemaVersionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SchemaVersionInstance, done: (err?: Error) => void) => void): void; + each(params: SchemaVersionListInstanceEachOptions, callback?: (item: SchemaVersionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SchemaVersionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SchemaVersionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SchemaVersionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SchemaVersionListInstanceEachOptions, callback?: (item: SchemaVersionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SchemaVersionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SchemaVersionPage) => any): Promise; + /** + * Retrieve a single target page of SchemaVersionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists SchemaVersionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SchemaVersionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SchemaVersionInstance[]) => any): Promise; + list(params: SchemaVersionListInstanceOptions, callback?: (error: Error | null, items: SchemaVersionInstance[]) => any): Promise; + /** + * Lists SchemaVersionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SchemaVersionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: SchemaVersionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of SchemaVersionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SchemaVersionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SchemaVersionPage) => any): Promise; + page(params: SchemaVersionListInstancePageOptions, callback?: (error: Error | null, items: SchemaVersionPage) => any): Promise; + /** + * Retrieve a single page of SchemaVersionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SchemaVersionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: SchemaVersionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SchemaVersionListInstance(version: V1, id: string): SchemaVersionListInstance { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + const instance = ((schemaVersion, ) => instance.get(schemaVersion, )) as SchemaVersionListInstance; + + instance.get = function get(schemaVersion, ): SchemaVersionContext { + return new SchemaVersionContextImpl(version, id, schemaVersion); + } + + instance._version = version; + instance._solution = { id, }; + instance._uri = `/Schemas/${id}/Versions`; + + instance.page = function page(params?: SchemaVersionListInstancePageOptions | ((error: Error | null, items: SchemaVersionPage) => any), callback?: (error: Error | null, items: SchemaVersionPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SchemaVersionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SchemaVersionPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SchemaVersionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SchemaVersionListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SchemaVersionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SchemaVersionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SchemaVersionPage extends Page { +/** +* Initialize the SchemaVersionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: SchemaVersionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SchemaVersionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SchemaVersionResource): SchemaVersionInstance { + + return new SchemaVersionInstance( + this._version, + payload, + this._solution.id, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/events/v1/sink.ts b/rest/events/v1/sink.ts new file mode 100644 index 000000000..bbcd9d8c0 --- /dev/null +++ b/rest/events/v1/sink.ts @@ -0,0 +1,962 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Events + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { SinkTestListInstance } from "./sink/sinkTest"; +import { SinkValidateListInstance } from "./sink/sinkValidate"; + + +/** + * The Sink type. Can only be \"kinesis\" or \"webhook\" currently. + */ +export type SinkSinkType = 'kinesis'|'webhook'|'segment'|'email'; + +/** + * The Status of this Sink. One of `initialized`, `validating`, `active` or `failed`. + */ +export type SinkStatus = 'initialized'|'validating'|'active'|'failed'; + + + + +/** + * Options to pass to update a SinkInstance + */ +export interface SinkContextUpdateOptions { + /** A human readable description for the Sink **This value should not contain PII.** */ + "description": string; +} + +/** + * Options to pass to create a SinkInstance + */ +export interface SinkListInstanceCreateOptions { + /** A human readable description for the Sink **This value should not contain PII.** */ + "description": string; + /** The information required for Twilio to connect to the provided Sink encoded as JSON. */ + "sinkConfiguration": any; + /** */ + "sinkType": SinkSinkType; +} + +/** + * Options to pass to each + */ +export interface SinkListInstanceEachOptions { + /** A boolean query parameter filtering the results to return sinks used/not used by a subscription. */ + "inUse"?: boolean; + /** A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. */ + "status"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SinkInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SinkListInstanceOptions { + /** A boolean query parameter filtering the results to return sinks used/not used by a subscription. */ + "inUse"?: boolean; + /** A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. */ + "status"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SinkListInstancePageOptions { + /** A boolean query parameter filtering the results to return sinks used/not used by a subscription. */ + "inUse"?: boolean; + /** A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. */ + "status"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SinkContext { + sinkTest: SinkTestListInstance; + sinkValidate: SinkValidateListInstance; + + /** + * Remove a SinkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a SinkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a SinkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkInstance + */ + fetch(callback?: (error: Error | null, item?: SinkInstance) => any): Promise + + /** + * Fetch a SinkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a SinkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkInstance + */ + update(params: SinkContextUpdateOptions, callback?: (error: Error | null, item?: SinkInstance) => any): Promise; + + /** + * Update a SinkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkInstance with HTTP metadata + */ + updateWithHttpInfo(params: SinkContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SinkContextSolution { + "sid": string; +} + +export class SinkContextImpl implements SinkContext { + protected _solution: SinkContextSolution; + protected _uri: string; + + protected _sinkTest?: SinkTestListInstance; + protected _sinkValidate?: SinkValidateListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Sinks/${sid}`; + } + + get sinkTest(): SinkTestListInstance { + this._sinkTest = this._sinkTest || SinkTestListInstance(this._version, this._solution.sid); + return this._sinkTest; + } + + get sinkValidate(): SinkValidateListInstance { + this._sinkValidate = this._sinkValidate || SinkValidateListInstance(this._version, this._solution.sid); + return this._sinkValidate; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SinkInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SinkInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new SinkInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: SinkContextUpdateOptions,callback?: (error: Error | null, item?: SinkInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["description"] === null || params["description"] === undefined) { + throw new Error('Required parameter "params[\'description\']" missing.'); + } + + let data: any = {}; + + + + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SinkInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: SinkContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["description"] === null || params["description"] === undefined) { + throw new Error('Required parameter "params[\'description\']" missing.'); + } + + let data: any = {}; + + + + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SinkInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SinkPayload extends TwilioResponsePayload { + sinks: SinkResource[]; +} + +interface SinkResource { + date_created: Date; + date_updated: Date; + description: string; + sid: string; + sink_configuration: any; + sink_type: SinkSinkType; + status: SinkStatus; + url: string; + links: Record; +} + +export class SinkInstance { + protected _solution: SinkContextSolution; + protected _context?: SinkContext; + + constructor(protected _version: V1, payload: SinkResource, sid?: string) { + + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.description = (payload.description); + this.sid = (payload.sid); + this.sinkConfiguration = (payload.sink_configuration); + this.sinkType = payload.sink_type; + this.status = payload.status; + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The date that this Sink was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Sink was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * A human readable description for the Sink + */ + description: string; + /** + * A 34 character string that uniquely identifies this Sink. + */ + sid: string; + /** + * The information required for Twilio to connect to the provided Sink encoded as JSON. + */ + sinkConfiguration: any; + sinkType: SinkSinkType; + status: SinkStatus; + /** + * The URL of this resource. + */ + url: string; + /** + * Contains a dictionary of URL links to nested resources of this Sink. + */ + links: Record; + + private get _proxy(): SinkContext { + this._context = this._context || new SinkContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a SinkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SinkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SinkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkInstance + */ + fetch(callback?: (error: Error | null, item?: SinkInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SinkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SinkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkInstance + */ + update(params: SinkContextUpdateOptions, callback?: (error: Error | null, item?: SinkInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: SinkInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a SinkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkInstance with HTTP metadata + */ + updateWithHttpInfo(params: SinkContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the sinkTest. + */ + sinkTest(): SinkTestListInstance { + return this._proxy.sinkTest; + } + + /** + * Access the sinkValidate. + */ + sinkValidate(): SinkValidateListInstance { + return this._proxy.sinkValidate; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + description: this.description, + sid: this.sid, + sinkConfiguration: this.sinkConfiguration, + sinkType: this.sinkType, + status: this.status, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SinkSolution { +} + +export interface SinkListInstance { + _version: V1; + _solution: SinkSolution; + _uri: string; + + (sid: string, ): SinkContext; + get(sid: string, ): SinkContext; + + + + + + + + + /** + * Create a SinkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkInstance + */ + create(params: SinkListInstanceCreateOptions, callback?: (error: Error | null, item?: SinkInstance) => any): Promise; + + /** + * Create a SinkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkInstance with HTTP metadata + */ + createWithHttpInfo(params: SinkListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams SinkInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SinkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SinkInstance, done: (err?: Error) => void) => void): void; + each(params: SinkListInstanceEachOptions, callback?: (item: SinkInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SinkInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SinkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SinkInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SinkListInstanceEachOptions, callback?: (item: SinkInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SinkInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SinkPage) => any): Promise; + /** + * Retrieve a single target page of SinkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists SinkInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SinkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SinkInstance[]) => any): Promise; + list(params: SinkListInstanceOptions, callback?: (error: Error | null, items: SinkInstance[]) => any): Promise; + /** + * Lists SinkInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SinkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: SinkListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of SinkInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SinkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SinkPage) => any): Promise; + page(params: SinkListInstancePageOptions, callback?: (error: Error | null, items: SinkPage) => any): Promise; + /** + * Retrieve a single page of SinkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SinkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: SinkListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SinkListInstance(version: V1): SinkListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SinkListInstance; + + instance.get = function get(sid, ): SinkContext { + return new SinkContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Sinks`; + + instance.create = function create(params: SinkListInstanceCreateOptions, callback?: (error: Error | null, items: SinkInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["description"] === null || params["description"] === undefined) { + throw new Error('Required parameter "params[\'description\']" missing.'); + } + + if (params["sinkConfiguration"] === null || params["sinkConfiguration"] === undefined) { + throw new Error('Required parameter "params[\'sinkConfiguration\']" missing.'); + } + + if (params["sinkType"] === null || params["sinkType"] === undefined) { + throw new Error('Required parameter "params[\'sinkType\']" missing.'); + } + + let data: any = {}; + + + + data["Description"] = params["description"]; + + data["SinkConfiguration"] = serialize.object(params["sinkConfiguration"]); + + data["SinkType"] = params["sinkType"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SinkInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SinkListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["description"] === null || params["description"] === undefined) { + throw new Error('Required parameter "params[\'description\']" missing.'); + } + + if (params["sinkConfiguration"] === null || params["sinkConfiguration"] === undefined) { + throw new Error('Required parameter "params[\'sinkConfiguration\']" missing.'); + } + + if (params["sinkType"] === null || params["sinkType"] === undefined) { + throw new Error('Required parameter "params[\'sinkType\']" missing.'); + } + + let data: any = {}; + + + + data["Description"] = params["description"]; + + data["SinkConfiguration"] = serialize.object(params["sinkConfiguration"]); + + data["SinkType"] = params["sinkType"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SinkInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SinkListInstancePageOptions | ((error: Error | null, items: SinkPage) => any), callback?: (error: Error | null, items: SinkPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["inUse"] !== undefined) + data["InUse"] = serialize.bool(params["inUse"]); + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SinkPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SinkPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SinkPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SinkListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["inUse"] !== undefined) + data["InUse"] = serialize.bool(params["inUse"]); + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SinkPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SinkPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SinkPage extends Page { +/** +* Initialize the SinkPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: SinkSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SinkInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SinkResource): SinkInstance { + + return new SinkInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/events/v1/sink/sinkTest.ts b/rest/events/v1/sink/sinkTest.ts new file mode 100644 index 000000000..7b99de4d4 --- /dev/null +++ b/rest/events/v1/sink/sinkTest.ts @@ -0,0 +1,155 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Events + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +export interface SinkTestSolution { + sid: string; +} + +export interface SinkTestListInstance { + _version: V1; + _solution: SinkTestSolution; + _uri: string; + + + + /** + * Create a SinkTestInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkTestInstance + */ + create(callback?: (error: Error | null, item?: SinkTestInstance) => any): Promise + + /** + * Create a SinkTestInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkTestInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SinkTestListInstance(version: V1, sid: string): SinkTestListInstance { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + const instance = {} as SinkTestListInstance; + + instance._version = version; + instance._solution = { sid, }; + instance._uri = `/Sinks/${sid}/Test`; + + instance.create = function create( callback?: (error: Error | null, items: SinkTestInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new SinkTestInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo( callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse => ({ + ...response, + body: new SinkTestInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface SinkTestPayload extends SinkTestResource {} + +interface SinkTestResource { + result: string; +} + +export class SinkTestInstance { + + constructor(protected _version: V1, payload: SinkTestResource, sid: string) { + + this.result = (payload.result); + + } + + /** + * Feedback indicating whether the test event was generated. + */ + result: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + result: this.result, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/events/v1/sink/sinkValidate.ts b/rest/events/v1/sink/sinkValidate.ts new file mode 100644 index 000000000..917797b40 --- /dev/null +++ b/rest/events/v1/sink/sinkValidate.ts @@ -0,0 +1,200 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Events + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to create a SinkValidateInstance + */ +export interface SinkValidateListInstanceCreateOptions { + /** A 34 character string that uniquely identifies the test event for a Sink being validated. */ + "testId": string; +} + + +export interface SinkValidateSolution { + sid: string; +} + +export interface SinkValidateListInstance { + _version: V1; + _solution: SinkValidateSolution; + _uri: string; + + + + /** + * Create a SinkValidateInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkValidateInstance + */ + create(params: SinkValidateListInstanceCreateOptions, callback?: (error: Error | null, item?: SinkValidateInstance) => any): Promise; + + /** + * Create a SinkValidateInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SinkValidateInstance with HTTP metadata + */ + createWithHttpInfo(params: SinkValidateListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SinkValidateListInstance(version: V1, sid: string): SinkValidateListInstance { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + const instance = {} as SinkValidateListInstance; + + instance._version = version; + instance._solution = { sid, }; + instance._uri = `/Sinks/${sid}/Validate`; + + instance.create = function create(params: SinkValidateListInstanceCreateOptions, callback?: (error: Error | null, items: SinkValidateInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["testId"] === null || params["testId"] === undefined) { + throw new Error('Required parameter "params[\'testId\']" missing.'); + } + + let data: any = {}; + + + + data["TestId"] = params["testId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SinkValidateInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SinkValidateListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["testId"] === null || params["testId"] === undefined) { + throw new Error('Required parameter "params[\'testId\']" missing.'); + } + + let data: any = {}; + + + + data["TestId"] = params["testId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SinkValidateInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface SinkValidatePayload extends SinkValidateResource {} + +interface SinkValidateResource { + result: string; +} + +export class SinkValidateInstance { + + constructor(protected _version: V1, payload: SinkValidateResource, sid: string) { + + this.result = (payload.result); + + } + + /** + * Feedback indicating whether the given Sink was validated. + */ + result: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + result: this.result, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/events/v1/subscription.ts b/rest/events/v1/subscription.ts new file mode 100644 index 000000000..4b312e946 --- /dev/null +++ b/rest/events/v1/subscription.ts @@ -0,0 +1,956 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Events + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { SubscribedEventListInstance } from "./subscription/subscribedEvent"; + + + + + +/** + * Options to pass to update a SubscriptionInstance + */ +export interface SubscriptionContextUpdateOptions { + /** A human readable description for the Subscription. */ + "description"?: string; +} + +/** + * Options to pass to create a SubscriptionInstance + */ +export interface SubscriptionListInstanceCreateOptions { + /** A human readable description for the Subscription **This value should not contain PII.** */ + "description": string; + /** The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. */ + "sinkSid": string; + /** An array of objects containing the subscribed Event Types */ + "types": Array; +} + +/** + * Options to pass to each + */ +export interface SubscriptionListInstanceEachOptions { + /** The SID of the sink that the list of Subscriptions should be filtered by. */ + "sinkSid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SubscriptionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SubscriptionListInstanceOptions { + /** The SID of the sink that the list of Subscriptions should be filtered by. */ + "sinkSid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SubscriptionListInstancePageOptions { + /** The SID of the sink that the list of Subscriptions should be filtered by. */ + "sinkSid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SubscriptionContext { + subscribedEvents: SubscribedEventListInstance; + + /** + * Remove a SubscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a SubscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a SubscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance + */ + fetch(callback?: (error: Error | null, item?: SubscriptionInstance) => any): Promise + + /** + * Fetch a SubscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a SubscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance + */ + update(callback?: (error: Error | null, item?: SubscriptionInstance) => any): Promise; + /** + * Update a SubscriptionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance + */ + update(params: SubscriptionContextUpdateOptions, callback?: (error: Error | null, item?: SubscriptionInstance) => any): Promise; + + /** + * Update a SubscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a SubscriptionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance with HTTP metadata + */ + updateWithHttpInfo(params: SubscriptionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SubscriptionContextSolution { + "sid": string; +} + +export class SubscriptionContextImpl implements SubscriptionContext { + protected _solution: SubscriptionContextSolution; + protected _uri: string; + + protected _subscribedEvents?: SubscribedEventListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Subscriptions/${sid}`; + } + + get subscribedEvents(): SubscribedEventListInstance { + this._subscribedEvents = this._subscribedEvents || SubscribedEventListInstance(this._version, this._solution.sid); + return this._subscribedEvents; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SubscriptionInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SubscriptionInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new SubscriptionInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SubscriptionContextUpdateOptions | ((error: Error | null, item?: SubscriptionInstance) => any),callback?: (error: Error | null, item?: SubscriptionInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SubscriptionInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SubscriptionContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SubscriptionInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SubscriptionPayload extends TwilioResponsePayload { + subscriptions: SubscriptionResource[]; +} + +interface SubscriptionResource { + account_sid: string; + sid: string; + date_created: Date; + date_updated: Date; + description: string; + sink_sid: string; + url: string; + links: Record; +} + +export class SubscriptionInstance { + protected _solution: SubscriptionContextSolution; + protected _context?: SubscriptionContext; + + constructor(protected _version: V1, payload: SubscriptionResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.description = (payload.description); + this.sinkSid = (payload.sink_sid); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * A 34 character string that uniquely identifies this Subscription. + */ + sid: string; + /** + * The date that this Subscription was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Subscription was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * A human readable description for the Subscription + */ + description: string; + /** + * The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + */ + sinkSid: string; + /** + * The URL of this resource. + */ + url: string; + /** + * Contains a dictionary of URL links to nested resources of this Subscription. + */ + links: Record; + + private get _proxy(): SubscriptionContext { + this._context = this._context || new SubscriptionContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a SubscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SubscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SubscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance + */ + fetch(callback?: (error: Error | null, item?: SubscriptionInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SubscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SubscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance + */ + update(callback?: (error: Error | null, item?: SubscriptionInstance) => any): Promise; + /** + * Update a SubscriptionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance + */ + update(params: SubscriptionContextUpdateOptions, callback?: (error: Error | null, item?: SubscriptionInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: SubscriptionInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a SubscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a SubscriptionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance with HTTP metadata + */ + updateWithHttpInfo(params: SubscriptionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the subscribedEvents. + */ + subscribedEvents(): SubscribedEventListInstance { + return this._proxy.subscribedEvents; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + description: this.description, + sinkSid: this.sinkSid, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SubscriptionSolution { +} + +export interface SubscriptionListInstance { + _version: V1; + _solution: SubscriptionSolution; + _uri: string; + + (sid: string, ): SubscriptionContext; + get(sid: string, ): SubscriptionContext; + + + + + + + + + /** + * Create a SubscriptionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance + */ + create(params: SubscriptionListInstanceCreateOptions, callback?: (error: Error | null, item?: SubscriptionInstance) => any): Promise; + + /** + * Create a SubscriptionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscriptionInstance with HTTP metadata + */ + createWithHttpInfo(params: SubscriptionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams SubscriptionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscriptionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SubscriptionInstance, done: (err?: Error) => void) => void): void; + each(params: SubscriptionListInstanceEachOptions, callback?: (item: SubscriptionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SubscriptionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscriptionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SubscriptionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SubscriptionListInstanceEachOptions, callback?: (item: SubscriptionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SubscriptionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SubscriptionPage) => any): Promise; + /** + * Retrieve a single target page of SubscriptionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists SubscriptionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscriptionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SubscriptionInstance[]) => any): Promise; + list(params: SubscriptionListInstanceOptions, callback?: (error: Error | null, items: SubscriptionInstance[]) => any): Promise; + /** + * Lists SubscriptionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscriptionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: SubscriptionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of SubscriptionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscriptionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SubscriptionPage) => any): Promise; + page(params: SubscriptionListInstancePageOptions, callback?: (error: Error | null, items: SubscriptionPage) => any): Promise; + /** + * Retrieve a single page of SubscriptionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscriptionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: SubscriptionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SubscriptionListInstance(version: V1): SubscriptionListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SubscriptionListInstance; + + instance.get = function get(sid, ): SubscriptionContext { + return new SubscriptionContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Subscriptions`; + + instance.create = function create(params: SubscriptionListInstanceCreateOptions, callback?: (error: Error | null, items: SubscriptionInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["description"] === null || params["description"] === undefined) { + throw new Error('Required parameter "params[\'description\']" missing.'); + } + + if (params["sinkSid"] === null || params["sinkSid"] === undefined) { + throw new Error('Required parameter "params[\'sinkSid\']" missing.'); + } + + if (params["types"] === null || params["types"] === undefined) { + throw new Error('Required parameter "params[\'types\']" missing.'); + } + + let data: any = {}; + + + + data["Description"] = params["description"]; + + data["SinkSid"] = params["sinkSid"]; + + data["Types"] = serialize.map(params["types"], (e: any) => serialize.object(e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SubscriptionInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SubscriptionListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["description"] === null || params["description"] === undefined) { + throw new Error('Required parameter "params[\'description\']" missing.'); + } + + if (params["sinkSid"] === null || params["sinkSid"] === undefined) { + throw new Error('Required parameter "params[\'sinkSid\']" missing.'); + } + + if (params["types"] === null || params["types"] === undefined) { + throw new Error('Required parameter "params[\'types\']" missing.'); + } + + let data: any = {}; + + + + data["Description"] = params["description"]; + + data["SinkSid"] = params["sinkSid"]; + + data["Types"] = serialize.map(params["types"], (e: any) => serialize.object(e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SubscriptionInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SubscriptionListInstancePageOptions | ((error: Error | null, items: SubscriptionPage) => any), callback?: (error: Error | null, items: SubscriptionPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sinkSid"] !== undefined) + data["SinkSid"] = params["sinkSid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SubscriptionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SubscriptionPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SubscriptionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SubscriptionListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sinkSid"] !== undefined) + data["SinkSid"] = params["sinkSid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SubscriptionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SubscriptionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SubscriptionPage extends Page { +/** +* Initialize the SubscriptionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: SubscriptionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SubscriptionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SubscriptionResource): SubscriptionInstance { + + return new SubscriptionInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/events/v1/subscription/subscribedEvent.ts b/rest/events/v1/subscription/subscribedEvent.ts new file mode 100644 index 000000000..b1417c7fc --- /dev/null +++ b/rest/events/v1/subscription/subscribedEvent.ts @@ -0,0 +1,899 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Events + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a SubscribedEventInstance + */ +export interface SubscribedEventContextUpdateOptions { + /** The schema version that the Subscription should use. */ + "schemaVersion"?: number; +} + +/** + * Options to pass to create a SubscribedEventInstance + */ +export interface SubscribedEventListInstanceCreateOptions { + /** Type of event being subscribed to. */ + "type": string; + /** The schema version that the Subscription should use. */ + "schemaVersion"?: number; +} + +/** + * Options to pass to each + */ +export interface SubscribedEventListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SubscribedEventInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SubscribedEventListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SubscribedEventListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SubscribedEventContext { + + /** + * Remove a SubscribedEventInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a SubscribedEventInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a SubscribedEventInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance + */ + fetch(callback?: (error: Error | null, item?: SubscribedEventInstance) => any): Promise + + /** + * Fetch a SubscribedEventInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a SubscribedEventInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance + */ + update(callback?: (error: Error | null, item?: SubscribedEventInstance) => any): Promise; + /** + * Update a SubscribedEventInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance + */ + update(params: SubscribedEventContextUpdateOptions, callback?: (error: Error | null, item?: SubscribedEventInstance) => any): Promise; + + /** + * Update a SubscribedEventInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a SubscribedEventInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance with HTTP metadata + */ + updateWithHttpInfo(params: SubscribedEventContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SubscribedEventContextSolution { + "subscriptionSid": string; + "type": string; +} + +export class SubscribedEventContextImpl implements SubscribedEventContext { + protected _solution: SubscribedEventContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, subscriptionSid: string, type: string) { + if (!isValidPathParam(subscriptionSid)) { + throw new Error('Parameter \'subscriptionSid\' is not valid.'); + } + + if (!isValidPathParam(type)) { + throw new Error('Parameter \'type\' is not valid.'); + } + + this._solution = { subscriptionSid, type, }; + this._uri = `/Subscriptions/${subscriptionSid}/SubscribedEvents/${type}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SubscribedEventInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SubscribedEventInstance(operationVersion, payload, instance._solution.subscriptionSid, instance._solution.type)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new SubscribedEventInstance(operationVersion, response.body, instance._solution.subscriptionSid, instance._solution.type) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SubscribedEventContextUpdateOptions | ((error: Error | null, item?: SubscribedEventInstance) => any),callback?: (error: Error | null, item?: SubscribedEventInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["schemaVersion"] !== undefined) + data["SchemaVersion"] = params["schemaVersion"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SubscribedEventInstance(operationVersion, payload, instance._solution.subscriptionSid, instance._solution.type)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SubscribedEventContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["schemaVersion"] !== undefined) + data["SchemaVersion"] = params["schemaVersion"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SubscribedEventInstance(operationVersion, response.body, instance._solution.subscriptionSid, instance._solution.type) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SubscribedEventPayload extends TwilioResponsePayload { + types: SubscribedEventResource[]; +} + +interface SubscribedEventResource { + account_sid: string; + type: string; + schema_version: number; + subscription_sid: string; + url: string; +} + +export class SubscribedEventInstance { + protected _solution: SubscribedEventContextSolution; + protected _context?: SubscribedEventContext; + + constructor(protected _version: V1, payload: SubscribedEventResource, subscriptionSid: string, type?: string) { + + this.accountSid = (payload.account_sid); + this.type = (payload.type); + this.schemaVersion = deserialize.integer(payload.schema_version); + this.subscriptionSid = (payload.subscription_sid); + this.url = (payload.url); + + this._solution = { subscriptionSid, type: type, }; + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * Type of event being subscribed to. + */ + type: string; + /** + * The schema version that the Subscription should use. + */ + schemaVersion: number; + /** + * The unique SID identifier of the Subscription. + */ + subscriptionSid: string; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): SubscribedEventContext { + this._context = this._context || new SubscribedEventContextImpl(this._version, this._solution.subscriptionSid, this._solution.type); + return this._context; + } + + /** + * Remove a SubscribedEventInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SubscribedEventInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SubscribedEventInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance + */ + fetch(callback?: (error: Error | null, item?: SubscribedEventInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SubscribedEventInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SubscribedEventInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance + */ + update(callback?: (error: Error | null, item?: SubscribedEventInstance) => any): Promise; + /** + * Update a SubscribedEventInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance + */ + update(params: SubscribedEventContextUpdateOptions, callback?: (error: Error | null, item?: SubscribedEventInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: SubscribedEventInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a SubscribedEventInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a SubscribedEventInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance with HTTP metadata + */ + updateWithHttpInfo(params: SubscribedEventContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + type: this.type, + schemaVersion: this.schemaVersion, + subscriptionSid: this.subscriptionSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SubscribedEventSolution { + subscriptionSid: string; +} + +export interface SubscribedEventListInstance { + _version: V1; + _solution: SubscribedEventSolution; + _uri: string; + + (type: string, ): SubscribedEventContext; + get(type: string, ): SubscribedEventContext; + + + + + + + + + /** + * Create a SubscribedEventInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance + */ + create(params: SubscribedEventListInstanceCreateOptions, callback?: (error: Error | null, item?: SubscribedEventInstance) => any): Promise; + + /** + * Create a SubscribedEventInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedEventInstance with HTTP metadata + */ + createWithHttpInfo(params: SubscribedEventListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams SubscribedEventInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedEventListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SubscribedEventInstance, done: (err?: Error) => void) => void): void; + each(params: SubscribedEventListInstanceEachOptions, callback?: (item: SubscribedEventInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SubscribedEventInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedEventListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SubscribedEventInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SubscribedEventListInstanceEachOptions, callback?: (item: SubscribedEventInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SubscribedEventInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SubscribedEventPage) => any): Promise; + /** + * Retrieve a single target page of SubscribedEventInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists SubscribedEventInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedEventListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SubscribedEventInstance[]) => any): Promise; + list(params: SubscribedEventListInstanceOptions, callback?: (error: Error | null, items: SubscribedEventInstance[]) => any): Promise; + /** + * Lists SubscribedEventInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedEventListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: SubscribedEventListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of SubscribedEventInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedEventListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SubscribedEventPage) => any): Promise; + page(params: SubscribedEventListInstancePageOptions, callback?: (error: Error | null, items: SubscribedEventPage) => any): Promise; + /** + * Retrieve a single page of SubscribedEventInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedEventListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: SubscribedEventListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SubscribedEventListInstance(version: V1, subscriptionSid: string): SubscribedEventListInstance { + if (!isValidPathParam(subscriptionSid)) { + throw new Error('Parameter \'subscriptionSid\' is not valid.'); + } + + const instance = ((type, ) => instance.get(type, )) as SubscribedEventListInstance; + + instance.get = function get(type, ): SubscribedEventContext { + return new SubscribedEventContextImpl(version, subscriptionSid, type); + } + + instance._version = version; + instance._solution = { subscriptionSid, }; + instance._uri = `/Subscriptions/${subscriptionSid}/SubscribedEvents`; + + instance.create = function create(params: SubscribedEventListInstanceCreateOptions, callback?: (error: Error | null, items: SubscribedEventInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["schemaVersion"] !== undefined) + data["SchemaVersion"] = params["schemaVersion"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SubscribedEventInstance(operationVersion, payload, instance._solution.subscriptionSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SubscribedEventListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["schemaVersion"] !== undefined) + data["SchemaVersion"] = params["schemaVersion"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SubscribedEventInstance(operationVersion, response.body, instance._solution.subscriptionSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SubscribedEventListInstancePageOptions | ((error: Error | null, items: SubscribedEventPage) => any), callback?: (error: Error | null, items: SubscribedEventPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SubscribedEventPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SubscribedEventPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SubscribedEventPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SubscribedEventListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SubscribedEventPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SubscribedEventPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SubscribedEventPage extends Page { +/** +* Initialize the SubscribedEventPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: SubscribedEventSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SubscribedEventInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SubscribedEventResource): SubscribedEventInstance { + + return new SubscribedEventInstance( + this._version, + payload, + this._solution.subscriptionSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/V1.ts b/rest/flexApi/V1.ts new file mode 100644 index 000000000..fbd2f151d --- /dev/null +++ b/rest/flexApi/V1.ts @@ -0,0 +1,236 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import FlexApiBase from "../FlexApiBase"; +import Version from "../../base/Version"; +import { AssessmentsListInstance } from "./v1/assessments"; +import { ChannelListInstance } from "./v1/channel"; +import { ConfigurationListInstance } from "./v1/configuration"; +import { FlexFlowListInstance } from "./v1/flexFlow"; +import { InsightsAssessmentsCommentListInstance } from "./v1/insightsAssessmentsComment"; +import { InsightsConversationsListInstance } from "./v1/insightsConversations"; +import { InsightsQuestionnairesListInstance } from "./v1/insightsQuestionnaires"; +import { InsightsQuestionnairesCategoryListInstance } from "./v1/insightsQuestionnairesCategory"; +import { InsightsQuestionnairesQuestionListInstance } from "./v1/insightsQuestionnairesQuestion"; +import { InsightsSegmentsListInstance } from "./v1/insightsSegments"; +import { InsightsSessionListInstance } from "./v1/insightsSession"; +import { InsightsSettingsAnswerSetsListInstance } from "./v1/insightsSettingsAnswerSets"; +import { InsightsSettingsCommentListInstance } from "./v1/insightsSettingsComment"; +import { InsightsUserRolesListInstance } from "./v1/insightsUserRoles"; +import { InteractionListInstance } from "./v1/interaction"; +import { PluginListInstance } from "./v1/plugin"; +import { PluginArchiveListInstance } from "./v1/pluginArchive"; +import { PluginConfigurationListInstance } from "./v1/pluginConfiguration"; +import { PluginConfigurationArchiveListInstance } from "./v1/pluginConfigurationArchive"; +import { PluginReleaseListInstance } from "./v1/pluginRelease"; +import { PluginVersionArchiveListInstance } from "./v1/pluginVersionArchive"; +import { ProvisioningStatusListInstance } from "./v1/provisioningStatus"; +import { WebChannelListInstance } from "./v1/webChannel"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of FlexApi + * + * @param domain - The Twilio (Twilio.FlexApi) domain + */ + constructor(domain: FlexApiBase) { + super(domain, "v1"); + } + + /** assessments - { Twilio.FlexApi.V1.AssessmentsListInstance } resource */ + protected _assessments?: AssessmentsListInstance; + /** channel - { Twilio.FlexApi.V1.ChannelListInstance } resource */ + protected _channel?: ChannelListInstance; + /** configuration - { Twilio.FlexApi.V1.ConfigurationListInstance } resource */ + protected _configuration?: ConfigurationListInstance; + /** flexFlow - { Twilio.FlexApi.V1.FlexFlowListInstance } resource */ + protected _flexFlow?: FlexFlowListInstance; + /** insightsAssessmentsComment - { Twilio.FlexApi.V1.InsightsAssessmentsCommentListInstance } resource */ + protected _insightsAssessmentsComment?: InsightsAssessmentsCommentListInstance; + /** insightsConversations - { Twilio.FlexApi.V1.InsightsConversationsListInstance } resource */ + protected _insightsConversations?: InsightsConversationsListInstance; + /** insightsQuestionnaires - { Twilio.FlexApi.V1.InsightsQuestionnairesListInstance } resource */ + protected _insightsQuestionnaires?: InsightsQuestionnairesListInstance; + /** insightsQuestionnairesCategory - { Twilio.FlexApi.V1.InsightsQuestionnairesCategoryListInstance } resource */ + protected _insightsQuestionnairesCategory?: InsightsQuestionnairesCategoryListInstance; + /** insightsQuestionnairesQuestion - { Twilio.FlexApi.V1.InsightsQuestionnairesQuestionListInstance } resource */ + protected _insightsQuestionnairesQuestion?: InsightsQuestionnairesQuestionListInstance; + /** insightsSegments - { Twilio.FlexApi.V1.InsightsSegmentsListInstance } resource */ + protected _insightsSegments?: InsightsSegmentsListInstance; + /** insightsSession - { Twilio.FlexApi.V1.InsightsSessionListInstance } resource */ + protected _insightsSession?: InsightsSessionListInstance; + /** insightsSettingsAnswerSets - { Twilio.FlexApi.V1.InsightsSettingsAnswerSetsListInstance } resource */ + protected _insightsSettingsAnswerSets?: InsightsSettingsAnswerSetsListInstance; + /** insightsSettingsComment - { Twilio.FlexApi.V1.InsightsSettingsCommentListInstance } resource */ + protected _insightsSettingsComment?: InsightsSettingsCommentListInstance; + /** insightsUserRoles - { Twilio.FlexApi.V1.InsightsUserRolesListInstance } resource */ + protected _insightsUserRoles?: InsightsUserRolesListInstance; + /** interaction - { Twilio.FlexApi.V1.InteractionListInstance } resource */ + protected _interaction?: InteractionListInstance; + /** plugins - { Twilio.FlexApi.V1.PluginListInstance } resource */ + protected _plugins?: PluginListInstance; + /** pluginArchive - { Twilio.FlexApi.V1.PluginArchiveListInstance } resource */ + protected _pluginArchive?: PluginArchiveListInstance; + /** pluginConfigurations - { Twilio.FlexApi.V1.PluginConfigurationListInstance } resource */ + protected _pluginConfigurations?: PluginConfigurationListInstance; + /** pluginConfigurationArchive - { Twilio.FlexApi.V1.PluginConfigurationArchiveListInstance } resource */ + protected _pluginConfigurationArchive?: PluginConfigurationArchiveListInstance; + /** pluginReleases - { Twilio.FlexApi.V1.PluginReleaseListInstance } resource */ + protected _pluginReleases?: PluginReleaseListInstance; + /** pluginVersionArchive - { Twilio.FlexApi.V1.PluginVersionArchiveListInstance } resource */ + protected _pluginVersionArchive?: PluginVersionArchiveListInstance; + /** provisioningStatus - { Twilio.FlexApi.V1.ProvisioningStatusListInstance } resource */ + protected _provisioningStatus?: ProvisioningStatusListInstance; + /** webChannel - { Twilio.FlexApi.V1.WebChannelListInstance } resource */ + protected _webChannel?: WebChannelListInstance; + + /** Getter for assessments resource */ + get assessments(): AssessmentsListInstance { + this._assessments = this._assessments || AssessmentsListInstance(this); + return this._assessments; + } + + /** Getter for channel resource */ + get channel(): ChannelListInstance { + this._channel = this._channel || ChannelListInstance(this); + return this._channel; + } + + /** Getter for configuration resource */ + get configuration(): ConfigurationListInstance { + this._configuration = this._configuration || ConfigurationListInstance(this); + return this._configuration; + } + + /** Getter for flexFlow resource */ + get flexFlow(): FlexFlowListInstance { + this._flexFlow = this._flexFlow || FlexFlowListInstance(this); + return this._flexFlow; + } + + /** Getter for insightsAssessmentsComment resource */ + get insightsAssessmentsComment(): InsightsAssessmentsCommentListInstance { + this._insightsAssessmentsComment = this._insightsAssessmentsComment || InsightsAssessmentsCommentListInstance(this); + return this._insightsAssessmentsComment; + } + + /** Getter for insightsConversations resource */ + get insightsConversations(): InsightsConversationsListInstance { + this._insightsConversations = this._insightsConversations || InsightsConversationsListInstance(this); + return this._insightsConversations; + } + + /** Getter for insightsQuestionnaires resource */ + get insightsQuestionnaires(): InsightsQuestionnairesListInstance { + this._insightsQuestionnaires = this._insightsQuestionnaires || InsightsQuestionnairesListInstance(this); + return this._insightsQuestionnaires; + } + + /** Getter for insightsQuestionnairesCategory resource */ + get insightsQuestionnairesCategory(): InsightsQuestionnairesCategoryListInstance { + this._insightsQuestionnairesCategory = this._insightsQuestionnairesCategory || InsightsQuestionnairesCategoryListInstance(this); + return this._insightsQuestionnairesCategory; + } + + /** Getter for insightsQuestionnairesQuestion resource */ + get insightsQuestionnairesQuestion(): InsightsQuestionnairesQuestionListInstance { + this._insightsQuestionnairesQuestion = this._insightsQuestionnairesQuestion || InsightsQuestionnairesQuestionListInstance(this); + return this._insightsQuestionnairesQuestion; + } + + /** Getter for insightsSegments resource */ + get insightsSegments(): InsightsSegmentsListInstance { + this._insightsSegments = this._insightsSegments || InsightsSegmentsListInstance(this); + return this._insightsSegments; + } + + /** Getter for insightsSession resource */ + get insightsSession(): InsightsSessionListInstance { + this._insightsSession = this._insightsSession || InsightsSessionListInstance(this); + return this._insightsSession; + } + + /** Getter for insightsSettingsAnswerSets resource */ + get insightsSettingsAnswerSets(): InsightsSettingsAnswerSetsListInstance { + this._insightsSettingsAnswerSets = this._insightsSettingsAnswerSets || InsightsSettingsAnswerSetsListInstance(this); + return this._insightsSettingsAnswerSets; + } + + /** Getter for insightsSettingsComment resource */ + get insightsSettingsComment(): InsightsSettingsCommentListInstance { + this._insightsSettingsComment = this._insightsSettingsComment || InsightsSettingsCommentListInstance(this); + return this._insightsSettingsComment; + } + + /** Getter for insightsUserRoles resource */ + get insightsUserRoles(): InsightsUserRolesListInstance { + this._insightsUserRoles = this._insightsUserRoles || InsightsUserRolesListInstance(this); + return this._insightsUserRoles; + } + + /** Getter for interaction resource */ + get interaction(): InteractionListInstance { + this._interaction = this._interaction || InteractionListInstance(this); + return this._interaction; + } + + /** Getter for plugins resource */ + get plugins(): PluginListInstance { + this._plugins = this._plugins || PluginListInstance(this); + return this._plugins; + } + + /** Getter for pluginArchive resource */ + get pluginArchive(): PluginArchiveListInstance { + this._pluginArchive = this._pluginArchive || PluginArchiveListInstance(this); + return this._pluginArchive; + } + + /** Getter for pluginConfigurations resource */ + get pluginConfigurations(): PluginConfigurationListInstance { + this._pluginConfigurations = this._pluginConfigurations || PluginConfigurationListInstance(this); + return this._pluginConfigurations; + } + + /** Getter for pluginConfigurationArchive resource */ + get pluginConfigurationArchive(): PluginConfigurationArchiveListInstance { + this._pluginConfigurationArchive = this._pluginConfigurationArchive || PluginConfigurationArchiveListInstance(this); + return this._pluginConfigurationArchive; + } + + /** Getter for pluginReleases resource */ + get pluginReleases(): PluginReleaseListInstance { + this._pluginReleases = this._pluginReleases || PluginReleaseListInstance(this); + return this._pluginReleases; + } + + /** Getter for pluginVersionArchive resource */ + get pluginVersionArchive(): PluginVersionArchiveListInstance { + this._pluginVersionArchive = this._pluginVersionArchive || PluginVersionArchiveListInstance(this); + return this._pluginVersionArchive; + } + + /** Getter for provisioningStatus resource */ + get provisioningStatus(): ProvisioningStatusListInstance { + this._provisioningStatus = this._provisioningStatus || ProvisioningStatusListInstance(this); + return this._provisioningStatus; + } + + /** Getter for webChannel resource */ + get webChannel(): WebChannelListInstance { + this._webChannel = this._webChannel || WebChannelListInstance(this); + return this._webChannel; + } + +} diff --git a/rest/flexApi/V2.ts b/rest/flexApi/V2.ts new file mode 100644 index 000000000..2524e48a9 --- /dev/null +++ b/rest/flexApi/V2.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import FlexApiBase from "../FlexApiBase"; +import Version from "../../base/Version"; +import { FlexUserListInstance } from "./v2/flexUser"; +import { WebChannelsListInstance } from "./v2/webChannels"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of FlexApi + * + * @param domain - The Twilio (Twilio.FlexApi) domain + */ + constructor(domain: FlexApiBase) { + super(domain, "v2"); + } + + /** flexUser - { Twilio.FlexApi.V2.FlexUserListInstance } resource */ + protected _flexUser?: FlexUserListInstance; + /** webChannels - { Twilio.FlexApi.V2.WebChannelsListInstance } resource */ + protected _webChannels?: WebChannelsListInstance; + + /** Getter for flexUser resource */ + get flexUser(): FlexUserListInstance { + this._flexUser = this._flexUser || FlexUserListInstance(this); + return this._flexUser; + } + + /** Getter for webChannels resource */ + get webChannels(): WebChannelsListInstance { + this._webChannels = this._webChannels || WebChannelsListInstance(this); + return this._webChannels; + } + +} diff --git a/rest/flexApi/v1/assessments.ts b/rest/flexApi/v1/assessments.ts new file mode 100644 index 000000000..fb5b9e2b9 --- /dev/null +++ b/rest/flexApi/v1/assessments.ts @@ -0,0 +1,929 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to update a AssessmentsInstance + */ +export interface AssessmentsContextUpdateOptions { + /** The offset of the conversation */ + "offset": number; + /** The answer text selected by user */ + "answerText": string; + /** The id of the answer selected by user */ + "answerId": string; + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +/** + * Options to pass to create a AssessmentsInstance + */ +export interface AssessmentsListInstanceCreateOptions { + /** The SID of the category */ + "categorySid": string; + /** The name of the category */ + "categoryName": string; + /** Segment Id of the conversation */ + "segmentId": string; + /** The id of the Agent */ + "agentId": string; + /** The offset of the conversation. */ + "offset": number; + /** The question SID selected for assessment */ + "metricId": string; + /** The question name of the assessment */ + "metricName": string; + /** The answer text selected by user */ + "answerText": string; + /** The id of the answer selected by user */ + "answerId": string; + /** Questionnaire SID of the associated question */ + "questionnaireSid": string; + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +/** + * Options to pass to each + */ +export interface AssessmentsListInstanceEachOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The id of the segment. */ + "segmentId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AssessmentsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AssessmentsListInstanceOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The id of the segment. */ + "segmentId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AssessmentsListInstancePageOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The id of the segment. */ + "segmentId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AssessmentsContext { + + /** + * Update a AssessmentsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssessmentsInstance + */ + update(params: AssessmentsContextUpdateOptions, callback?: (error: Error | null, item?: AssessmentsInstance) => any): Promise; + + /** + * Update a AssessmentsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssessmentsInstance with HTTP metadata + */ + updateWithHttpInfo(params: AssessmentsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AssessmentsContextSolution { + "assessmentSid": string; +} + +export class AssessmentsContextImpl implements AssessmentsContext { + protected _solution: AssessmentsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, assessmentSid: string) { + if (!isValidPathParam(assessmentSid)) { + throw new Error('Parameter \'assessmentSid\' is not valid.'); + } + + this._solution = { assessmentSid, }; + this._uri = `/Insights/QualityManagement/Assessments/${assessmentSid}`; + } + + update(params: AssessmentsContextUpdateOptions,callback?: (error: Error | null, item?: AssessmentsInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["offset"] === null || params["offset"] === undefined) { + throw new Error('Required parameter "params[\'offset\']" missing.'); + } + + if (params["answerText"] === null || params["answerText"] === undefined) { + throw new Error('Required parameter "params[\'answerText\']" missing.'); + } + + if (params["answerId"] === null || params["answerId"] === undefined) { + throw new Error('Required parameter "params[\'answerId\']" missing.'); + } + + let data: any = {}; + + + + data["Offset"] = params["offset"]; + + data["AnswerText"] = params["answerText"]; + + data["AnswerId"] = params["answerId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AssessmentsInstance(operationVersion, payload, instance._solution.assessmentSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: AssessmentsContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["offset"] === null || params["offset"] === undefined) { + throw new Error('Required parameter "params[\'offset\']" missing.'); + } + + if (params["answerText"] === null || params["answerText"] === undefined) { + throw new Error('Required parameter "params[\'answerText\']" missing.'); + } + + if (params["answerId"] === null || params["answerId"] === undefined) { + throw new Error('Required parameter "params[\'answerId\']" missing.'); + } + + let data: any = {}; + + + + data["Offset"] = params["offset"]; + + data["AnswerText"] = params["answerText"]; + + data["AnswerId"] = params["answerId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AssessmentsInstance(operationVersion, response.body, instance._solution.assessmentSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AssessmentsPayload extends TwilioResponsePayload { + assessments: AssessmentsResource[]; +} + +interface AssessmentsResource { + account_sid: string; + assessment_sid: string; + offset: string; + report: boolean; + weight: string; + agent_id: string; + segment_id: string; + user_name: string; + user_email: string; + answer_text: string; + answer_id: string; + assessment: any; + timestamp: string; + url: string; +} + +export class AssessmentsInstance { + protected _solution: AssessmentsContextSolution; + protected _context?: AssessmentsContext; + + constructor(protected _version: V1, payload: AssessmentsResource, assessmentSid?: string) { + + this.accountSid = (payload.account_sid); + this.assessmentSid = (payload.assessment_sid); + this.offset = (payload.offset); + this.report = (payload.report); + this.weight = (payload.weight); + this.agentId = (payload.agent_id); + this.segmentId = (payload.segment_id); + this.userName = (payload.user_name); + this.userEmail = (payload.user_email); + this.answerText = (payload.answer_text); + this.answerId = (payload.answer_id); + this.assessment = (payload.assessment); + this.timestamp = (payload.timestamp); + this.url = (payload.url); + + this._solution = { assessmentSid: assessmentSid, }; + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The SID of the assessment + */ + assessmentSid: string; + /** + * Offset of the conversation + */ + offset: string; + /** + * The flag indicating if this assessment is part of report + */ + report: boolean; + /** + * The weightage given to this comment + */ + weight: string; + /** + * The id of the Agent + */ + agentId: string; + /** + * Segment Id of conversation + */ + segmentId: string; + /** + * The name of the user. + */ + userName: string; + /** + * The email id of the user. + */ + userEmail: string; + /** + * The answer text selected by user + */ + answerText: string; + /** + * The id of the answer selected by user + */ + answerId: string; + /** + * Assessment Details associated with an assessment + */ + assessment: any; + timestamp: string; + url: string; + + private get _proxy(): AssessmentsContext { + this._context = this._context || new AssessmentsContextImpl(this._version, this._solution.assessmentSid); + return this._context; + } + + /** + * Update a AssessmentsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssessmentsInstance + */ + update(params: AssessmentsContextUpdateOptions, callback?: (error: Error | null, item?: AssessmentsInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: AssessmentsInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a AssessmentsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssessmentsInstance with HTTP metadata + */ + updateWithHttpInfo(params: AssessmentsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + assessmentSid: this.assessmentSid, + offset: this.offset, + report: this.report, + weight: this.weight, + agentId: this.agentId, + segmentId: this.segmentId, + userName: this.userName, + userEmail: this.userEmail, + answerText: this.answerText, + answerId: this.answerId, + assessment: this.assessment, + timestamp: this.timestamp, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AssessmentsSolution { +} + +export interface AssessmentsListInstance { + _version: V1; + _solution: AssessmentsSolution; + _uri: string; + + (assessmentSid: string, ): AssessmentsContext; + get(assessmentSid: string, ): AssessmentsContext; + + + + + /** + * Create a AssessmentsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssessmentsInstance + */ + create(params: AssessmentsListInstanceCreateOptions, callback?: (error: Error | null, item?: AssessmentsInstance) => any): Promise; + + /** + * Create a AssessmentsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssessmentsInstance with HTTP metadata + */ + createWithHttpInfo(params: AssessmentsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams AssessmentsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssessmentsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AssessmentsInstance, done: (err?: Error) => void) => void): void; + each(params: AssessmentsListInstanceEachOptions, callback?: (item: AssessmentsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AssessmentsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssessmentsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AssessmentsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AssessmentsListInstanceEachOptions, callback?: (item: AssessmentsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AssessmentsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AssessmentsPage) => any): Promise; + /** + * Retrieve a single target page of AssessmentsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists AssessmentsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssessmentsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AssessmentsInstance[]) => any): Promise; + list(params: AssessmentsListInstanceOptions, callback?: (error: Error | null, items: AssessmentsInstance[]) => any): Promise; + /** + * Lists AssessmentsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssessmentsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: AssessmentsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of AssessmentsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssessmentsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AssessmentsPage) => any): Promise; + page(params: AssessmentsListInstancePageOptions, callback?: (error: Error | null, items: AssessmentsPage) => any): Promise; + /** + * Retrieve a single page of AssessmentsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssessmentsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: AssessmentsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AssessmentsListInstance(version: V1): AssessmentsListInstance { + const instance = ((assessmentSid, ) => instance.get(assessmentSid, )) as AssessmentsListInstance; + + instance.get = function get(assessmentSid, ): AssessmentsContext { + return new AssessmentsContextImpl(version, assessmentSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Insights/QualityManagement/Assessments`; + + instance.create = function create(params: AssessmentsListInstanceCreateOptions, callback?: (error: Error | null, items: AssessmentsInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["categorySid"] === null || params["categorySid"] === undefined) { + throw new Error('Required parameter "params[\'categorySid\']" missing.'); + } + + if (params["categoryName"] === null || params["categoryName"] === undefined) { + throw new Error('Required parameter "params[\'categoryName\']" missing.'); + } + + if (params["segmentId"] === null || params["segmentId"] === undefined) { + throw new Error('Required parameter "params[\'segmentId\']" missing.'); + } + + if (params["agentId"] === null || params["agentId"] === undefined) { + throw new Error('Required parameter "params[\'agentId\']" missing.'); + } + + if (params["offset"] === null || params["offset"] === undefined) { + throw new Error('Required parameter "params[\'offset\']" missing.'); + } + + if (params["metricId"] === null || params["metricId"] === undefined) { + throw new Error('Required parameter "params[\'metricId\']" missing.'); + } + + if (params["metricName"] === null || params["metricName"] === undefined) { + throw new Error('Required parameter "params[\'metricName\']" missing.'); + } + + if (params["answerText"] === null || params["answerText"] === undefined) { + throw new Error('Required parameter "params[\'answerText\']" missing.'); + } + + if (params["answerId"] === null || params["answerId"] === undefined) { + throw new Error('Required parameter "params[\'answerId\']" missing.'); + } + + if (params["questionnaireSid"] === null || params["questionnaireSid"] === undefined) { + throw new Error('Required parameter "params[\'questionnaireSid\']" missing.'); + } + + let data: any = {}; + + + + data["CategorySid"] = params["categorySid"]; + + data["CategoryName"] = params["categoryName"]; + + data["SegmentId"] = params["segmentId"]; + + data["AgentId"] = params["agentId"]; + + data["Offset"] = params["offset"]; + + data["MetricId"] = params["metricId"]; + + data["MetricName"] = params["metricName"]; + + data["AnswerText"] = params["answerText"]; + + data["AnswerId"] = params["answerId"]; + + data["QuestionnaireSid"] = params["questionnaireSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AssessmentsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AssessmentsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["categorySid"] === null || params["categorySid"] === undefined) { + throw new Error('Required parameter "params[\'categorySid\']" missing.'); + } + + if (params["categoryName"] === null || params["categoryName"] === undefined) { + throw new Error('Required parameter "params[\'categoryName\']" missing.'); + } + + if (params["segmentId"] === null || params["segmentId"] === undefined) { + throw new Error('Required parameter "params[\'segmentId\']" missing.'); + } + + if (params["agentId"] === null || params["agentId"] === undefined) { + throw new Error('Required parameter "params[\'agentId\']" missing.'); + } + + if (params["offset"] === null || params["offset"] === undefined) { + throw new Error('Required parameter "params[\'offset\']" missing.'); + } + + if (params["metricId"] === null || params["metricId"] === undefined) { + throw new Error('Required parameter "params[\'metricId\']" missing.'); + } + + if (params["metricName"] === null || params["metricName"] === undefined) { + throw new Error('Required parameter "params[\'metricName\']" missing.'); + } + + if (params["answerText"] === null || params["answerText"] === undefined) { + throw new Error('Required parameter "params[\'answerText\']" missing.'); + } + + if (params["answerId"] === null || params["answerId"] === undefined) { + throw new Error('Required parameter "params[\'answerId\']" missing.'); + } + + if (params["questionnaireSid"] === null || params["questionnaireSid"] === undefined) { + throw new Error('Required parameter "params[\'questionnaireSid\']" missing.'); + } + + let data: any = {}; + + + + data["CategorySid"] = params["categorySid"]; + + data["CategoryName"] = params["categoryName"]; + + data["SegmentId"] = params["segmentId"]; + + data["AgentId"] = params["agentId"]; + + data["Offset"] = params["offset"]; + + data["MetricId"] = params["metricId"]; + + data["MetricName"] = params["metricName"]; + + data["AnswerText"] = params["answerText"]; + + data["AnswerId"] = params["answerId"]; + + data["QuestionnaireSid"] = params["questionnaireSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AssessmentsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AssessmentsListInstancePageOptions | ((error: Error | null, items: AssessmentsPage) => any), callback?: (error: Error | null, items: AssessmentsPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["segmentId"] !== undefined) + data["SegmentId"] = params["segmentId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AssessmentsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AssessmentsPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AssessmentsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AssessmentsListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["segmentId"] !== undefined) + data["SegmentId"] = params["segmentId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssessmentsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssessmentsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AssessmentsPage extends Page { +/** +* Initialize the AssessmentsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: AssessmentsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AssessmentsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AssessmentsResource): AssessmentsInstance { + + return new AssessmentsInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/channel.ts b/rest/flexApi/v1/channel.ts new file mode 100644 index 000000000..cebfdaa8c --- /dev/null +++ b/rest/flexApi/v1/channel.ts @@ -0,0 +1,820 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a ChannelInstance + */ +export interface ChannelListInstanceCreateOptions { + /** The SID of the Flex Flow. */ + "flexFlowSid": string; + /** The `identity` value that uniquely identifies the new resource\\\'s chat User. */ + "identity": string; + /** The chat participant\\\'s friendly name. */ + "chatUserFriendlyName": string; + /** The chat channel\\\'s friendly name. */ + "chatFriendlyName": string; + /** The Target Contact Identity, for example the phone number of an SMS. */ + "target"?: string; + /** The chat channel\\\'s unique name. */ + "chatUniqueName"?: string; + /** The pre-engagement data. */ + "preEngagementData"?: string; + /** The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` */ + "taskSid"?: string; + /** The Task attributes to be added for the TaskRouter Task. */ + "taskAttributes"?: string; + /** Whether to create the channel as long-lived. */ + "longLived"?: boolean; +} + +/** + * Options to pass to each + */ +export interface ChannelListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChannelListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChannelListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ChannelContext { + + /** + * Remove a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + + /** + * Fetch a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ChannelContextSolution { + "sid": string; +} + +export class ChannelContextImpl implements ChannelContext { + protected _solution: ChannelContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Channels/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ChannelPayload extends TwilioResponsePayload { + flex_chat_channels: ChannelResource[]; +} + +interface ChannelResource { + account_sid: string; + flex_flow_sid: string; + sid: string; + user_sid: string; + task_sid: string; + url: string; + date_created: Date; + date_updated: Date; +} + +export class ChannelInstance { + protected _solution: ChannelContextSolution; + protected _context?: ChannelContext; + + constructor(protected _version: V1, payload: ChannelResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.flexFlowSid = (payload.flex_flow_sid); + this.sid = (payload.sid); + this.userSid = (payload.user_sid); + this.taskSid = (payload.task_sid); + this.url = (payload.url); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel resource and owns this Workflow. + */ + accountSid: string; + /** + * The SID of the Flex Flow. + */ + flexFlowSid: string; + /** + * The unique string that we created to identify the Channel resource. + */ + sid: string; + /** + * The SID of the chat user. + */ + userSid: string; + /** + * The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + */ + taskSid: string; + /** + * The absolute URL of the Flex chat channel resource. + */ + url: string; + /** + * The date and time in GMT when the Flex chat channel was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Flex chat channel was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + private get _proxy(): ChannelContext { + this._context = this._context || new ChannelContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + flexFlowSid: this.flexFlowSid, + sid: this.sid, + userSid: this.userSid, + taskSid: this.taskSid, + url: this.url, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ChannelSolution { +} + +export interface ChannelListInstance { + _version: V1; + _solution: ChannelSolution; + _uri: string; + + (sid: string, ): ChannelContext; + get(sid: string, ): ChannelContext; + + + + + + + /** + * Create a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + create(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + /** + * Create a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + createWithHttpInfo(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + each(params: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise; + /** + * Retrieve a single target page of ChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise; + list(params: ChannelListInstanceOptions, callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise; + /** + * Lists ChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ChannelPage) => any): Promise; + page(params: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ChannelPage) => any): Promise; + /** + * Retrieve a single page of ChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChannelListInstance(version: V1): ChannelListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ChannelListInstance; + + instance.get = function get(sid, ): ChannelContext { + return new ChannelContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Channels`; + + instance.create = function create(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, items: ChannelInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["flexFlowSid"] === null || params["flexFlowSid"] === undefined) { + throw new Error('Required parameter "params[\'flexFlowSid\']" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + if (params["chatUserFriendlyName"] === null || params["chatUserFriendlyName"] === undefined) { + throw new Error('Required parameter "params[\'chatUserFriendlyName\']" missing.'); + } + + if (params["chatFriendlyName"] === null || params["chatFriendlyName"] === undefined) { + throw new Error('Required parameter "params[\'chatFriendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FlexFlowSid"] = params["flexFlowSid"]; + + data["Identity"] = params["identity"]; + + data["ChatUserFriendlyName"] = params["chatUserFriendlyName"]; + + data["ChatFriendlyName"] = params["chatFriendlyName"]; + if (params["target"] !== undefined) + data["Target"] = params["target"]; + if (params["chatUniqueName"] !== undefined) + data["ChatUniqueName"] = params["chatUniqueName"]; + if (params["preEngagementData"] !== undefined) + data["PreEngagementData"] = params["preEngagementData"]; + if (params["taskSid"] !== undefined) + data["TaskSid"] = params["taskSid"]; + if (params["taskAttributes"] !== undefined) + data["TaskAttributes"] = params["taskAttributes"]; + if (params["longLived"] !== undefined) + data["LongLived"] = serialize.bool(params["longLived"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["flexFlowSid"] === null || params["flexFlowSid"] === undefined) { + throw new Error('Required parameter "params[\'flexFlowSid\']" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + if (params["chatUserFriendlyName"] === null || params["chatUserFriendlyName"] === undefined) { + throw new Error('Required parameter "params[\'chatUserFriendlyName\']" missing.'); + } + + if (params["chatFriendlyName"] === null || params["chatFriendlyName"] === undefined) { + throw new Error('Required parameter "params[\'chatFriendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FlexFlowSid"] = params["flexFlowSid"]; + + data["Identity"] = params["identity"]; + + data["ChatUserFriendlyName"] = params["chatUserFriendlyName"]; + + data["ChatFriendlyName"] = params["chatFriendlyName"]; + if (params["target"] !== undefined) + data["Target"] = params["target"]; + if (params["chatUniqueName"] !== undefined) + data["ChatUniqueName"] = params["chatUniqueName"]; + if (params["preEngagementData"] !== undefined) + data["PreEngagementData"] = params["preEngagementData"]; + if (params["taskSid"] !== undefined) + data["TaskSid"] = params["taskSid"]; + if (params["taskAttributes"] !== undefined) + data["TaskAttributes"] = params["taskAttributes"]; + if (params["longLived"] !== undefined) + data["LongLived"] = serialize.bool(params["longLived"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ChannelListInstancePageOptions | ((error: Error | null, items: ChannelPage) => any), callback?: (error: Error | null, items: ChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ChannelPage extends Page { +/** +* Initialize the ChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChannelResource): ChannelInstance { + + return new ChannelInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/configuration.ts b/rest/flexApi/v1/configuration.ts new file mode 100644 index 000000000..66f4c943e --- /dev/null +++ b/rest/flexApi/v1/configuration.ts @@ -0,0 +1,809 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The status of the Flex onboarding. Can be: `ok`, `inprogress`,`notstarted`. + */ +export type ConfigurationStatus = 'ok'|'inprogress'|'notstarted'; + + +/** + * Options to pass to fetch a ConfigurationInstance + */ +export interface ConfigurationContextFetchOptions { + /** The Pinned UI version of the Configuration resource to fetch. */ + "uiVersion"?: string; +} + +/** + * Options to pass to update a ConfigurationInstance + */ +export interface ConfigurationContextUpdateOptions { + /** */ + "body"?: object; +} + +export interface ConfigurationContext { + + /** + * Fetch a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Fetch a ConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(params: ConfigurationContextFetchOptions, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(params: ConfigurationContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Update a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Update a ConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(params: object, headers?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConfigurationContextSolution { +} + +export class ConfigurationContextImpl implements ConfigurationContext { + protected _solution: ConfigurationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/Configuration`; + } + + fetch(params?: ConfigurationContextFetchOptions | ((error: Error | null, item?: ConfigurationInstance) => any),callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["uiVersion"] !== undefined) + data["UiVersion"] = params["uiVersion"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: ConfigurationContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["uiVersion"] !== undefined) + data["UiVersion"] = params["uiVersion"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: object | ((error: Error | null, item?: ConfigurationInstance) => any), headers?: any,callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as object; + } else { + params = params || {} as Partial as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: object | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as object; + } else { + params = params || {} as Partial as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConfigurationPayload extends ConfigurationResource {} + +interface ConfigurationResource { + account_sid: string; + date_created: Date; + date_updated: Date; + attributes: any; + status: ConfigurationStatus; + taskrouter_workspace_sid: string; + taskrouter_target_workflow_sid: string; + taskrouter_target_taskqueue_sid: string; + taskrouter_taskqueues: Array; + taskrouter_skills: Array; + taskrouter_worker_channels: any; + taskrouter_worker_attributes: any; + taskrouter_offline_activity_sid: string; + runtime_domain: string; + messaging_service_instance_sid: string; + chat_service_instance_sid: string; + flex_service_instance_sid: string; + flex_instance_sid: string; + ui_language: string; + ui_attributes: any; + ui_dependencies: any; + ui_version: string; + service_version: string; + call_recording_enabled: boolean; + call_recording_webhook_url: string; + crm_enabled: boolean; + crm_type: string; + crm_callback_url: string; + crm_fallback_url: string; + crm_attributes: any; + public_attributes: any; + plugin_service_enabled: boolean; + plugin_service_attributes: any; + integrations: Array; + outbound_call_flows: any; + serverless_service_sids: Array; + queue_stats_configuration: any; + notifications: any; + markdown: any; + url: string; + flex_insights_hr: any; + flex_insights_drilldown: boolean; + flex_url: string; + channel_configs: Array; + debugger_integration: any; + flex_ui_status_report: any; + agent_conv_end_methods: any; + citrix_voice_vdi: any; + offline_config: any; +} + +export class ConfigurationInstance { + protected _solution: ConfigurationContextSolution; + protected _context?: ConfigurationContext; + + constructor(protected _version: V1, payload: ConfigurationResource) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.attributes = (payload.attributes); + this.status = payload.status; + this.taskrouterWorkspaceSid = (payload.taskrouter_workspace_sid); + this.taskrouterTargetWorkflowSid = (payload.taskrouter_target_workflow_sid); + this.taskrouterTargetTaskqueueSid = (payload.taskrouter_target_taskqueue_sid); + this.taskrouterTaskqueues = (payload.taskrouter_taskqueues); + this.taskrouterSkills = (payload.taskrouter_skills); + this.taskrouterWorkerChannels = (payload.taskrouter_worker_channels); + this.taskrouterWorkerAttributes = (payload.taskrouter_worker_attributes); + this.taskrouterOfflineActivitySid = (payload.taskrouter_offline_activity_sid); + this.runtimeDomain = (payload.runtime_domain); + this.messagingServiceInstanceSid = (payload.messaging_service_instance_sid); + this.chatServiceInstanceSid = (payload.chat_service_instance_sid); + this.flexServiceInstanceSid = (payload.flex_service_instance_sid); + this.flexInstanceSid = (payload.flex_instance_sid); + this.uiLanguage = (payload.ui_language); + this.uiAttributes = (payload.ui_attributes); + this.uiDependencies = (payload.ui_dependencies); + this.uiVersion = (payload.ui_version); + this.serviceVersion = (payload.service_version); + this.callRecordingEnabled = (payload.call_recording_enabled); + this.callRecordingWebhookUrl = (payload.call_recording_webhook_url); + this.crmEnabled = (payload.crm_enabled); + this.crmType = (payload.crm_type); + this.crmCallbackUrl = (payload.crm_callback_url); + this.crmFallbackUrl = (payload.crm_fallback_url); + this.crmAttributes = (payload.crm_attributes); + this.publicAttributes = (payload.public_attributes); + this.pluginServiceEnabled = (payload.plugin_service_enabled); + this.pluginServiceAttributes = (payload.plugin_service_attributes); + this.integrations = (payload.integrations); + this.outboundCallFlows = (payload.outbound_call_flows); + this.serverlessServiceSids = (payload.serverless_service_sids); + this.queueStatsConfiguration = (payload.queue_stats_configuration); + this.notifications = (payload.notifications); + this.markdown = (payload.markdown); + this.url = (payload.url); + this.flexInsightsHr = (payload.flex_insights_hr); + this.flexInsightsDrilldown = (payload.flex_insights_drilldown); + this.flexUrl = (payload.flex_url); + this.channelConfigs = (payload.channel_configs); + this.debuggerIntegration = (payload.debugger_integration); + this.flexUiStatusReport = (payload.flex_ui_status_report); + this.agentConvEndMethods = (payload.agent_conv_end_methods); + this.citrixVoiceVdi = (payload.citrix_voice_vdi); + this.offlineConfig = (payload.offline_config); + + this._solution = { }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Configuration resource. + */ + accountSid: string; + /** + * The date and time in GMT when the Configuration resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Configuration resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * An object that contains application-specific data. + */ + attributes: any; + status: ConfigurationStatus; + /** + * The SID of the TaskRouter Workspace. + */ + taskrouterWorkspaceSid: string; + /** + * The SID of the TaskRouter target Workflow. + */ + taskrouterTargetWorkflowSid: string; + /** + * The SID of the TaskRouter Target TaskQueue. + */ + taskrouterTargetTaskqueueSid: string; + /** + * The list of TaskRouter TaskQueues. + */ + taskrouterTaskqueues: Array; + /** + * The Skill description for TaskRouter workers. + */ + taskrouterSkills: Array; + /** + * The TaskRouter default channel capacities and availability for workers. + */ + taskrouterWorkerChannels: any; + /** + * The TaskRouter Worker attributes. + */ + taskrouterWorkerAttributes: any; + /** + * The TaskRouter SID of the offline activity. + */ + taskrouterOfflineActivitySid: string; + /** + * The URL where the Flex instance is hosted. + */ + runtimeDomain: string; + /** + * The SID of the Messaging service instance. + */ + messagingServiceInstanceSid: string; + /** + * The SID of the chat service this user belongs to. + */ + chatServiceInstanceSid: string; + /** + * The SID of the Flex service instance. + */ + flexServiceInstanceSid: string; + /** + * The SID of the Flex instance. + */ + flexInstanceSid: string; + /** + * The primary language of the Flex UI. + */ + uiLanguage: string; + /** + * The object that describes Flex UI characteristics and settings. + */ + uiAttributes: any; + /** + * The object that defines the NPM packages and versions to be used in Hosted Flex. + */ + uiDependencies: any; + /** + * The Pinned UI version. + */ + uiVersion: string; + /** + * The Flex Service version. + */ + serviceVersion: string; + /** + * Whether call recording is enabled. + */ + callRecordingEnabled: boolean; + /** + * The call recording webhook URL. + */ + callRecordingWebhookUrl: string; + /** + * Whether CRM is present for Flex. + */ + crmEnabled: boolean; + /** + * The CRM type. + */ + crmType: string; + /** + * The CRM Callback URL. + */ + crmCallbackUrl: string; + /** + * The CRM Fallback URL. + */ + crmFallbackUrl: string; + /** + * An object that contains the CRM attributes. + */ + crmAttributes: any; + /** + * The list of public attributes, which are visible to unauthenticated clients. + */ + publicAttributes: any; + /** + * Whether the plugin service enabled. + */ + pluginServiceEnabled: boolean; + /** + * The plugin service attributes. + */ + pluginServiceAttributes: any; + /** + * A list of objects that contain the configurations for the Integrations supported in this configuration. + */ + integrations: Array; + /** + * The list of outbound call flows. + */ + outboundCallFlows: any; + /** + * The list of serverless service SIDs. + */ + serverlessServiceSids: Array; + /** + * Configurable parameters for Queues Statistics. + */ + queueStatsConfiguration: any; + /** + * Configurable parameters for Notifications. + */ + notifications: any; + /** + * Configurable parameters for Markdown. + */ + markdown: any; + /** + * The absolute URL of the Configuration resource. + */ + url: string; + /** + * Object with enabled/disabled flag with list of workspaces. + */ + flexInsightsHr: any; + /** + * Setting this to true will redirect Flex UI to the URL set in flex_url + */ + flexInsightsDrilldown: boolean; + /** + * URL to redirect to in case drilldown is enabled. + */ + flexUrl: string; + /** + * Settings for different limits for Flex Conversations channels attachments. + */ + channelConfigs: Array; + /** + * Configurable parameters for Debugger Integration. + */ + debuggerIntegration: any; + /** + * Configurable parameters for Flex UI Status report. + */ + flexUiStatusReport: any; + /** + * Agent conversation end methods. + */ + agentConvEndMethods: any; + /** + * Citrix voice vdi configuration and settings. + */ + citrixVoiceVdi: any; + /** + * Presence and presence ttl configuration + */ + offlineConfig: any; + + private get _proxy(): ConfigurationContext { + this._context = this._context || new ConfigurationContextImpl(this._version); + return this._context; + } + + /** + * Fetch a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Fetch a ConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(params: ConfigurationContextFetchOptions, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(params: ConfigurationContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Update a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + /** + * Update a ConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(params: object, headers?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + attributes: this.attributes, + status: this.status, + taskrouterWorkspaceSid: this.taskrouterWorkspaceSid, + taskrouterTargetWorkflowSid: this.taskrouterTargetWorkflowSid, + taskrouterTargetTaskqueueSid: this.taskrouterTargetTaskqueueSid, + taskrouterTaskqueues: this.taskrouterTaskqueues, + taskrouterSkills: this.taskrouterSkills, + taskrouterWorkerChannels: this.taskrouterWorkerChannels, + taskrouterWorkerAttributes: this.taskrouterWorkerAttributes, + taskrouterOfflineActivitySid: this.taskrouterOfflineActivitySid, + runtimeDomain: this.runtimeDomain, + messagingServiceInstanceSid: this.messagingServiceInstanceSid, + chatServiceInstanceSid: this.chatServiceInstanceSid, + flexServiceInstanceSid: this.flexServiceInstanceSid, + flexInstanceSid: this.flexInstanceSid, + uiLanguage: this.uiLanguage, + uiAttributes: this.uiAttributes, + uiDependencies: this.uiDependencies, + uiVersion: this.uiVersion, + serviceVersion: this.serviceVersion, + callRecordingEnabled: this.callRecordingEnabled, + callRecordingWebhookUrl: this.callRecordingWebhookUrl, + crmEnabled: this.crmEnabled, + crmType: this.crmType, + crmCallbackUrl: this.crmCallbackUrl, + crmFallbackUrl: this.crmFallbackUrl, + crmAttributes: this.crmAttributes, + publicAttributes: this.publicAttributes, + pluginServiceEnabled: this.pluginServiceEnabled, + pluginServiceAttributes: this.pluginServiceAttributes, + integrations: this.integrations, + outboundCallFlows: this.outboundCallFlows, + serverlessServiceSids: this.serverlessServiceSids, + queueStatsConfiguration: this.queueStatsConfiguration, + notifications: this.notifications, + markdown: this.markdown, + url: this.url, + flexInsightsHr: this.flexInsightsHr, + flexInsightsDrilldown: this.flexInsightsDrilldown, + flexUrl: this.flexUrl, + channelConfigs: this.channelConfigs, + debuggerIntegration: this.debuggerIntegration, + flexUiStatusReport: this.flexUiStatusReport, + agentConvEndMethods: this.agentConvEndMethods, + citrixVoiceVdi: this.citrixVoiceVdi, + offlineConfig: this.offlineConfig, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConfigurationSolution { +} + +export interface ConfigurationListInstance { + _version: V1; + _solution: ConfigurationSolution; + _uri: string; + + (): ConfigurationContext; + get(): ConfigurationContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConfigurationListInstance(version: V1): ConfigurationListInstance { + const instance = (() => instance.get()) as ConfigurationListInstance; + + instance.get = function get(): ConfigurationContext { + return new ConfigurationContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/flexApi/v1/flexFlow.ts b/rest/flexApi/v1/flexFlow.ts new file mode 100644 index 000000000..32374c830 --- /dev/null +++ b/rest/flexApi/v1/flexFlow.ts @@ -0,0 +1,1167 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The channel type. One of `web`, `facebook`, `sms`, `whatsapp`, `line` or `custom`. By default, Studio’s Send to Flex widget passes it on to the Task attributes for Tasks created based on this Flex Flow. The Task attributes will be used by the Flex UI to render the respective Task as appropriate (applying channel-specific design and length limits). If `channelType` is `facebook`, `whatsapp` or `line`, the Send to Flex widget should set the Task Channel to Programmable Chat. + */ +export type FlexFlowChannelType = 'web'|'sms'|'facebook'|'whatsapp'|'line'|'custom'; + +/** + * The software that will handle inbound messages. [Integration Type](https://www.twilio.com/docs/flex/developer/messaging/manage-flows#integration-types) can be: `studio`, `external`, or `task`. + */ +export type FlexFlowIntegrationType = 'studio'|'external'|'task'; + + + + +/** + * Options to pass to update a FlexFlowInstance + */ +export interface FlexFlowContextUpdateOptions { + /** A descriptive string that you create to describe the Flex Flow resource. */ + "friendlyName"?: string; + /** The SID of the chat service. */ + "chatServiceSid"?: string; + /** */ + "channelType"?: FlexFlowChannelType; + /** The channel contact\\\'s Identity. */ + "contactIdentity"?: string; + /** Whether the new Flex Flow is enabled. */ + "enabled"?: boolean; + /** */ + "integrationType"?: FlexFlowIntegrationType; + /** The SID of the Studio Flow. Required when `integrationType` is `studio`. */ + "integration.flowSid"?: string; + /** The URL of the external webhook. Required when `integrationType` is `external`. */ + "integration.url"?: string; + /** The Workspace SID for a new Task. Required when `integrationType` is `task`. */ + "integration.workspaceSid"?: string; + /** The Workflow SID for a new Task. Required when `integrationType` is `task`. */ + "integration.workflowSid"?: string; + /** The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. */ + "integration.channel"?: string; + /** The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. */ + "integration.timeout"?: number; + /** The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. */ + "integration.priority"?: number; + /** In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. */ + "integration.creationOnMessage"?: boolean; + /** When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. */ + "longLived"?: boolean; + /** When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. */ + "janitorEnabled"?: boolean; + /** The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. */ + "integration.retryCount"?: number; +} + +/** + * Options to pass to create a FlexFlowInstance + */ +export interface FlexFlowListInstanceCreateOptions { + /** A descriptive string that you create to describe the Flex Flow resource. */ + "friendlyName": string; + /** The SID of the chat service. */ + "chatServiceSid": string; + /** */ + "channelType": FlexFlowChannelType; + /** The channel contact\\\'s Identity. */ + "contactIdentity"?: string; + /** Whether the new Flex Flow is enabled. */ + "enabled"?: boolean; + /** */ + "integrationType"?: FlexFlowIntegrationType; + /** The SID of the Studio Flow. Required when `integrationType` is `studio`. */ + "integration.flowSid"?: string; + /** The URL of the external webhook. Required when `integrationType` is `external`. */ + "integration.url"?: string; + /** The Workspace SID for a new Task. Required when `integrationType` is `task`. */ + "integration.workspaceSid"?: string; + /** The Workflow SID for a new Task. Required when `integrationType` is `task`. */ + "integration.workflowSid"?: string; + /** The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. */ + "integration.channel"?: string; + /** The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. */ + "integration.timeout"?: number; + /** The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. */ + "integration.priority"?: number; + /** In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. */ + "integration.creationOnMessage"?: boolean; + /** When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. */ + "longLived"?: boolean; + /** When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. */ + "janitorEnabled"?: boolean; + /** The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. */ + "integration.retryCount"?: number; +} + +/** + * Options to pass to each + */ +export interface FlexFlowListInstanceEachOptions { + /** The `friendly_name` of the Flex Flow resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: FlexFlowInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface FlexFlowListInstanceOptions { + /** The `friendly_name` of the Flex Flow resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface FlexFlowListInstancePageOptions { + /** The `friendly_name` of the Flex Flow resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface FlexFlowContext { + + /** + * Remove a FlexFlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a FlexFlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a FlexFlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance + */ + fetch(callback?: (error: Error | null, item?: FlexFlowInstance) => any): Promise + + /** + * Fetch a FlexFlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a FlexFlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance + */ + update(callback?: (error: Error | null, item?: FlexFlowInstance) => any): Promise; + /** + * Update a FlexFlowInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance + */ + update(params: FlexFlowContextUpdateOptions, callback?: (error: Error | null, item?: FlexFlowInstance) => any): Promise; + + /** + * Update a FlexFlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a FlexFlowInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance with HTTP metadata + */ + updateWithHttpInfo(params: FlexFlowContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FlexFlowContextSolution { + "sid": string; +} + +export class FlexFlowContextImpl implements FlexFlowContext { + protected _solution: FlexFlowContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/FlexFlows/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: FlexFlowInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FlexFlowInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new FlexFlowInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: FlexFlowContextUpdateOptions | ((error: Error | null, item?: FlexFlowInstance) => any),callback?: (error: Error | null, item?: FlexFlowInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["chatServiceSid"] !== undefined) + data["ChatServiceSid"] = params["chatServiceSid"]; + if (params["channelType"] !== undefined) + data["ChannelType"] = params["channelType"]; + if (params["contactIdentity"] !== undefined) + data["ContactIdentity"] = params["contactIdentity"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["integrationType"] !== undefined) + data["IntegrationType"] = params["integrationType"]; + if (params["integration.flowSid"] !== undefined) + data["Integration.FlowSid"] = params["integration.flowSid"]; + if (params["integration.url"] !== undefined) + data["Integration.Url"] = params["integration.url"]; + if (params["integration.workspaceSid"] !== undefined) + data["Integration.WorkspaceSid"] = params["integration.workspaceSid"]; + if (params["integration.workflowSid"] !== undefined) + data["Integration.WorkflowSid"] = params["integration.workflowSid"]; + if (params["integration.channel"] !== undefined) + data["Integration.Channel"] = params["integration.channel"]; + if (params["integration.timeout"] !== undefined) + data["Integration.Timeout"] = params["integration.timeout"]; + if (params["integration.priority"] !== undefined) + data["Integration.Priority"] = params["integration.priority"]; + if (params["integration.creationOnMessage"] !== undefined) + data["Integration.CreationOnMessage"] = serialize.bool(params["integration.creationOnMessage"]); + if (params["longLived"] !== undefined) + data["LongLived"] = serialize.bool(params["longLived"]); + if (params["janitorEnabled"] !== undefined) + data["JanitorEnabled"] = serialize.bool(params["janitorEnabled"]); + if (params["integration.retryCount"] !== undefined) + data["Integration.RetryCount"] = params["integration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FlexFlowInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: FlexFlowContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["chatServiceSid"] !== undefined) + data["ChatServiceSid"] = params["chatServiceSid"]; + if (params["channelType"] !== undefined) + data["ChannelType"] = params["channelType"]; + if (params["contactIdentity"] !== undefined) + data["ContactIdentity"] = params["contactIdentity"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["integrationType"] !== undefined) + data["IntegrationType"] = params["integrationType"]; + if (params["integration.flowSid"] !== undefined) + data["Integration.FlowSid"] = params["integration.flowSid"]; + if (params["integration.url"] !== undefined) + data["Integration.Url"] = params["integration.url"]; + if (params["integration.workspaceSid"] !== undefined) + data["Integration.WorkspaceSid"] = params["integration.workspaceSid"]; + if (params["integration.workflowSid"] !== undefined) + data["Integration.WorkflowSid"] = params["integration.workflowSid"]; + if (params["integration.channel"] !== undefined) + data["Integration.Channel"] = params["integration.channel"]; + if (params["integration.timeout"] !== undefined) + data["Integration.Timeout"] = params["integration.timeout"]; + if (params["integration.priority"] !== undefined) + data["Integration.Priority"] = params["integration.priority"]; + if (params["integration.creationOnMessage"] !== undefined) + data["Integration.CreationOnMessage"] = serialize.bool(params["integration.creationOnMessage"]); + if (params["longLived"] !== undefined) + data["LongLived"] = serialize.bool(params["longLived"]); + if (params["janitorEnabled"] !== undefined) + data["JanitorEnabled"] = serialize.bool(params["janitorEnabled"]); + if (params["integration.retryCount"] !== undefined) + data["Integration.RetryCount"] = params["integration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new FlexFlowInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FlexFlowPayload extends TwilioResponsePayload { + flex_flows: FlexFlowResource[]; +} + +interface FlexFlowResource { + account_sid: string; + date_created: Date; + date_updated: Date; + sid: string; + friendly_name: string; + chat_service_sid: string; + channel_type: FlexFlowChannelType; + contact_identity: string; + enabled: boolean; + integration_type: FlexFlowIntegrationType; + integration: any; + long_lived: boolean; + janitor_enabled: boolean; + url: string; +} + +export class FlexFlowInstance { + protected _solution: FlexFlowContextSolution; + protected _context?: FlexFlowContext; + + constructor(protected _version: V1, payload: FlexFlowResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.chatServiceSid = (payload.chat_service_sid); + this.channelType = payload.channel_type; + this.contactIdentity = (payload.contact_identity); + this.enabled = (payload.enabled); + this.integrationType = payload.integration_type; + this.integration = (payload.integration); + this.longLived = (payload.long_lived); + this.janitorEnabled = (payload.janitor_enabled); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Flow resource and owns this Workflow. + */ + accountSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The unique string that we created to identify the Flex Flow resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The SID of the chat service. + */ + chatServiceSid: string; + channelType: FlexFlowChannelType; + /** + * The channel contact\'s Identity. + */ + contactIdentity: string; + /** + * Whether the Flex Flow is enabled. + */ + enabled: boolean; + integrationType: FlexFlowIntegrationType; + /** + * An object that contains specific parameters for the integration. + */ + integration: any; + /** + * When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + */ + longLived: boolean; + /** + * When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + */ + janitorEnabled: boolean; + /** + * The absolute URL of the Flex Flow resource. + */ + url: string; + + private get _proxy(): FlexFlowContext { + this._context = this._context || new FlexFlowContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a FlexFlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a FlexFlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a FlexFlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance + */ + fetch(callback?: (error: Error | null, item?: FlexFlowInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FlexFlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a FlexFlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance + */ + update(callback?: (error: Error | null, item?: FlexFlowInstance) => any): Promise; + /** + * Update a FlexFlowInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance + */ + update(params: FlexFlowContextUpdateOptions, callback?: (error: Error | null, item?: FlexFlowInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: FlexFlowInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a FlexFlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a FlexFlowInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance with HTTP metadata + */ + updateWithHttpInfo(params: FlexFlowContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + sid: this.sid, + friendlyName: this.friendlyName, + chatServiceSid: this.chatServiceSid, + channelType: this.channelType, + contactIdentity: this.contactIdentity, + enabled: this.enabled, + integrationType: this.integrationType, + integration: this.integration, + longLived: this.longLived, + janitorEnabled: this.janitorEnabled, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FlexFlowSolution { +} + +export interface FlexFlowListInstance { + _version: V1; + _solution: FlexFlowSolution; + _uri: string; + + (sid: string, ): FlexFlowContext; + get(sid: string, ): FlexFlowContext; + + + + + + + + + /** + * Create a FlexFlowInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance + */ + create(params: FlexFlowListInstanceCreateOptions, callback?: (error: Error | null, item?: FlexFlowInstance) => any): Promise; + + /** + * Create a FlexFlowInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexFlowInstance with HTTP metadata + */ + createWithHttpInfo(params: FlexFlowListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams FlexFlowInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlexFlowListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: FlexFlowInstance, done: (err?: Error) => void) => void): void; + each(params: FlexFlowListInstanceEachOptions, callback?: (item: FlexFlowInstance, done: (err?: Error) => void) => void): void; + /** + * Streams FlexFlowInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlexFlowListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: FlexFlowInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: FlexFlowListInstanceEachOptions, callback?: (item: FlexFlowInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of FlexFlowInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: FlexFlowPage) => any): Promise; + /** + * Retrieve a single target page of FlexFlowInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists FlexFlowInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlexFlowListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: FlexFlowInstance[]) => any): Promise; + list(params: FlexFlowListInstanceOptions, callback?: (error: Error | null, items: FlexFlowInstance[]) => any): Promise; + /** + * Lists FlexFlowInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlexFlowListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: FlexFlowListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of FlexFlowInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlexFlowListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: FlexFlowPage) => any): Promise; + page(params: FlexFlowListInstancePageOptions, callback?: (error: Error | null, items: FlexFlowPage) => any): Promise; + /** + * Retrieve a single page of FlexFlowInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlexFlowListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: FlexFlowListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FlexFlowListInstance(version: V1): FlexFlowListInstance { + const instance = ((sid, ) => instance.get(sid, )) as FlexFlowListInstance; + + instance.get = function get(sid, ): FlexFlowContext { + return new FlexFlowContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/FlexFlows`; + + instance.create = function create(params: FlexFlowListInstanceCreateOptions, callback?: (error: Error | null, items: FlexFlowInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["chatServiceSid"] === null || params["chatServiceSid"] === undefined) { + throw new Error('Required parameter "params[\'chatServiceSid\']" missing.'); + } + + if (params["channelType"] === null || params["channelType"] === undefined) { + throw new Error('Required parameter "params[\'channelType\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["ChatServiceSid"] = params["chatServiceSid"]; + + data["ChannelType"] = params["channelType"]; + if (params["contactIdentity"] !== undefined) + data["ContactIdentity"] = params["contactIdentity"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["integrationType"] !== undefined) + data["IntegrationType"] = params["integrationType"]; + if (params["integration.flowSid"] !== undefined) + data["Integration.FlowSid"] = params["integration.flowSid"]; + if (params["integration.url"] !== undefined) + data["Integration.Url"] = params["integration.url"]; + if (params["integration.workspaceSid"] !== undefined) + data["Integration.WorkspaceSid"] = params["integration.workspaceSid"]; + if (params["integration.workflowSid"] !== undefined) + data["Integration.WorkflowSid"] = params["integration.workflowSid"]; + if (params["integration.channel"] !== undefined) + data["Integration.Channel"] = params["integration.channel"]; + if (params["integration.timeout"] !== undefined) + data["Integration.Timeout"] = params["integration.timeout"]; + if (params["integration.priority"] !== undefined) + data["Integration.Priority"] = params["integration.priority"]; + if (params["integration.creationOnMessage"] !== undefined) + data["Integration.CreationOnMessage"] = serialize.bool(params["integration.creationOnMessage"]); + if (params["longLived"] !== undefined) + data["LongLived"] = serialize.bool(params["longLived"]); + if (params["janitorEnabled"] !== undefined) + data["JanitorEnabled"] = serialize.bool(params["janitorEnabled"]); + if (params["integration.retryCount"] !== undefined) + data["Integration.RetryCount"] = params["integration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FlexFlowInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: FlexFlowListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["chatServiceSid"] === null || params["chatServiceSid"] === undefined) { + throw new Error('Required parameter "params[\'chatServiceSid\']" missing.'); + } + + if (params["channelType"] === null || params["channelType"] === undefined) { + throw new Error('Required parameter "params[\'channelType\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["ChatServiceSid"] = params["chatServiceSid"]; + + data["ChannelType"] = params["channelType"]; + if (params["contactIdentity"] !== undefined) + data["ContactIdentity"] = params["contactIdentity"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["integrationType"] !== undefined) + data["IntegrationType"] = params["integrationType"]; + if (params["integration.flowSid"] !== undefined) + data["Integration.FlowSid"] = params["integration.flowSid"]; + if (params["integration.url"] !== undefined) + data["Integration.Url"] = params["integration.url"]; + if (params["integration.workspaceSid"] !== undefined) + data["Integration.WorkspaceSid"] = params["integration.workspaceSid"]; + if (params["integration.workflowSid"] !== undefined) + data["Integration.WorkflowSid"] = params["integration.workflowSid"]; + if (params["integration.channel"] !== undefined) + data["Integration.Channel"] = params["integration.channel"]; + if (params["integration.timeout"] !== undefined) + data["Integration.Timeout"] = params["integration.timeout"]; + if (params["integration.priority"] !== undefined) + data["Integration.Priority"] = params["integration.priority"]; + if (params["integration.creationOnMessage"] !== undefined) + data["Integration.CreationOnMessage"] = serialize.bool(params["integration.creationOnMessage"]); + if (params["longLived"] !== undefined) + data["LongLived"] = serialize.bool(params["longLived"]); + if (params["janitorEnabled"] !== undefined) + data["JanitorEnabled"] = serialize.bool(params["janitorEnabled"]); + if (params["integration.retryCount"] !== undefined) + data["Integration.RetryCount"] = params["integration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new FlexFlowInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: FlexFlowListInstancePageOptions | ((error: Error | null, items: FlexFlowPage) => any), callback?: (error: Error | null, items: FlexFlowPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new FlexFlowPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: FlexFlowPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new FlexFlowPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: FlexFlowListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FlexFlowPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FlexFlowPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class FlexFlowPage extends Page { +/** +* Initialize the FlexFlowPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: FlexFlowSolution) { + super(version, response, solution); + } + + /** + * Build an instance of FlexFlowInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: FlexFlowResource): FlexFlowInstance { + + return new FlexFlowInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/insightsAssessmentsComment.ts b/rest/flexApi/v1/insightsAssessmentsComment.ts new file mode 100644 index 000000000..7b477afa1 --- /dev/null +++ b/rest/flexApi/v1/insightsAssessmentsComment.ts @@ -0,0 +1,653 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a InsightsAssessmentsCommentInstance + */ +export interface InsightsAssessmentsCommentListInstanceCreateOptions { + /** The ID of the category */ + "categoryId": string; + /** The name of the category */ + "categoryName": string; + /** The Assessment comment. */ + "comment": string; + /** The id of the segment. */ + "segmentId": string; + /** The id of the agent. */ + "agentId": string; + /** The offset */ + "offset": number; + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +/** + * Options to pass to each + */ +export interface InsightsAssessmentsCommentListInstanceEachOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The id of the segment. */ + "segmentId"?: string; + /** The id of the agent. */ + "agentId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InsightsAssessmentsCommentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InsightsAssessmentsCommentListInstanceOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The id of the segment. */ + "segmentId"?: string; + /** The id of the agent. */ + "agentId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InsightsAssessmentsCommentListInstancePageOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The id of the segment. */ + "segmentId"?: string; + /** The id of the agent. */ + "agentId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface InsightsAssessmentsCommentSolution { +} + +export interface InsightsAssessmentsCommentListInstance { + _version: V1; + _solution: InsightsAssessmentsCommentSolution; + _uri: string; + + + + /** + * Create a InsightsAssessmentsCommentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsAssessmentsCommentInstance + */ + create(params: InsightsAssessmentsCommentListInstanceCreateOptions, callback?: (error: Error | null, item?: InsightsAssessmentsCommentInstance) => any): Promise; + + /** + * Create a InsightsAssessmentsCommentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsAssessmentsCommentInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsAssessmentsCommentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams InsightsAssessmentsCommentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsAssessmentsCommentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InsightsAssessmentsCommentInstance, done: (err?: Error) => void) => void): void; + each(params: InsightsAssessmentsCommentListInstanceEachOptions, callback?: (item: InsightsAssessmentsCommentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InsightsAssessmentsCommentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsAssessmentsCommentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InsightsAssessmentsCommentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InsightsAssessmentsCommentListInstanceEachOptions, callback?: (item: InsightsAssessmentsCommentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InsightsAssessmentsCommentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsAssessmentsCommentPage) => any): Promise; + /** + * Retrieve a single target page of InsightsAssessmentsCommentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InsightsAssessmentsCommentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsAssessmentsCommentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InsightsAssessmentsCommentInstance[]) => any): Promise; + list(params: InsightsAssessmentsCommentListInstanceOptions, callback?: (error: Error | null, items: InsightsAssessmentsCommentInstance[]) => any): Promise; + /** + * Lists InsightsAssessmentsCommentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsAssessmentsCommentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InsightsAssessmentsCommentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InsightsAssessmentsCommentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsAssessmentsCommentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InsightsAssessmentsCommentPage) => any): Promise; + page(params: InsightsAssessmentsCommentListInstancePageOptions, callback?: (error: Error | null, items: InsightsAssessmentsCommentPage) => any): Promise; + /** + * Retrieve a single page of InsightsAssessmentsCommentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsAssessmentsCommentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InsightsAssessmentsCommentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InsightsAssessmentsCommentListInstance(version: V1): InsightsAssessmentsCommentListInstance { + const instance = {} as InsightsAssessmentsCommentListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Insights/QualityManagement/Assessments/Comments`; + + instance.create = function create(params: InsightsAssessmentsCommentListInstanceCreateOptions, callback?: (error: Error | null, items: InsightsAssessmentsCommentInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["categoryId"] === null || params["categoryId"] === undefined) { + throw new Error('Required parameter "params[\'categoryId\']" missing.'); + } + + if (params["categoryName"] === null || params["categoryName"] === undefined) { + throw new Error('Required parameter "params[\'categoryName\']" missing.'); + } + + if (params["comment"] === null || params["comment"] === undefined) { + throw new Error('Required parameter "params[\'comment\']" missing.'); + } + + if (params["segmentId"] === null || params["segmentId"] === undefined) { + throw new Error('Required parameter "params[\'segmentId\']" missing.'); + } + + if (params["agentId"] === null || params["agentId"] === undefined) { + throw new Error('Required parameter "params[\'agentId\']" missing.'); + } + + if (params["offset"] === null || params["offset"] === undefined) { + throw new Error('Required parameter "params[\'offset\']" missing.'); + } + + let data: any = {}; + + + + data["CategoryId"] = params["categoryId"]; + + data["CategoryName"] = params["categoryName"]; + + data["Comment"] = params["comment"]; + + data["SegmentId"] = params["segmentId"]; + + data["AgentId"] = params["agentId"]; + + data["Offset"] = params["offset"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsAssessmentsCommentInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InsightsAssessmentsCommentListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["categoryId"] === null || params["categoryId"] === undefined) { + throw new Error('Required parameter "params[\'categoryId\']" missing.'); + } + + if (params["categoryName"] === null || params["categoryName"] === undefined) { + throw new Error('Required parameter "params[\'categoryName\']" missing.'); + } + + if (params["comment"] === null || params["comment"] === undefined) { + throw new Error('Required parameter "params[\'comment\']" missing.'); + } + + if (params["segmentId"] === null || params["segmentId"] === undefined) { + throw new Error('Required parameter "params[\'segmentId\']" missing.'); + } + + if (params["agentId"] === null || params["agentId"] === undefined) { + throw new Error('Required parameter "params[\'agentId\']" missing.'); + } + + if (params["offset"] === null || params["offset"] === undefined) { + throw new Error('Required parameter "params[\'offset\']" missing.'); + } + + let data: any = {}; + + + + data["CategoryId"] = params["categoryId"]; + + data["CategoryName"] = params["categoryName"]; + + data["Comment"] = params["comment"]; + + data["SegmentId"] = params["segmentId"]; + + data["AgentId"] = params["agentId"]; + + data["Offset"] = params["offset"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsAssessmentsCommentInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InsightsAssessmentsCommentListInstancePageOptions | ((error: Error | null, items: InsightsAssessmentsCommentPage) => any), callback?: (error: Error | null, items: InsightsAssessmentsCommentPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["segmentId"] !== undefined) + data["SegmentId"] = params["segmentId"]; + if (params["agentId"] !== undefined) + data["AgentId"] = params["agentId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InsightsAssessmentsCommentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsAssessmentsCommentPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InsightsAssessmentsCommentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InsightsAssessmentsCommentListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["segmentId"] !== undefined) + data["SegmentId"] = params["segmentId"]; + if (params["agentId"] !== undefined) + data["AgentId"] = params["agentId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsAssessmentsCommentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsAssessmentsCommentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface InsightsAssessmentsCommentPayload extends TwilioResponsePayload { + comments: InsightsAssessmentsCommentResource[]; +} + +interface InsightsAssessmentsCommentResource { + account_sid: string; + assessment_sid: string; + comment: any; + offset: string; + report: boolean; + weight: string; + agent_id: string; + segment_id: string; + user_name: string; + user_email: string; + timestamp: string; + url: string; +} + +export class InsightsAssessmentsCommentInstance { + + constructor(protected _version: V1, payload: InsightsAssessmentsCommentResource) { + + this.accountSid = (payload.account_sid); + this.assessmentSid = (payload.assessment_sid); + this.comment = (payload.comment); + this.offset = (payload.offset); + this.report = (payload.report); + this.weight = (payload.weight); + this.agentId = (payload.agent_id); + this.segmentId = (payload.segment_id); + this.userName = (payload.user_name); + this.userEmail = (payload.user_email); + this.timestamp = (payload.timestamp); + this.url = (payload.url); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + */ + accountSid: string; + /** + * The SID of the assessment. + */ + assessmentSid: string; + /** + * The comment added for assessment. + */ + comment: any; + /** + * The offset + */ + offset: string; + /** + * The flag indicating if this assessment is part of report + */ + report: boolean; + /** + * The weightage given to this comment + */ + weight: string; + /** + * The id of the agent. + */ + agentId: string; + /** + * The id of the segment. + */ + segmentId: string; + /** + * The name of the user. + */ + userName: string; + /** + * The email id of the user. + */ + userEmail: string; + /** + * The timestamp when the record is inserted + */ + timestamp: string; + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + assessmentSid: this.assessmentSid, + comment: this.comment, + offset: this.offset, + report: this.report, + weight: this.weight, + agentId: this.agentId, + segmentId: this.segmentId, + userName: this.userName, + userEmail: this.userEmail, + timestamp: this.timestamp, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class InsightsAssessmentsCommentPage extends Page { +/** +* Initialize the InsightsAssessmentsCommentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InsightsAssessmentsCommentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InsightsAssessmentsCommentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InsightsAssessmentsCommentResource): InsightsAssessmentsCommentInstance { + + return new InsightsAssessmentsCommentInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/insightsConversations.ts b/rest/flexApi/v1/insightsConversations.ts new file mode 100644 index 000000000..e41b324ec --- /dev/null +++ b/rest/flexApi/v1/insightsConversations.ts @@ -0,0 +1,417 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface InsightsConversationsListInstanceEachOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** Unique Id of the segment for which conversation details needs to be fetched */ + "segmentId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InsightsConversationsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InsightsConversationsListInstanceOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** Unique Id of the segment for which conversation details needs to be fetched */ + "segmentId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InsightsConversationsListInstancePageOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** Unique Id of the segment for which conversation details needs to be fetched */ + "segmentId"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface InsightsConversationsSolution { +} + +export interface InsightsConversationsListInstance { + _version: V1; + _solution: InsightsConversationsSolution; + _uri: string; + + + + + /** + * Streams InsightsConversationsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsConversationsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InsightsConversationsInstance, done: (err?: Error) => void) => void): void; + each(params: InsightsConversationsListInstanceEachOptions, callback?: (item: InsightsConversationsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InsightsConversationsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsConversationsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InsightsConversationsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InsightsConversationsListInstanceEachOptions, callback?: (item: InsightsConversationsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InsightsConversationsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsConversationsPage) => any): Promise; + /** + * Retrieve a single target page of InsightsConversationsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InsightsConversationsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsConversationsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InsightsConversationsInstance[]) => any): Promise; + list(params: InsightsConversationsListInstanceOptions, callback?: (error: Error | null, items: InsightsConversationsInstance[]) => any): Promise; + /** + * Lists InsightsConversationsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsConversationsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InsightsConversationsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InsightsConversationsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsConversationsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InsightsConversationsPage) => any): Promise; + page(params: InsightsConversationsListInstancePageOptions, callback?: (error: Error | null, items: InsightsConversationsPage) => any): Promise; + /** + * Retrieve a single page of InsightsConversationsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsConversationsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InsightsConversationsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InsightsConversationsListInstance(version: V1): InsightsConversationsListInstance { + const instance = {} as InsightsConversationsListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Insights/Conversations`; + + instance.page = function page(params?: InsightsConversationsListInstancePageOptions | ((error: Error | null, items: InsightsConversationsPage) => any), callback?: (error: Error | null, items: InsightsConversationsPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["segmentId"] !== undefined) + data["SegmentId"] = params["segmentId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InsightsConversationsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsConversationsPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InsightsConversationsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InsightsConversationsListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["segmentId"] !== undefined) + data["SegmentId"] = params["segmentId"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsConversationsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsConversationsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface InsightsConversationsPayload extends TwilioResponsePayload { + conversations: InsightsConversationsResource[]; +} + +interface InsightsConversationsResource { + account_id: string; + conversation_id: string; + segment_count: number; + segments: Array; +} + +export class InsightsConversationsInstance { + + constructor(protected _version: V1, payload: InsightsConversationsResource) { + + this.accountId = (payload.account_id); + this.conversationId = (payload.conversation_id); + this.segmentCount = deserialize.integer(payload.segment_count); + this.segments = (payload.segments); + + } + + /** + * The id of the account. + */ + accountId: string; + /** + * The unique id of the conversation + */ + conversationId: string; + /** + * The count of segments for a conversation + */ + segmentCount: number; + /** + * The Segments of a conversation + */ + segments: Array; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountId: this.accountId, + conversationId: this.conversationId, + segmentCount: this.segmentCount, + segments: this.segments, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class InsightsConversationsPage extends Page { +/** +* Initialize the InsightsConversationsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InsightsConversationsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InsightsConversationsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InsightsConversationsResource): InsightsConversationsInstance { + + return new InsightsConversationsInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/insightsQuestionnaires.ts b/rest/flexApi/v1/insightsQuestionnaires.ts new file mode 100644 index 000000000..9758a7e4b --- /dev/null +++ b/rest/flexApi/v1/insightsQuestionnaires.ts @@ -0,0 +1,1075 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to remove a InsightsQuestionnairesInstance + */ +export interface InsightsQuestionnairesContextRemoveOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +/** + * Options to pass to fetch a InsightsQuestionnairesInstance + */ +export interface InsightsQuestionnairesContextFetchOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +/** + * Options to pass to update a InsightsQuestionnairesInstance + */ +export interface InsightsQuestionnairesContextUpdateOptions { + /** The flag to enable or disable questionnaire */ + "active": boolean; + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The name of this questionnaire */ + "name"?: string; + /** The description of this questionnaire */ + "description"?: string; + /** The list of questions sids under a questionnaire */ + "questionSids"?: Array; +} + +/** + * Options to pass to create a InsightsQuestionnairesInstance + */ +export interface InsightsQuestionnairesListInstanceCreateOptions { + /** The name of this questionnaire */ + "name": string; + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The description of this questionnaire */ + "description"?: string; + /** The flag to enable or disable questionnaire */ + "active"?: boolean; + /** The list of questions sids under a questionnaire */ + "questionSids"?: Array; +} + +/** + * Options to pass to each + */ +export interface InsightsQuestionnairesListInstanceEachOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** Flag indicating whether to include inactive questionnaires or not */ + "includeInactive"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InsightsQuestionnairesInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InsightsQuestionnairesListInstanceOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** Flag indicating whether to include inactive questionnaires or not */ + "includeInactive"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InsightsQuestionnairesListInstancePageOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** Flag indicating whether to include inactive questionnaires or not */ + "includeInactive"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InsightsQuestionnairesContext { + + /** + * Remove a InsightsQuestionnairesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a InsightsQuestionnairesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance + */ + remove(params: InsightsQuestionnairesContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a InsightsQuestionnairesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a InsightsQuestionnairesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance with HTTP metadata + */ + removeWithHttpInfo(params: InsightsQuestionnairesContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a InsightsQuestionnairesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance + */ + fetch(callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise; + /** + * Fetch a InsightsQuestionnairesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance + */ + fetch(params: InsightsQuestionnairesContextFetchOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise; + + /** + * Fetch a InsightsQuestionnairesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a InsightsQuestionnairesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance with HTTP metadata + */ + fetchWithHttpInfo(params: InsightsQuestionnairesContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Update a InsightsQuestionnairesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance + */ + update(params: InsightsQuestionnairesContextUpdateOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise; + + /** + * Update a InsightsQuestionnairesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance with HTTP metadata + */ + updateWithHttpInfo(params: InsightsQuestionnairesContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InsightsQuestionnairesContextSolution { + "questionnaireSid": string; +} + +export class InsightsQuestionnairesContextImpl implements InsightsQuestionnairesContext { + protected _solution: InsightsQuestionnairesContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, questionnaireSid: string) { + if (!isValidPathParam(questionnaireSid)) { + throw new Error('Parameter \'questionnaireSid\' is not valid.'); + } + + this._solution = { questionnaireSid, }; + this._uri = `/Insights/QualityManagement/Questionnaires/${questionnaireSid}`; + } + + remove(params?: InsightsQuestionnairesContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: InsightsQuestionnairesContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(params?: InsightsQuestionnairesContextFetchOptions | ((error: Error | null, item?: InsightsQuestionnairesInstance) => any),callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsQuestionnairesInstance(operationVersion, payload, instance._solution.questionnaireSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: InsightsQuestionnairesContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsQuestionnairesInstance(operationVersion, response.body, instance._solution.questionnaireSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: InsightsQuestionnairesContextUpdateOptions,callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["active"] === null || params["active"] === undefined) { + throw new Error('Required parameter "params[\'active\']" missing.'); + } + + let data: any = {}; + + + + data["Active"] = serialize.bool(params["active"]); + if (params["name"] !== undefined) + data["Name"] = params["name"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["questionSids"] !== undefined) + data["QuestionSids"] = serialize.map(params["questionSids"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsQuestionnairesInstance(operationVersion, payload, instance._solution.questionnaireSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: InsightsQuestionnairesContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["active"] === null || params["active"] === undefined) { + throw new Error('Required parameter "params[\'active\']" missing.'); + } + + let data: any = {}; + + + + data["Active"] = serialize.bool(params["active"]); + if (params["name"] !== undefined) + data["Name"] = params["name"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["questionSids"] !== undefined) + data["QuestionSids"] = serialize.map(params["questionSids"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsQuestionnairesInstance(operationVersion, response.body, instance._solution.questionnaireSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InsightsQuestionnairesPayload extends TwilioResponsePayload { + questionnaires: InsightsQuestionnairesResource[]; +} + +interface InsightsQuestionnairesResource { + account_sid: string; + questionnaire_sid: string; + name: string; + description: string; + active: boolean; + questions: Array; + url: string; +} + +export class InsightsQuestionnairesInstance { + protected _solution: InsightsQuestionnairesContextSolution; + protected _context?: InsightsQuestionnairesContext; + + constructor(protected _version: V1, payload: InsightsQuestionnairesResource, questionnaireSid?: string) { + + this.accountSid = (payload.account_sid); + this.questionnaireSid = (payload.questionnaire_sid); + this.name = (payload.name); + this.description = (payload.description); + this.active = (payload.active); + this.questions = (payload.questions); + this.url = (payload.url); + + this._solution = { questionnaireSid: questionnaireSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + */ + accountSid: string; + /** + * The sid of this questionnaire + */ + questionnaireSid: string; + /** + * The name of this category. + */ + name: string; + /** + * The description of this questionnaire + */ + description: string; + /** + * The flag to enable or disable questionnaire + */ + active: boolean; + /** + * The list of questions with category for a questionnaire + */ + questions: Array; + url: string; + + private get _proxy(): InsightsQuestionnairesContext { + this._context = this._context || new InsightsQuestionnairesContextImpl(this._version, this._solution.questionnaireSid); + return this._context; + } + + /** + * Remove a InsightsQuestionnairesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a InsightsQuestionnairesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance + */ + remove(params: InsightsQuestionnairesContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a InsightsQuestionnairesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a InsightsQuestionnairesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance with HTTP metadata + */ + removeWithHttpInfo(params: InsightsQuestionnairesContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a InsightsQuestionnairesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance + */ + fetch(callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise; + /** + * Fetch a InsightsQuestionnairesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance + */ + fetch(params: InsightsQuestionnairesContextFetchOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a InsightsQuestionnairesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a InsightsQuestionnairesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance with HTTP metadata + */ + fetchWithHttpInfo(params: InsightsQuestionnairesContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Update a InsightsQuestionnairesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance + */ + update(params: InsightsQuestionnairesContextUpdateOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a InsightsQuestionnairesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance with HTTP metadata + */ + updateWithHttpInfo(params: InsightsQuestionnairesContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + questionnaireSid: this.questionnaireSid, + name: this.name, + description: this.description, + active: this.active, + questions: this.questions, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InsightsQuestionnairesSolution { +} + +export interface InsightsQuestionnairesListInstance { + _version: V1; + _solution: InsightsQuestionnairesSolution; + _uri: string; + + (questionnaireSid: string, ): InsightsQuestionnairesContext; + get(questionnaireSid: string, ): InsightsQuestionnairesContext; + + + + + + + + + /** + * Create a InsightsQuestionnairesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance + */ + create(params: InsightsQuestionnairesListInstanceCreateOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesInstance) => any): Promise; + + /** + * Create a InsightsQuestionnairesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsQuestionnairesListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams InsightsQuestionnairesInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InsightsQuestionnairesInstance, done: (err?: Error) => void) => void): void; + each(params: InsightsQuestionnairesListInstanceEachOptions, callback?: (item: InsightsQuestionnairesInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InsightsQuestionnairesInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InsightsQuestionnairesInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InsightsQuestionnairesListInstanceEachOptions, callback?: (item: InsightsQuestionnairesInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InsightsQuestionnairesInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsQuestionnairesPage) => any): Promise; + /** + * Retrieve a single target page of InsightsQuestionnairesInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InsightsQuestionnairesInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InsightsQuestionnairesInstance[]) => any): Promise; + list(params: InsightsQuestionnairesListInstanceOptions, callback?: (error: Error | null, items: InsightsQuestionnairesInstance[]) => any): Promise; + /** + * Lists InsightsQuestionnairesInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InsightsQuestionnairesListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InsightsQuestionnairesInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InsightsQuestionnairesPage) => any): Promise; + page(params: InsightsQuestionnairesListInstancePageOptions, callback?: (error: Error | null, items: InsightsQuestionnairesPage) => any): Promise; + /** + * Retrieve a single page of InsightsQuestionnairesInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InsightsQuestionnairesListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InsightsQuestionnairesListInstance(version: V1): InsightsQuestionnairesListInstance { + const instance = ((questionnaireSid, ) => instance.get(questionnaireSid, )) as InsightsQuestionnairesListInstance; + + instance.get = function get(questionnaireSid, ): InsightsQuestionnairesContext { + return new InsightsQuestionnairesContextImpl(version, questionnaireSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Insights/QualityManagement/Questionnaires`; + + instance.create = function create(params: InsightsQuestionnairesListInstanceCreateOptions, callback?: (error: Error | null, items: InsightsQuestionnairesInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["name"] === null || params["name"] === undefined) { + throw new Error('Required parameter "params[\'name\']" missing.'); + } + + let data: any = {}; + + + + data["Name"] = params["name"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["active"] !== undefined) + data["Active"] = serialize.bool(params["active"]); + if (params["questionSids"] !== undefined) + data["QuestionSids"] = serialize.map(params["questionSids"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsQuestionnairesInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InsightsQuestionnairesListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["name"] === null || params["name"] === undefined) { + throw new Error('Required parameter "params[\'name\']" missing.'); + } + + let data: any = {}; + + + + data["Name"] = params["name"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["active"] !== undefined) + data["Active"] = serialize.bool(params["active"]); + if (params["questionSids"] !== undefined) + data["QuestionSids"] = serialize.map(params["questionSids"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsQuestionnairesInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InsightsQuestionnairesListInstancePageOptions | ((error: Error | null, items: InsightsQuestionnairesPage) => any), callback?: (error: Error | null, items: InsightsQuestionnairesPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["includeInactive"] !== undefined) + data["IncludeInactive"] = serialize.bool(params["includeInactive"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InsightsQuestionnairesPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsQuestionnairesPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InsightsQuestionnairesPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InsightsQuestionnairesListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["includeInactive"] !== undefined) + data["IncludeInactive"] = serialize.bool(params["includeInactive"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsQuestionnairesPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsQuestionnairesPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InsightsQuestionnairesPage extends Page { +/** +* Initialize the InsightsQuestionnairesPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InsightsQuestionnairesSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InsightsQuestionnairesInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InsightsQuestionnairesResource): InsightsQuestionnairesInstance { + + return new InsightsQuestionnairesInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/insightsQuestionnairesCategory.ts b/rest/flexApi/v1/insightsQuestionnairesCategory.ts new file mode 100644 index 000000000..07e062331 --- /dev/null +++ b/rest/flexApi/v1/insightsQuestionnairesCategory.ts @@ -0,0 +1,851 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to remove a InsightsQuestionnairesCategoryInstance + */ +export interface InsightsQuestionnairesCategoryContextRemoveOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +/** + * Options to pass to update a InsightsQuestionnairesCategoryInstance + */ +export interface InsightsQuestionnairesCategoryContextUpdateOptions { + /** The name of this category. */ + "name": string; + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +/** + * Options to pass to create a InsightsQuestionnairesCategoryInstance + */ +export interface InsightsQuestionnairesCategoryListInstanceCreateOptions { + /** The name of this category. */ + "name": string; + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +/** + * Options to pass to each + */ +export interface InsightsQuestionnairesCategoryListInstanceEachOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InsightsQuestionnairesCategoryInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InsightsQuestionnairesCategoryListInstanceOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InsightsQuestionnairesCategoryListInstancePageOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InsightsQuestionnairesCategoryContext { + + /** + * Remove a InsightsQuestionnairesCategoryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a InsightsQuestionnairesCategoryInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesCategoryInstance + */ + remove(params: InsightsQuestionnairesCategoryContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a InsightsQuestionnairesCategoryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a InsightsQuestionnairesCategoryInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesCategoryInstance with HTTP metadata + */ + removeWithHttpInfo(params: InsightsQuestionnairesCategoryContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Update a InsightsQuestionnairesCategoryInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesCategoryInstance + */ + update(params: InsightsQuestionnairesCategoryContextUpdateOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesCategoryInstance) => any): Promise; + + /** + * Update a InsightsQuestionnairesCategoryInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesCategoryInstance with HTTP metadata + */ + updateWithHttpInfo(params: InsightsQuestionnairesCategoryContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InsightsQuestionnairesCategoryContextSolution { + "categorySid": string; +} + +export class InsightsQuestionnairesCategoryContextImpl implements InsightsQuestionnairesCategoryContext { + protected _solution: InsightsQuestionnairesCategoryContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, categorySid: string) { + if (!isValidPathParam(categorySid)) { + throw new Error('Parameter \'categorySid\' is not valid.'); + } + + this._solution = { categorySid, }; + this._uri = `/Insights/QualityManagement/Categories/${categorySid}`; + } + + remove(params?: InsightsQuestionnairesCategoryContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: InsightsQuestionnairesCategoryContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: InsightsQuestionnairesCategoryContextUpdateOptions,callback?: (error: Error | null, item?: InsightsQuestionnairesCategoryInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["name"] === null || params["name"] === undefined) { + throw new Error('Required parameter "params[\'name\']" missing.'); + } + + let data: any = {}; + + + + data["Name"] = params["name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsQuestionnairesCategoryInstance(operationVersion, payload, instance._solution.categorySid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: InsightsQuestionnairesCategoryContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["name"] === null || params["name"] === undefined) { + throw new Error('Required parameter "params[\'name\']" missing.'); + } + + let data: any = {}; + + + + data["Name"] = params["name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsQuestionnairesCategoryInstance(operationVersion, response.body, instance._solution.categorySid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InsightsQuestionnairesCategoryPayload extends TwilioResponsePayload { + categories: InsightsQuestionnairesCategoryResource[]; +} + +interface InsightsQuestionnairesCategoryResource { + account_sid: string; + category_sid: string; + name: string; + url: string; +} + +export class InsightsQuestionnairesCategoryInstance { + protected _solution: InsightsQuestionnairesCategoryContextSolution; + protected _context?: InsightsQuestionnairesCategoryContext; + + constructor(protected _version: V1, payload: InsightsQuestionnairesCategoryResource, categorySid?: string) { + + this.accountSid = (payload.account_sid); + this.categorySid = (payload.category_sid); + this.name = (payload.name); + this.url = (payload.url); + + this._solution = { categorySid: categorySid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + */ + accountSid: string; + /** + * The SID of the category + */ + categorySid: string; + /** + * The name of this category. + */ + name: string; + url: string; + + private get _proxy(): InsightsQuestionnairesCategoryContext { + this._context = this._context || new InsightsQuestionnairesCategoryContextImpl(this._version, this._solution.categorySid); + return this._context; + } + + /** + * Remove a InsightsQuestionnairesCategoryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a InsightsQuestionnairesCategoryInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesCategoryInstance + */ + remove(params: InsightsQuestionnairesCategoryContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a InsightsQuestionnairesCategoryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a InsightsQuestionnairesCategoryInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesCategoryInstance with HTTP metadata + */ + removeWithHttpInfo(params: InsightsQuestionnairesCategoryContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Update a InsightsQuestionnairesCategoryInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesCategoryInstance + */ + update(params: InsightsQuestionnairesCategoryContextUpdateOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesCategoryInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: InsightsQuestionnairesCategoryInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a InsightsQuestionnairesCategoryInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesCategoryInstance with HTTP metadata + */ + updateWithHttpInfo(params: InsightsQuestionnairesCategoryContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + categorySid: this.categorySid, + name: this.name, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InsightsQuestionnairesCategorySolution { +} + +export interface InsightsQuestionnairesCategoryListInstance { + _version: V1; + _solution: InsightsQuestionnairesCategorySolution; + _uri: string; + + (categorySid: string, ): InsightsQuestionnairesCategoryContext; + get(categorySid: string, ): InsightsQuestionnairesCategoryContext; + + + + + + + /** + * Create a InsightsQuestionnairesCategoryInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesCategoryInstance + */ + create(params: InsightsQuestionnairesCategoryListInstanceCreateOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesCategoryInstance) => any): Promise; + + /** + * Create a InsightsQuestionnairesCategoryInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesCategoryInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsQuestionnairesCategoryListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams InsightsQuestionnairesCategoryInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesCategoryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InsightsQuestionnairesCategoryInstance, done: (err?: Error) => void) => void): void; + each(params: InsightsQuestionnairesCategoryListInstanceEachOptions, callback?: (item: InsightsQuestionnairesCategoryInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InsightsQuestionnairesCategoryInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesCategoryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InsightsQuestionnairesCategoryInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InsightsQuestionnairesCategoryListInstanceEachOptions, callback?: (item: InsightsQuestionnairesCategoryInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InsightsQuestionnairesCategoryInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsQuestionnairesCategoryPage) => any): Promise; + /** + * Retrieve a single target page of InsightsQuestionnairesCategoryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InsightsQuestionnairesCategoryInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesCategoryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InsightsQuestionnairesCategoryInstance[]) => any): Promise; + list(params: InsightsQuestionnairesCategoryListInstanceOptions, callback?: (error: Error | null, items: InsightsQuestionnairesCategoryInstance[]) => any): Promise; + /** + * Lists InsightsQuestionnairesCategoryInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesCategoryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InsightsQuestionnairesCategoryListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InsightsQuestionnairesCategoryInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesCategoryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InsightsQuestionnairesCategoryPage) => any): Promise; + page(params: InsightsQuestionnairesCategoryListInstancePageOptions, callback?: (error: Error | null, items: InsightsQuestionnairesCategoryPage) => any): Promise; + /** + * Retrieve a single page of InsightsQuestionnairesCategoryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesCategoryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InsightsQuestionnairesCategoryListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InsightsQuestionnairesCategoryListInstance(version: V1): InsightsQuestionnairesCategoryListInstance { + const instance = ((categorySid, ) => instance.get(categorySid, )) as InsightsQuestionnairesCategoryListInstance; + + instance.get = function get(categorySid, ): InsightsQuestionnairesCategoryContext { + return new InsightsQuestionnairesCategoryContextImpl(version, categorySid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Insights/QualityManagement/Categories`; + + instance.create = function create(params: InsightsQuestionnairesCategoryListInstanceCreateOptions, callback?: (error: Error | null, items: InsightsQuestionnairesCategoryInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["name"] === null || params["name"] === undefined) { + throw new Error('Required parameter "params[\'name\']" missing.'); + } + + let data: any = {}; + + + + data["Name"] = params["name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsQuestionnairesCategoryInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InsightsQuestionnairesCategoryListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["name"] === null || params["name"] === undefined) { + throw new Error('Required parameter "params[\'name\']" missing.'); + } + + let data: any = {}; + + + + data["Name"] = params["name"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsQuestionnairesCategoryInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InsightsQuestionnairesCategoryListInstancePageOptions | ((error: Error | null, items: InsightsQuestionnairesCategoryPage) => any), callback?: (error: Error | null, items: InsightsQuestionnairesCategoryPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InsightsQuestionnairesCategoryPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsQuestionnairesCategoryPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InsightsQuestionnairesCategoryPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InsightsQuestionnairesCategoryListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsQuestionnairesCategoryPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsQuestionnairesCategoryPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InsightsQuestionnairesCategoryPage extends Page { +/** +* Initialize the InsightsQuestionnairesCategoryPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InsightsQuestionnairesCategorySolution) { + super(version, response, solution); + } + + /** + * Build an instance of InsightsQuestionnairesCategoryInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InsightsQuestionnairesCategoryResource): InsightsQuestionnairesCategoryInstance { + + return new InsightsQuestionnairesCategoryInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/insightsQuestionnairesQuestion.ts b/rest/flexApi/v1/insightsQuestionnairesQuestion.ts new file mode 100644 index 000000000..2cf8e0629 --- /dev/null +++ b/rest/flexApi/v1/insightsQuestionnairesQuestion.ts @@ -0,0 +1,975 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to remove a InsightsQuestionnairesQuestionInstance + */ +export interface InsightsQuestionnairesQuestionContextRemoveOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +/** + * Options to pass to update a InsightsQuestionnairesQuestionInstance + */ +export interface InsightsQuestionnairesQuestionContextUpdateOptions { + /** The flag to enable for disable NA for answer. */ + "allowNa": boolean; + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The SID of the category */ + "categorySid"?: string; + /** The question. */ + "question"?: string; + /** The description for the question. */ + "description"?: string; + /** The answer_set for the question. */ + "answerSetId"?: string; +} + +/** + * Options to pass to create a InsightsQuestionnairesQuestionInstance + */ +export interface InsightsQuestionnairesQuestionListInstanceCreateOptions { + /** The SID of the category */ + "categorySid": string; + /** The question. */ + "question": string; + /** The answer_set for the question. */ + "answerSetId": string; + /** The flag to enable for disable NA for answer. */ + "allowNa": boolean; + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The description for the question. */ + "description"?: string; +} + +/** + * Options to pass to each + */ +export interface InsightsQuestionnairesQuestionListInstanceEachOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The list of category SIDs */ + "categorySid"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InsightsQuestionnairesQuestionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InsightsQuestionnairesQuestionListInstanceOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The list of category SIDs */ + "categorySid"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InsightsQuestionnairesQuestionListInstancePageOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** The list of category SIDs */ + "categorySid"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InsightsQuestionnairesQuestionContext { + + /** + * Remove a InsightsQuestionnairesQuestionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a InsightsQuestionnairesQuestionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesQuestionInstance + */ + remove(params: InsightsQuestionnairesQuestionContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a InsightsQuestionnairesQuestionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a InsightsQuestionnairesQuestionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesQuestionInstance with HTTP metadata + */ + removeWithHttpInfo(params: InsightsQuestionnairesQuestionContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Update a InsightsQuestionnairesQuestionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesQuestionInstance + */ + update(params: InsightsQuestionnairesQuestionContextUpdateOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesQuestionInstance) => any): Promise; + + /** + * Update a InsightsQuestionnairesQuestionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesQuestionInstance with HTTP metadata + */ + updateWithHttpInfo(params: InsightsQuestionnairesQuestionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InsightsQuestionnairesQuestionContextSolution { + "questionSid": string; +} + +export class InsightsQuestionnairesQuestionContextImpl implements InsightsQuestionnairesQuestionContext { + protected _solution: InsightsQuestionnairesQuestionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, questionSid: string) { + if (!isValidPathParam(questionSid)) { + throw new Error('Parameter \'questionSid\' is not valid.'); + } + + this._solution = { questionSid, }; + this._uri = `/Insights/QualityManagement/Questions/${questionSid}`; + } + + remove(params?: InsightsQuestionnairesQuestionContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: InsightsQuestionnairesQuestionContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: InsightsQuestionnairesQuestionContextUpdateOptions,callback?: (error: Error | null, item?: InsightsQuestionnairesQuestionInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["allowNa"] === null || params["allowNa"] === undefined) { + throw new Error('Required parameter "params[\'allowNa\']" missing.'); + } + + let data: any = {}; + + + + data["AllowNa"] = serialize.bool(params["allowNa"]); + if (params["categorySid"] !== undefined) + data["CategorySid"] = params["categorySid"]; + if (params["question"] !== undefined) + data["Question"] = params["question"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["answerSetId"] !== undefined) + data["AnswerSetId"] = params["answerSetId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsQuestionnairesQuestionInstance(operationVersion, payload, instance._solution.questionSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: InsightsQuestionnairesQuestionContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["allowNa"] === null || params["allowNa"] === undefined) { + throw new Error('Required parameter "params[\'allowNa\']" missing.'); + } + + let data: any = {}; + + + + data["AllowNa"] = serialize.bool(params["allowNa"]); + if (params["categorySid"] !== undefined) + data["CategorySid"] = params["categorySid"]; + if (params["question"] !== undefined) + data["Question"] = params["question"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["answerSetId"] !== undefined) + data["AnswerSetId"] = params["answerSetId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsQuestionnairesQuestionInstance(operationVersion, response.body, instance._solution.questionSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InsightsQuestionnairesQuestionPayload extends TwilioResponsePayload { + questions: InsightsQuestionnairesQuestionResource[]; +} + +interface InsightsQuestionnairesQuestionResource { + account_sid: string; + question_sid: string; + question: string; + description: string; + category: any; + answer_set_id: string; + allow_na: boolean; + usage: number; + answer_set: any; + url: string; +} + +export class InsightsQuestionnairesQuestionInstance { + protected _solution: InsightsQuestionnairesQuestionContextSolution; + protected _context?: InsightsQuestionnairesQuestionContext; + + constructor(protected _version: V1, payload: InsightsQuestionnairesQuestionResource, questionSid?: string) { + + this.accountSid = (payload.account_sid); + this.questionSid = (payload.question_sid); + this.question = (payload.question); + this.description = (payload.description); + this.category = (payload.category); + this.answerSetId = (payload.answer_set_id); + this.allowNa = (payload.allow_na); + this.usage = deserialize.integer(payload.usage); + this.answerSet = (payload.answer_set); + this.url = (payload.url); + + this._solution = { questionSid: questionSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + */ + accountSid: string; + /** + * The SID of the question + */ + questionSid: string; + /** + * The question. + */ + question: string; + /** + * The description for the question. + */ + description: string; + /** + * The Category for the question. + */ + category: any; + /** + * The answer_set for the question. + */ + answerSetId: string; + /** + * The flag to enable for disable NA for answer. + */ + allowNa: boolean; + /** + * Integer value that tells a particular question is used by how many questionnaires + */ + usage: number; + /** + * Set of answers for the question + */ + answerSet: any; + url: string; + + private get _proxy(): InsightsQuestionnairesQuestionContext { + this._context = this._context || new InsightsQuestionnairesQuestionContextImpl(this._version, this._solution.questionSid); + return this._context; + } + + /** + * Remove a InsightsQuestionnairesQuestionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a InsightsQuestionnairesQuestionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesQuestionInstance + */ + remove(params: InsightsQuestionnairesQuestionContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a InsightsQuestionnairesQuestionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a InsightsQuestionnairesQuestionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesQuestionInstance with HTTP metadata + */ + removeWithHttpInfo(params: InsightsQuestionnairesQuestionContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Update a InsightsQuestionnairesQuestionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesQuestionInstance + */ + update(params: InsightsQuestionnairesQuestionContextUpdateOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesQuestionInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: InsightsQuestionnairesQuestionInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a InsightsQuestionnairesQuestionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesQuestionInstance with HTTP metadata + */ + updateWithHttpInfo(params: InsightsQuestionnairesQuestionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + questionSid: this.questionSid, + question: this.question, + description: this.description, + category: this.category, + answerSetId: this.answerSetId, + allowNa: this.allowNa, + usage: this.usage, + answerSet: this.answerSet, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InsightsQuestionnairesQuestionSolution { +} + +export interface InsightsQuestionnairesQuestionListInstance { + _version: V1; + _solution: InsightsQuestionnairesQuestionSolution; + _uri: string; + + (questionSid: string, ): InsightsQuestionnairesQuestionContext; + get(questionSid: string, ): InsightsQuestionnairesQuestionContext; + + + + + + + /** + * Create a InsightsQuestionnairesQuestionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesQuestionInstance + */ + create(params: InsightsQuestionnairesQuestionListInstanceCreateOptions, callback?: (error: Error | null, item?: InsightsQuestionnairesQuestionInstance) => any): Promise; + + /** + * Create a InsightsQuestionnairesQuestionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsQuestionnairesQuestionInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsQuestionnairesQuestionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams InsightsQuestionnairesQuestionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesQuestionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InsightsQuestionnairesQuestionInstance, done: (err?: Error) => void) => void): void; + each(params: InsightsQuestionnairesQuestionListInstanceEachOptions, callback?: (item: InsightsQuestionnairesQuestionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InsightsQuestionnairesQuestionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesQuestionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InsightsQuestionnairesQuestionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InsightsQuestionnairesQuestionListInstanceEachOptions, callback?: (item: InsightsQuestionnairesQuestionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InsightsQuestionnairesQuestionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsQuestionnairesQuestionPage) => any): Promise; + /** + * Retrieve a single target page of InsightsQuestionnairesQuestionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InsightsQuestionnairesQuestionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesQuestionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InsightsQuestionnairesQuestionInstance[]) => any): Promise; + list(params: InsightsQuestionnairesQuestionListInstanceOptions, callback?: (error: Error | null, items: InsightsQuestionnairesQuestionInstance[]) => any): Promise; + /** + * Lists InsightsQuestionnairesQuestionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesQuestionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InsightsQuestionnairesQuestionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InsightsQuestionnairesQuestionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesQuestionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InsightsQuestionnairesQuestionPage) => any): Promise; + page(params: InsightsQuestionnairesQuestionListInstancePageOptions, callback?: (error: Error | null, items: InsightsQuestionnairesQuestionPage) => any): Promise; + /** + * Retrieve a single page of InsightsQuestionnairesQuestionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsQuestionnairesQuestionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InsightsQuestionnairesQuestionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InsightsQuestionnairesQuestionListInstance(version: V1): InsightsQuestionnairesQuestionListInstance { + const instance = ((questionSid, ) => instance.get(questionSid, )) as InsightsQuestionnairesQuestionListInstance; + + instance.get = function get(questionSid, ): InsightsQuestionnairesQuestionContext { + return new InsightsQuestionnairesQuestionContextImpl(version, questionSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Insights/QualityManagement/Questions`; + + instance.create = function create(params: InsightsQuestionnairesQuestionListInstanceCreateOptions, callback?: (error: Error | null, items: InsightsQuestionnairesQuestionInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["categorySid"] === null || params["categorySid"] === undefined) { + throw new Error('Required parameter "params[\'categorySid\']" missing.'); + } + + if (params["question"] === null || params["question"] === undefined) { + throw new Error('Required parameter "params[\'question\']" missing.'); + } + + if (params["answerSetId"] === null || params["answerSetId"] === undefined) { + throw new Error('Required parameter "params[\'answerSetId\']" missing.'); + } + + if (params["allowNa"] === null || params["allowNa"] === undefined) { + throw new Error('Required parameter "params[\'allowNa\']" missing.'); + } + + let data: any = {}; + + + + data["CategorySid"] = params["categorySid"]; + + data["Question"] = params["question"]; + + data["AnswerSetId"] = params["answerSetId"]; + + data["AllowNa"] = serialize.bool(params["allowNa"]); + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsQuestionnairesQuestionInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InsightsQuestionnairesQuestionListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["categorySid"] === null || params["categorySid"] === undefined) { + throw new Error('Required parameter "params[\'categorySid\']" missing.'); + } + + if (params["question"] === null || params["question"] === undefined) { + throw new Error('Required parameter "params[\'question\']" missing.'); + } + + if (params["answerSetId"] === null || params["answerSetId"] === undefined) { + throw new Error('Required parameter "params[\'answerSetId\']" missing.'); + } + + if (params["allowNa"] === null || params["allowNa"] === undefined) { + throw new Error('Required parameter "params[\'allowNa\']" missing.'); + } + + let data: any = {}; + + + + data["CategorySid"] = params["categorySid"]; + + data["Question"] = params["question"]; + + data["AnswerSetId"] = params["answerSetId"]; + + data["AllowNa"] = serialize.bool(params["allowNa"]); + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsQuestionnairesQuestionInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InsightsQuestionnairesQuestionListInstancePageOptions | ((error: Error | null, items: InsightsQuestionnairesQuestionPage) => any), callback?: (error: Error | null, items: InsightsQuestionnairesQuestionPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["categorySid"] !== undefined) + data["CategorySid"] = serialize.map(params["categorySid"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InsightsQuestionnairesQuestionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsQuestionnairesQuestionPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InsightsQuestionnairesQuestionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InsightsQuestionnairesQuestionListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["categorySid"] !== undefined) + data["CategorySid"] = serialize.map(params["categorySid"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsQuestionnairesQuestionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsQuestionnairesQuestionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InsightsQuestionnairesQuestionPage extends Page { +/** +* Initialize the InsightsQuestionnairesQuestionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InsightsQuestionnairesQuestionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InsightsQuestionnairesQuestionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InsightsQuestionnairesQuestionResource): InsightsQuestionnairesQuestionInstance { + + return new InsightsQuestionnairesQuestionInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/insightsSegments.ts b/rest/flexApi/v1/insightsSegments.ts new file mode 100644 index 000000000..2fa822995 --- /dev/null +++ b/rest/flexApi/v1/insightsSegments.ts @@ -0,0 +1,544 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface InsightsSegmentsListInstanceEachOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** To unique id of the segment */ + "segmentId"?: string; + /** The list of reservation Ids */ + "reservationId"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InsightsSegmentsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InsightsSegmentsListInstanceOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** To unique id of the segment */ + "segmentId"?: string; + /** The list of reservation Ids */ + "reservationId"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InsightsSegmentsListInstancePageOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; + /** To unique id of the segment */ + "segmentId"?: string; + /** The list of reservation Ids */ + "reservationId"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface InsightsSegmentsSolution { +} + +export interface InsightsSegmentsListInstance { + _version: V1; + _solution: InsightsSegmentsSolution; + _uri: string; + + + + + /** + * Streams InsightsSegmentsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsSegmentsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InsightsSegmentsInstance, done: (err?: Error) => void) => void): void; + each(params: InsightsSegmentsListInstanceEachOptions, callback?: (item: InsightsSegmentsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InsightsSegmentsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsSegmentsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InsightsSegmentsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InsightsSegmentsListInstanceEachOptions, callback?: (item: InsightsSegmentsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InsightsSegmentsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsSegmentsPage) => any): Promise; + /** + * Retrieve a single target page of InsightsSegmentsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InsightsSegmentsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsSegmentsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InsightsSegmentsInstance[]) => any): Promise; + list(params: InsightsSegmentsListInstanceOptions, callback?: (error: Error | null, items: InsightsSegmentsInstance[]) => any): Promise; + /** + * Lists InsightsSegmentsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsSegmentsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InsightsSegmentsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InsightsSegmentsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsSegmentsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InsightsSegmentsPage) => any): Promise; + page(params: InsightsSegmentsListInstancePageOptions, callback?: (error: Error | null, items: InsightsSegmentsPage) => any): Promise; + /** + * Retrieve a single page of InsightsSegmentsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InsightsSegmentsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InsightsSegmentsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InsightsSegmentsListInstance(version: V1): InsightsSegmentsListInstance { + const instance = {} as InsightsSegmentsListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Insights/Segments`; + + instance.page = function page(params?: InsightsSegmentsListInstancePageOptions | ((error: Error | null, items: InsightsSegmentsPage) => any), callback?: (error: Error | null, items: InsightsSegmentsPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["segmentId"] !== undefined) + data["SegmentId"] = params["segmentId"]; + if (params["reservationId"] !== undefined) + data["ReservationId"] = serialize.map(params["reservationId"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InsightsSegmentsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InsightsSegmentsPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InsightsSegmentsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InsightsSegmentsListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["segmentId"] !== undefined) + data["SegmentId"] = params["segmentId"]; + if (params["reservationId"] !== undefined) + data["ReservationId"] = serialize.map(params["reservationId"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsSegmentsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InsightsSegmentsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface InsightsSegmentsPayload extends TwilioResponsePayload { + segments: InsightsSegmentsResource[]; +} + +interface InsightsSegmentsResource { + segment_id: string; + external_id: string; + queue: string; + external_contact: string; + external_segment_link_id: string; + date: string; + account_id: string; + external_segment_link: string; + agent_id: string; + agent_phone: string; + agent_name: string; + agent_team_name: string; + agent_team_name_in_hierarchy: string; + agent_link: string; + customer_phone: string; + customer_name: string; + customer_link: string; + segment_recording_offset: string; + media: any; + assessment_type: any; + assessment_percentage: any; + url: string; +} + +export class InsightsSegmentsInstance { + + constructor(protected _version: V1, payload: InsightsSegmentsResource) { + + this.segmentId = (payload.segment_id); + this.externalId = (payload.external_id); + this.queue = (payload.queue); + this.externalContact = (payload.external_contact); + this.externalSegmentLinkId = (payload.external_segment_link_id); + this.date = (payload.date); + this.accountId = (payload.account_id); + this.externalSegmentLink = (payload.external_segment_link); + this.agentId = (payload.agent_id); + this.agentPhone = (payload.agent_phone); + this.agentName = (payload.agent_name); + this.agentTeamName = (payload.agent_team_name); + this.agentTeamNameInHierarchy = (payload.agent_team_name_in_hierarchy); + this.agentLink = (payload.agent_link); + this.customerPhone = (payload.customer_phone); + this.customerName = (payload.customer_name); + this.customerLink = (payload.customer_link); + this.segmentRecordingOffset = (payload.segment_recording_offset); + this.media = (payload.media); + this.assessmentType = (payload.assessment_type); + this.assessmentPercentage = (payload.assessment_percentage); + this.url = (payload.url); + + } + + /** + * To unique id of the segment + */ + segmentId: string; + /** + * The unique id for the conversation. + */ + externalId: string; + queue: string; + externalContact: string; + /** + * The uuid for the external_segment_link. + */ + externalSegmentLinkId: string; + /** + * The date of the conversation. + */ + date: string; + /** + * The unique id for the account. + */ + accountId: string; + /** + * The hyperlink to recording of the task event. + */ + externalSegmentLink: string; + /** + * The unique id for the agent. + */ + agentId: string; + /** + * The phone number of the agent. + */ + agentPhone: string; + /** + * The name of the agent. + */ + agentName: string; + /** + * The team name to which agent belongs. + */ + agentTeamName: string; + /** + * he team name to which agent belongs. + */ + agentTeamNameInHierarchy: string; + /** + * The link to the agent conversation. + */ + agentLink: string; + /** + * The phone number of the customer. + */ + customerPhone: string; + /** + * The name of the customer. + */ + customerName: string; + /** + * The link to the customer conversation. + */ + customerLink: string; + /** + * The offset value for the recording. + */ + segmentRecordingOffset: string; + /** + * The media identifiers of the conversation. + */ + media: any; + /** + * The type of the assessment. + */ + assessmentType: any; + /** + * The percentage scored on the Assessments. + */ + assessmentPercentage: any; + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + segmentId: this.segmentId, + externalId: this.externalId, + queue: this.queue, + externalContact: this.externalContact, + externalSegmentLinkId: this.externalSegmentLinkId, + date: this.date, + accountId: this.accountId, + externalSegmentLink: this.externalSegmentLink, + agentId: this.agentId, + agentPhone: this.agentPhone, + agentName: this.agentName, + agentTeamName: this.agentTeamName, + agentTeamNameInHierarchy: this.agentTeamNameInHierarchy, + agentLink: this.agentLink, + customerPhone: this.customerPhone, + customerName: this.customerName, + customerLink: this.customerLink, + segmentRecordingOffset: this.segmentRecordingOffset, + media: this.media, + assessmentType: this.assessmentType, + assessmentPercentage: this.assessmentPercentage, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class InsightsSegmentsPage extends Page { +/** +* Initialize the InsightsSegmentsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InsightsSegmentsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InsightsSegmentsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InsightsSegmentsResource): InsightsSegmentsInstance { + + return new InsightsSegmentsInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/insightsSession.ts b/rest/flexApi/v1/insightsSession.ts new file mode 100644 index 000000000..9314f4a01 --- /dev/null +++ b/rest/flexApi/v1/insightsSession.ts @@ -0,0 +1,332 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a InsightsSessionInstance + */ +export interface InsightsSessionContextCreateOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +export interface InsightsSessionContext { + + /** + * Create a InsightsSessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSessionInstance + */ + create(callback?: (error: Error | null, item?: InsightsSessionInstance) => any): Promise; + /** + * Create a InsightsSessionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSessionInstance + */ + create(params: InsightsSessionContextCreateOptions, callback?: (error: Error | null, item?: InsightsSessionInstance) => any): Promise; + + /** + * Create a InsightsSessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSessionInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a InsightsSessionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSessionInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsSessionContextCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InsightsSessionContextSolution { +} + +export class InsightsSessionContextImpl implements InsightsSessionContext { + protected _solution: InsightsSessionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/Insights/Session`; + } + + create(params?: InsightsSessionContextCreateOptions | ((error: Error | null, item?: InsightsSessionInstance) => any),callback?: (error: Error | null, item?: InsightsSessionInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsSessionInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params?: InsightsSessionContextCreateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsSessionInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InsightsSessionPayload extends InsightsSessionResource {} + +interface InsightsSessionResource { + workspace_id: string; + session_expiry: string; + session_id: string; + base_url: string; + url: string; +} + +export class InsightsSessionInstance { + protected _solution: InsightsSessionContextSolution; + protected _context?: InsightsSessionContext; + + constructor(protected _version: V1, payload: InsightsSessionResource) { + + this.workspaceId = (payload.workspace_id); + this.sessionExpiry = (payload.session_expiry); + this.sessionId = (payload.session_id); + this.baseUrl = (payload.base_url); + this.url = (payload.url); + + this._solution = { }; + } + + /** + * Unique ID to identify the user\'s workspace + */ + workspaceId: string; + /** + * The session expiry date and time, given in ISO 8601 format. + */ + sessionExpiry: string; + /** + * The unique ID for the session + */ + sessionId: string; + /** + * The base URL to fetch reports and dashboards + */ + baseUrl: string; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): InsightsSessionContext { + this._context = this._context || new InsightsSessionContextImpl(this._version); + return this._context; + } + + /** + * Create a InsightsSessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSessionInstance + */ + create(callback?: (error: Error | null, item?: InsightsSessionInstance) => any): Promise; + /** + * Create a InsightsSessionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSessionInstance + */ + create(params: InsightsSessionContextCreateOptions, callback?: (error: Error | null, item?: InsightsSessionInstance) => any): Promise; + + create(params?: any, callback?: (error: Error | null, item?: InsightsSessionInstance) => any): Promise + { + return this._proxy.create(params, callback); + } + + /** + * Create a InsightsSessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSessionInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a InsightsSessionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSessionInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsSessionContextCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + workspaceId: this.workspaceId, + sessionExpiry: this.sessionExpiry, + sessionId: this.sessionId, + baseUrl: this.baseUrl, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InsightsSessionSolution { +} + +export interface InsightsSessionListInstance { + _version: V1; + _solution: InsightsSessionSolution; + _uri: string; + + (): InsightsSessionContext; + get(): InsightsSessionContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InsightsSessionListInstance(version: V1): InsightsSessionListInstance { + const instance = (() => instance.get()) as InsightsSessionListInstance; + + instance.get = function get(): InsightsSessionContext { + return new InsightsSessionContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/flexApi/v1/insightsSettingsAnswerSets.ts b/rest/flexApi/v1/insightsSettingsAnswerSets.ts new file mode 100644 index 000000000..7ef87a9da --- /dev/null +++ b/rest/flexApi/v1/insightsSettingsAnswerSets.ts @@ -0,0 +1,230 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a InsightsSettingsAnswerSetsInstance + */ +export interface InsightsSettingsAnswerSetsListInstanceFetchOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; +} + + +export interface InsightsSettingsAnswerSetsSolution { +} + +export interface InsightsSettingsAnswerSetsListInstance { + _version: V1; + _solution: InsightsSettingsAnswerSetsSolution; + _uri: string; + + + + /** + * Fetch a InsightsSettingsAnswerSetsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSettingsAnswerSetsInstance + */ + fetch(callback?: (error: Error | null, item?: InsightsSettingsAnswerSetsInstance) => any): Promise; + /** + * Fetch a InsightsSettingsAnswerSetsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSettingsAnswerSetsInstance + */ + fetch(params: InsightsSettingsAnswerSetsListInstanceFetchOptions, callback?: (error: Error | null, item?: InsightsSettingsAnswerSetsInstance) => any): Promise; + + /** + * Fetch a InsightsSettingsAnswerSetsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSettingsAnswerSetsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a InsightsSettingsAnswerSetsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSettingsAnswerSetsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: InsightsSettingsAnswerSetsListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InsightsSettingsAnswerSetsListInstance(version: V1): InsightsSettingsAnswerSetsListInstance { + const instance = {} as InsightsSettingsAnswerSetsListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Insights/QualityManagement/Settings/AnswerSets`; + + instance.fetch = function fetch(params?: InsightsSettingsAnswerSetsListInstanceFetchOptions | ((error: Error | null, items: InsightsSettingsAnswerSetsInstance) => any), callback?: (error: Error | null, items: InsightsSettingsAnswerSetsInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsSettingsAnswerSetsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params?: InsightsSettingsAnswerSetsListInstanceFetchOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsSettingsAnswerSetsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface InsightsSettingsAnswerSetsPayload extends InsightsSettingsAnswerSetsResource {} + +interface InsightsSettingsAnswerSetsResource { + account_sid: string; + answer_sets: any; + answer_set_categories: any; + not_applicable: any; + url: string; +} + +export class InsightsSettingsAnswerSetsInstance { + + constructor(protected _version: V1, payload: InsightsSettingsAnswerSetsResource) { + + this.accountSid = (payload.account_sid); + this.answerSets = (payload.answer_sets); + this.answerSetCategories = (payload.answer_set_categories); + this.notApplicable = (payload.not_applicable); + this.url = (payload.url); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + */ + accountSid: string; + /** + * The lis of answer sets + */ + answerSets: any; + /** + * The list of answer set categories + */ + answerSetCategories: any; + /** + * The details for not applicable answer set + */ + notApplicable: any; + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + answerSets: this.answerSets, + answerSetCategories: this.answerSetCategories, + notApplicable: this.notApplicable, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/flexApi/v1/insightsSettingsComment.ts b/rest/flexApi/v1/insightsSettingsComment.ts new file mode 100644 index 000000000..84d79360b --- /dev/null +++ b/rest/flexApi/v1/insightsSettingsComment.ts @@ -0,0 +1,213 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a InsightsSettingsCommentInstance + */ +export interface InsightsSettingsCommentListInstanceFetchOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; +} + + +export interface InsightsSettingsCommentSolution { +} + +export interface InsightsSettingsCommentListInstance { + _version: V1; + _solution: InsightsSettingsCommentSolution; + _uri: string; + + + + /** + * Fetch a InsightsSettingsCommentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSettingsCommentInstance + */ + fetch(callback?: (error: Error | null, item?: InsightsSettingsCommentInstance) => any): Promise; + /** + * Fetch a InsightsSettingsCommentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSettingsCommentInstance + */ + fetch(params: InsightsSettingsCommentListInstanceFetchOptions, callback?: (error: Error | null, item?: InsightsSettingsCommentInstance) => any): Promise; + + /** + * Fetch a InsightsSettingsCommentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSettingsCommentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a InsightsSettingsCommentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsSettingsCommentInstance with HTTP metadata + */ + fetchWithHttpInfo(params: InsightsSettingsCommentListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InsightsSettingsCommentListInstance(version: V1): InsightsSettingsCommentListInstance { + const instance = {} as InsightsSettingsCommentListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Insights/QualityManagement/Settings/CommentTags`; + + instance.fetch = function fetch(params?: InsightsSettingsCommentListInstanceFetchOptions | ((error: Error | null, items: InsightsSettingsCommentInstance) => any), callback?: (error: Error | null, items: InsightsSettingsCommentInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsSettingsCommentInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params?: InsightsSettingsCommentListInstanceFetchOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsSettingsCommentInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface InsightsSettingsCommentPayload extends InsightsSettingsCommentResource {} + +interface InsightsSettingsCommentResource { + account_sid: string; + comments: any; + url: string; +} + +export class InsightsSettingsCommentInstance { + + constructor(protected _version: V1, payload: InsightsSettingsCommentResource) { + + this.accountSid = (payload.account_sid); + this.comments = (payload.comments); + this.url = (payload.url); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + */ + accountSid: string; + comments: any; + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + comments: this.comments, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/flexApi/v1/insightsUserRoles.ts b/rest/flexApi/v1/insightsUserRoles.ts new file mode 100644 index 000000000..235a0fef4 --- /dev/null +++ b/rest/flexApi/v1/insightsUserRoles.ts @@ -0,0 +1,308 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a InsightsUserRolesInstance + */ +export interface InsightsUserRolesContextFetchOptions { + /** The Authorization HTTP request header */ + "authorization"?: string; +} + +export interface InsightsUserRolesContext { + + /** + * Fetch a InsightsUserRolesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsUserRolesInstance + */ + fetch(callback?: (error: Error | null, item?: InsightsUserRolesInstance) => any): Promise; + /** + * Fetch a InsightsUserRolesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsUserRolesInstance + */ + fetch(params: InsightsUserRolesContextFetchOptions, callback?: (error: Error | null, item?: InsightsUserRolesInstance) => any): Promise; + + /** + * Fetch a InsightsUserRolesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsUserRolesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a InsightsUserRolesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsUserRolesInstance with HTTP metadata + */ + fetchWithHttpInfo(params: InsightsUserRolesContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InsightsUserRolesContextSolution { +} + +export class InsightsUserRolesContextImpl implements InsightsUserRolesContext { + protected _solution: InsightsUserRolesContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/Insights/UserRoles`; + } + + fetch(params?: InsightsUserRolesContextFetchOptions | ((error: Error | null, item?: InsightsUserRolesInstance) => any),callback?: (error: Error | null, item?: InsightsUserRolesInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new InsightsUserRolesInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: InsightsUserRolesContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["authorization"] !== undefined) headers["Authorization"] = params["authorization"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InsightsUserRolesInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InsightsUserRolesPayload extends InsightsUserRolesResource {} + +interface InsightsUserRolesResource { + roles: Array; + url: string; +} + +export class InsightsUserRolesInstance { + protected _solution: InsightsUserRolesContextSolution; + protected _context?: InsightsUserRolesContext; + + constructor(protected _version: V1, payload: InsightsUserRolesResource) { + + this.roles = (payload.roles); + this.url = (payload.url); + + this._solution = { }; + } + + /** + * Flex Insights roles for the user + */ + roles: Array; + url: string; + + private get _proxy(): InsightsUserRolesContext { + this._context = this._context || new InsightsUserRolesContextImpl(this._version); + return this._context; + } + + /** + * Fetch a InsightsUserRolesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsUserRolesInstance + */ + fetch(callback?: (error: Error | null, item?: InsightsUserRolesInstance) => any): Promise; + /** + * Fetch a InsightsUserRolesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsUserRolesInstance + */ + fetch(params: InsightsUserRolesContextFetchOptions, callback?: (error: Error | null, item?: InsightsUserRolesInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: InsightsUserRolesInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a InsightsUserRolesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsUserRolesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a InsightsUserRolesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InsightsUserRolesInstance with HTTP metadata + */ + fetchWithHttpInfo(params: InsightsUserRolesContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + roles: this.roles, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InsightsUserRolesSolution { +} + +export interface InsightsUserRolesListInstance { + _version: V1; + _solution: InsightsUserRolesSolution; + _uri: string; + + (): InsightsUserRolesContext; + get(): InsightsUserRolesContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InsightsUserRolesListInstance(version: V1): InsightsUserRolesListInstance { + const instance = (() => instance.get()) as InsightsUserRolesListInstance; + + instance.get = function get(): InsightsUserRolesContext { + return new InsightsUserRolesContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/flexApi/v1/interaction.ts b/rest/flexApi/v1/interaction.ts new file mode 100644 index 000000000..f6d2ab230 --- /dev/null +++ b/rest/flexApi/v1/interaction.ts @@ -0,0 +1,557 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { InteractionChannelListInstance } from "./interaction/interactionChannel"; + + + + +/** + * Options to pass to update a InteractionInstance + */ +export interface InteractionContextUpdateOptions { + /** The unique identifier for Interaction level webhook */ + "webhookTtid"?: string; +} + +/** + * Options to pass to create a InteractionInstance + */ +export interface InteractionListInstanceCreateOptions { + /** The Interaction\\\'s channel. */ + "channel": any; + /** The Interaction\\\'s routing logic. */ + "routing"?: any; + /** The Interaction context sid is used for adding a context lookup sid */ + "interactionContextSid"?: string; + /** The unique identifier for Interaction level webhook */ + "webhookTtid"?: string; +} + +export interface InteractionContext { + channels: InteractionChannelListInstance; + + /** + * Fetch a InteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance + */ + fetch(callback?: (error: Error | null, item?: InteractionInstance) => any): Promise + + /** + * Fetch a InteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a InteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance + */ + update(callback?: (error: Error | null, item?: InteractionInstance) => any): Promise; + /** + * Update a InteractionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance + */ + update(params: InteractionContextUpdateOptions, callback?: (error: Error | null, item?: InteractionInstance) => any): Promise; + + /** + * Update a InteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a InteractionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance with HTTP metadata + */ + updateWithHttpInfo(params: InteractionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InteractionContextSolution { + "sid": string; +} + +export class InteractionContextImpl implements InteractionContext { + protected _solution: InteractionContextSolution; + protected _uri: string; + + protected _channels?: InteractionChannelListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Interactions/${sid}`; + } + + get channels(): InteractionChannelListInstance { + this._channels = this._channels || InteractionChannelListInstance(this._version, this._solution.sid); + return this._channels; + } + + fetch(callback?: (error: Error | null, item?: InteractionInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InteractionInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: InteractionContextUpdateOptions | ((error: Error | null, item?: InteractionInstance) => any),callback?: (error: Error | null, item?: InteractionInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["webhookTtid"] !== undefined) + data["WebhookTtid"] = params["webhookTtid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InteractionInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: InteractionContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["webhookTtid"] !== undefined) + data["WebhookTtid"] = params["webhookTtid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InteractionPayload extends InteractionResource {} + +interface InteractionResource { + sid: string; + channel: any; + routing: any; + url: string; + links: Record; + interaction_context_sid: string; + webhook_ttid: string; +} + +export class InteractionInstance { + protected _solution: InteractionContextSolution; + protected _context?: InteractionContext; + + constructor(protected _version: V1, payload: InteractionResource, sid?: string) { + + this.sid = (payload.sid); + this.channel = (payload.channel); + this.routing = (payload.routing); + this.url = (payload.url); + this.links = (payload.links); + this.interactionContextSid = (payload.interaction_context_sid); + this.webhookTtid = (payload.webhook_ttid); + + this._solution = { sid: sid, }; + } + + /** + * The unique string created by Twilio to identify an Interaction resource, prefixed with KD. + */ + sid: string; + /** + * A JSON object that defines the Interaction’s communication channel and includes details about the channel. See the [Outbound SMS](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) and [inbound (API-initiated)](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#api-initiated-contact) Channel object examples. + */ + channel: any; + /** + * A JSON Object representing the routing rules for the Interaction Channel. See [Outbound SMS Example](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) for an example Routing object. The Interactions resource uses TaskRouter for all routing functionality. All attributes in the Routing object on your Interaction request body are added “as is” to the task. For a list of known attributes consumed by the Flex UI and/or Flex Insights, see [Known Task Attributes](https://www.twilio.com/docs/flex/developer/conversations/interactions-api#task-attributes). + */ + routing: any; + url: string; + links: Record; + interactionContextSid: string; + webhookTtid: string; + + private get _proxy(): InteractionContext { + this._context = this._context || new InteractionContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a InteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance + */ + fetch(callback?: (error: Error | null, item?: InteractionInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a InteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance + */ + update(callback?: (error: Error | null, item?: InteractionInstance) => any): Promise; + /** + * Update a InteractionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance + */ + update(params: InteractionContextUpdateOptions, callback?: (error: Error | null, item?: InteractionInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: InteractionInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a InteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a InteractionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance with HTTP metadata + */ + updateWithHttpInfo(params: InteractionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the channels. + */ + channels(): InteractionChannelListInstance { + return this._proxy.channels; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + channel: this.channel, + routing: this.routing, + url: this.url, + links: this.links, + interactionContextSid: this.interactionContextSid, + webhookTtid: this.webhookTtid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InteractionSolution { +} + +export interface InteractionListInstance { + _version: V1; + _solution: InteractionSolution; + _uri: string; + + (sid: string, ): InteractionContext; + get(sid: string, ): InteractionContext; + + + + + + + /** + * Create a InteractionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance + */ + create(params: InteractionListInstanceCreateOptions, callback?: (error: Error | null, item?: InteractionInstance) => any): Promise; + + /** + * Create a InteractionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance with HTTP metadata + */ + createWithHttpInfo(params: InteractionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InteractionListInstance(version: V1): InteractionListInstance { + const instance = ((sid, ) => instance.get(sid, )) as InteractionListInstance; + + instance.get = function get(sid, ): InteractionContext { + return new InteractionContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Interactions`; + + instance.create = function create(params: InteractionListInstanceCreateOptions, callback?: (error: Error | null, items: InteractionInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["channel"] === null || params["channel"] === undefined) { + throw new Error('Required parameter "params[\'channel\']" missing.'); + } + + let data: any = {}; + + + + data["Channel"] = serialize.object(params["channel"]); + if (params["routing"] !== undefined) + data["Routing"] = serialize.object(params["routing"]); + if (params["interactionContextSid"] !== undefined) + data["InteractionContextSid"] = params["interactionContextSid"]; + if (params["webhookTtid"] !== undefined) + data["WebhookTtid"] = params["webhookTtid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InteractionInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InteractionListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["channel"] === null || params["channel"] === undefined) { + throw new Error('Required parameter "params[\'channel\']" missing.'); + } + + let data: any = {}; + + + + data["Channel"] = serialize.object(params["channel"]); + if (params["routing"] !== undefined) + data["Routing"] = serialize.object(params["routing"]); + if (params["interactionContextSid"] !== undefined) + data["InteractionContextSid"] = params["interactionContextSid"]; + if (params["webhookTtid"] !== undefined) + data["WebhookTtid"] = params["webhookTtid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/flexApi/v1/interaction/interactionChannel.ts b/rest/flexApi/v1/interaction/interactionChannel.ts new file mode 100644 index 000000000..dc433dcd3 --- /dev/null +++ b/rest/flexApi/v1/interaction/interactionChannel.ts @@ -0,0 +1,758 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { InteractionChannelInviteListInstance } from "./interactionChannel/interactionChannelInvite"; +import { InteractionChannelParticipantListInstance } from "./interactionChannel/interactionChannelParticipant"; +import { InteractionTransferListInstance } from "./interactionChannel/interactionTransfer"; + + +/** + * The status of this channel. + */ +export type InteractionChannelChannelStatus = 'setup'|'active'|'failed'|'closed'|'inactive'|'pause'|'transfer'; + +/** + * The Interaction Channel\'s type. Can be: `sms`, `email`, `chat`, `whatsapp`, `web`, `messenger`, or `gbm`. **Note:** These can be different from the task channel type specified in the Routing attributes. Task channel type corresponds to channel capacity while this channel type is the actual media type + */ +export type InteractionChannelType = 'voice'|'sms'|'email'|'web'|'whatsapp'|'chat'|'messenger'|'gbm'; + +export type InteractionChannelUpdateChannelStatus = 'closed'|'inactive'; + + + +/** + * Options to pass to update a InteractionChannelInstance + */ +export interface InteractionChannelContextUpdateOptions { + /** */ + "status": InteractionChannelUpdateChannelStatus; + /** It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. */ + "routing"?: any; +} + +/** + * Options to pass to each + */ +export interface InteractionChannelListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InteractionChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InteractionChannelListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InteractionChannelListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InteractionChannelContext { + invites: InteractionChannelInviteListInstance; + participants: InteractionChannelParticipantListInstance; + transfers: InteractionTransferListInstance; + + /** + * Fetch a InteractionChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelInstance + */ + fetch(callback?: (error: Error | null, item?: InteractionChannelInstance) => any): Promise + + /** + * Fetch a InteractionChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a InteractionChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelInstance + */ + update(params: InteractionChannelContextUpdateOptions, callback?: (error: Error | null, item?: InteractionChannelInstance) => any): Promise; + + /** + * Update a InteractionChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: InteractionChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InteractionChannelContextSolution { + "interactionSid": string; + "sid": string; +} + +export class InteractionChannelContextImpl implements InteractionChannelContext { + protected _solution: InteractionChannelContextSolution; + protected _uri: string; + + protected _invites?: InteractionChannelInviteListInstance; + protected _participants?: InteractionChannelParticipantListInstance; + protected _transfers?: InteractionTransferListInstance; + + constructor(protected _version: V1, interactionSid: string, sid: string) { + if (!isValidPathParam(interactionSid)) { + throw new Error('Parameter \'interactionSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { interactionSid, sid, }; + this._uri = `/Interactions/${interactionSid}/Channels/${sid}`; + } + + get invites(): InteractionChannelInviteListInstance { + this._invites = this._invites || InteractionChannelInviteListInstance(this._version, this._solution.interactionSid, this._solution.sid); + return this._invites; + } + + get participants(): InteractionChannelParticipantListInstance { + this._participants = this._participants || InteractionChannelParticipantListInstance(this._version, this._solution.interactionSid, this._solution.sid); + return this._participants; + } + + get transfers(): InteractionTransferListInstance { + this._transfers = this._transfers || InteractionTransferListInstance(this._version, this._solution.interactionSid, this._solution.sid); + return this._transfers; + } + + fetch(callback?: (error: Error | null, item?: InteractionChannelInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InteractionChannelInstance(operationVersion, payload, instance._solution.interactionSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionChannelInstance(operationVersion, response.body, instance._solution.interactionSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: InteractionChannelContextUpdateOptions,callback?: (error: Error | null, item?: InteractionChannelInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + if (params["routing"] !== undefined) + data["Routing"] = serialize.object(params["routing"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InteractionChannelInstance(operationVersion, payload, instance._solution.interactionSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: InteractionChannelContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + if (params["routing"] !== undefined) + data["Routing"] = serialize.object(params["routing"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionChannelInstance(operationVersion, response.body, instance._solution.interactionSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InteractionChannelPayload extends TwilioResponsePayload { + channels: InteractionChannelResource[]; +} + +interface InteractionChannelResource { + sid: string; + interaction_sid: string; + type: InteractionChannelType; + status: InteractionChannelChannelStatus; + error_code: number; + error_message: string; + url: string; + links: Record; +} + +export class InteractionChannelInstance { + protected _solution: InteractionChannelContextSolution; + protected _context?: InteractionChannelContext; + + constructor(protected _version: V1, payload: InteractionChannelResource, interactionSid: string, sid?: string) { + + this.sid = (payload.sid); + this.interactionSid = (payload.interaction_sid); + this.type = payload.type; + this.status = payload.status; + this.errorCode = deserialize.integer(payload.error_code); + this.errorMessage = (payload.error_message); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { interactionSid, sid: sid, }; + } + + /** + * The unique string created by Twilio to identify an Interaction Channel resource, prefixed with UO. + */ + sid: string; + /** + * The unique string created by Twilio to identify an Interaction resource, prefixed with KD. + */ + interactionSid: string; + type: InteractionChannelType; + status: InteractionChannelChannelStatus; + /** + * The Twilio error code for a failed channel. + */ + errorCode: number; + /** + * The error message for a failed channel. + */ + errorMessage: string; + url: string; + links: Record; + + private get _proxy(): InteractionChannelContext { + this._context = this._context || new InteractionChannelContextImpl(this._version, this._solution.interactionSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a InteractionChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelInstance + */ + fetch(callback?: (error: Error | null, item?: InteractionChannelInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InteractionChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a InteractionChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelInstance + */ + update(params: InteractionChannelContextUpdateOptions, callback?: (error: Error | null, item?: InteractionChannelInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: InteractionChannelInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a InteractionChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: InteractionChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the invites. + */ + invites(): InteractionChannelInviteListInstance { + return this._proxy.invites; + } + + /** + * Access the participants. + */ + participants(): InteractionChannelParticipantListInstance { + return this._proxy.participants; + } + + /** + * Access the transfers. + */ + transfers(): InteractionTransferListInstance { + return this._proxy.transfers; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + interactionSid: this.interactionSid, + type: this.type, + status: this.status, + errorCode: this.errorCode, + errorMessage: this.errorMessage, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InteractionChannelSolution { + interactionSid: string; +} + +export interface InteractionChannelListInstance { + _version: V1; + _solution: InteractionChannelSolution; + _uri: string; + + (sid: string, ): InteractionChannelContext; + get(sid: string, ): InteractionChannelContext; + + + + + + + + /** + * Streams InteractionChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InteractionChannelInstance, done: (err?: Error) => void) => void): void; + each(params: InteractionChannelListInstanceEachOptions, callback?: (item: InteractionChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InteractionChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InteractionChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InteractionChannelListInstanceEachOptions, callback?: (item: InteractionChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InteractionChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InteractionChannelPage) => any): Promise; + /** + * Retrieve a single target page of InteractionChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InteractionChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InteractionChannelInstance[]) => any): Promise; + list(params: InteractionChannelListInstanceOptions, callback?: (error: Error | null, items: InteractionChannelInstance[]) => any): Promise; + /** + * Lists InteractionChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InteractionChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InteractionChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InteractionChannelPage) => any): Promise; + page(params: InteractionChannelListInstancePageOptions, callback?: (error: Error | null, items: InteractionChannelPage) => any): Promise; + /** + * Retrieve a single page of InteractionChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InteractionChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InteractionChannelListInstance(version: V1, interactionSid: string): InteractionChannelListInstance { + if (!isValidPathParam(interactionSid)) { + throw new Error('Parameter \'interactionSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as InteractionChannelListInstance; + + instance.get = function get(sid, ): InteractionChannelContext { + return new InteractionChannelContextImpl(version, interactionSid, sid); + } + + instance._version = version; + instance._solution = { interactionSid, }; + instance._uri = `/Interactions/${interactionSid}/Channels`; + + instance.page = function page(params?: InteractionChannelListInstancePageOptions | ((error: Error | null, items: InteractionChannelPage) => any), callback?: (error: Error | null, items: InteractionChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InteractionChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InteractionChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InteractionChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InteractionChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InteractionChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InteractionChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InteractionChannelPage extends Page { +/** +* Initialize the InteractionChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InteractionChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InteractionChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InteractionChannelResource): InteractionChannelInstance { + + return new InteractionChannelInstance( + this._version, + payload, + this._solution.interactionSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/interaction/interactionChannel/interactionChannelInvite.ts b/rest/flexApi/v1/interaction/interactionChannel/interactionChannelInvite.ts new file mode 100644 index 000000000..3a7fa7f33 --- /dev/null +++ b/rest/flexApi/v1/interaction/interactionChannel/interactionChannelInvite.ts @@ -0,0 +1,514 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to create a InteractionChannelInviteInstance + */ +export interface InteractionChannelInviteListInstanceCreateOptions { + /** The Interaction\\\'s routing logic. */ + "routing": any; +} + +/** + * Options to pass to each + */ +export interface InteractionChannelInviteListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InteractionChannelInviteInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InteractionChannelInviteListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InteractionChannelInviteListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface InteractionChannelInviteSolution { + interactionSid: string; + channelSid: string; +} + +export interface InteractionChannelInviteListInstance { + _version: V1; + _solution: InteractionChannelInviteSolution; + _uri: string; + + + + /** + * Create a InteractionChannelInviteInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelInviteInstance + */ + create(params: InteractionChannelInviteListInstanceCreateOptions, callback?: (error: Error | null, item?: InteractionChannelInviteInstance) => any): Promise; + + /** + * Create a InteractionChannelInviteInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelInviteInstance with HTTP metadata + */ + createWithHttpInfo(params: InteractionChannelInviteListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams InteractionChannelInviteInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelInviteListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InteractionChannelInviteInstance, done: (err?: Error) => void) => void): void; + each(params: InteractionChannelInviteListInstanceEachOptions, callback?: (item: InteractionChannelInviteInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InteractionChannelInviteInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelInviteListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InteractionChannelInviteInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InteractionChannelInviteListInstanceEachOptions, callback?: (item: InteractionChannelInviteInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InteractionChannelInviteInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InteractionChannelInvitePage) => any): Promise; + /** + * Retrieve a single target page of InteractionChannelInviteInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InteractionChannelInviteInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelInviteListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InteractionChannelInviteInstance[]) => any): Promise; + list(params: InteractionChannelInviteListInstanceOptions, callback?: (error: Error | null, items: InteractionChannelInviteInstance[]) => any): Promise; + /** + * Lists InteractionChannelInviteInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelInviteListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InteractionChannelInviteListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InteractionChannelInviteInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelInviteListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InteractionChannelInvitePage) => any): Promise; + page(params: InteractionChannelInviteListInstancePageOptions, callback?: (error: Error | null, items: InteractionChannelInvitePage) => any): Promise; + /** + * Retrieve a single page of InteractionChannelInviteInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelInviteListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InteractionChannelInviteListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InteractionChannelInviteListInstance(version: V1, interactionSid: string, channelSid: string): InteractionChannelInviteListInstance { + if (!isValidPathParam(interactionSid)) { + throw new Error('Parameter \'interactionSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = {} as InteractionChannelInviteListInstance; + + instance._version = version; + instance._solution = { interactionSid, channelSid, }; + instance._uri = `/Interactions/${interactionSid}/Channels/${channelSid}/Invites`; + + instance.create = function create(params: InteractionChannelInviteListInstanceCreateOptions, callback?: (error: Error | null, items: InteractionChannelInviteInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["routing"] === null || params["routing"] === undefined) { + throw new Error('Required parameter "params[\'routing\']" missing.'); + } + + let data: any = {}; + + + + data["Routing"] = serialize.object(params["routing"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InteractionChannelInviteInstance(operationVersion, payload, instance._solution.interactionSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InteractionChannelInviteListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["routing"] === null || params["routing"] === undefined) { + throw new Error('Required parameter "params[\'routing\']" missing.'); + } + + let data: any = {}; + + + + data["Routing"] = serialize.object(params["routing"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionChannelInviteInstance(operationVersion, response.body, instance._solution.interactionSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InteractionChannelInviteListInstancePageOptions | ((error: Error | null, items: InteractionChannelInvitePage) => any), callback?: (error: Error | null, items: InteractionChannelInvitePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InteractionChannelInvitePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InteractionChannelInvitePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InteractionChannelInvitePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InteractionChannelInviteListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InteractionChannelInvitePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InteractionChannelInvitePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface InteractionChannelInvitePayload extends TwilioResponsePayload { + invites: InteractionChannelInviteResource[]; +} + +interface InteractionChannelInviteResource { + sid: string; + interaction_sid: string; + channel_sid: string; + routing: any; + url: string; +} + +export class InteractionChannelInviteInstance { + + constructor(protected _version: V1, payload: InteractionChannelInviteResource, interactionSid: string, channelSid: string) { + + this.sid = (payload.sid); + this.interactionSid = (payload.interaction_sid); + this.channelSid = (payload.channel_sid); + this.routing = (payload.routing); + this.url = (payload.url); + + } + + /** + * The unique string created by Twilio to identify an Interaction Channel Invite resource. + */ + sid: string; + /** + * The Interaction SID for this Channel. + */ + interactionSid: string; + /** + * The Channel SID for this Invite. + */ + channelSid: string; + /** + * A JSON object representing the routing rules for the Interaction Channel. See [Outbound SMS Example](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) for an example Routing object. The Interactions resource uses TaskRouter for all routing functionality. All attributes in the Routing object on your Interaction request body are added “as is” to the task. For a list of known attributes consumed by the Flex UI and/or Flex Insights, see [Known Task Attributes](https://www.twilio.com/docs/flex/developer/conversations/interactions-api#task-attributes). + */ + routing: any; + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + interactionSid: this.interactionSid, + channelSid: this.channelSid, + routing: this.routing, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class InteractionChannelInvitePage extends Page { +/** +* Initialize the InteractionChannelInvitePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InteractionChannelInviteSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InteractionChannelInviteInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InteractionChannelInviteResource): InteractionChannelInviteInstance { + + return new InteractionChannelInviteInstance( + this._version, + payload, + this._solution.interactionSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/interaction/interactionChannel/interactionChannelParticipant.ts b/rest/flexApi/v1/interaction/interactionChannel/interactionChannelParticipant.ts new file mode 100644 index 000000000..6de324bd8 --- /dev/null +++ b/rest/flexApi/v1/interaction/interactionChannel/interactionChannelParticipant.ts @@ -0,0 +1,742 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type InteractionChannelParticipantStatus = 'closed'|'wrapup'; + +/** + * Participant type. Can be: `agent`, `customer`, `supervisor`, `external`, `unknown` + */ +export type InteractionChannelParticipantType = 'supervisor'|'customer'|'external'|'agent'|'unknown'; + + +/** + * Options to pass to update a InteractionChannelParticipantInstance + */ +export interface InteractionChannelParticipantContextUpdateOptions { + /** */ + "status": InteractionChannelParticipantStatus; +} + +/** + * Options to pass to create a InteractionChannelParticipantInstance + */ +export interface InteractionChannelParticipantListInstanceCreateOptions { + /** */ + "type": InteractionChannelParticipantType; + /** JSON representing the Media Properties for the new Participant. */ + "mediaProperties": any; + /** Object representing the Routing Properties for the new Participant. */ + "routingProperties"?: any; +} + +/** + * Options to pass to each + */ +export interface InteractionChannelParticipantListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InteractionChannelParticipantInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InteractionChannelParticipantListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InteractionChannelParticipantListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InteractionChannelParticipantContext { + + /** + * Update a InteractionChannelParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelParticipantInstance + */ + update(params: InteractionChannelParticipantContextUpdateOptions, callback?: (error: Error | null, item?: InteractionChannelParticipantInstance) => any): Promise; + + /** + * Update a InteractionChannelParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: InteractionChannelParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InteractionChannelParticipantContextSolution { + "interactionSid": string; + "channelSid": string; + "sid": string; +} + +export class InteractionChannelParticipantContextImpl implements InteractionChannelParticipantContext { + protected _solution: InteractionChannelParticipantContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, interactionSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(interactionSid)) { + throw new Error('Parameter \'interactionSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { interactionSid, channelSid, sid, }; + this._uri = `/Interactions/${interactionSid}/Channels/${channelSid}/Participants/${sid}`; + } + + update(params: InteractionChannelParticipantContextUpdateOptions,callback?: (error: Error | null, item?: InteractionChannelParticipantInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InteractionChannelParticipantInstance(operationVersion, payload, instance._solution.interactionSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: InteractionChannelParticipantContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionChannelParticipantInstance(operationVersion, response.body, instance._solution.interactionSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InteractionChannelParticipantPayload extends TwilioResponsePayload { + participants: InteractionChannelParticipantResource[]; +} + +interface InteractionChannelParticipantResource { + sid: string; + type: InteractionChannelParticipantType; + interaction_sid: string; + channel_sid: string; + url: string; + routing_properties: any; +} + +export class InteractionChannelParticipantInstance { + protected _solution: InteractionChannelParticipantContextSolution; + protected _context?: InteractionChannelParticipantContext; + + constructor(protected _version: V1, payload: InteractionChannelParticipantResource, interactionSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.type = payload.type; + this.interactionSid = (payload.interaction_sid); + this.channelSid = (payload.channel_sid); + this.url = (payload.url); + this.routingProperties = (payload.routing_properties); + + this._solution = { interactionSid, channelSid, sid: sid, }; + } + + /** + * The unique string created by Twilio to identify an Interaction Channel Participant resource. + */ + sid: string; + type: InteractionChannelParticipantType; + /** + * The Interaction Sid for this channel. + */ + interactionSid: string; + /** + * The Channel Sid for this Participant. + */ + channelSid: string; + url: string; + /** + * The Participant\'s routing properties. + */ + routingProperties: any; + + private get _proxy(): InteractionChannelParticipantContext { + this._context = this._context || new InteractionChannelParticipantContextImpl(this._version, this._solution.interactionSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Update a InteractionChannelParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelParticipantInstance + */ + update(params: InteractionChannelParticipantContextUpdateOptions, callback?: (error: Error | null, item?: InteractionChannelParticipantInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: InteractionChannelParticipantInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a InteractionChannelParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: InteractionChannelParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + type: this.type, + interactionSid: this.interactionSid, + channelSid: this.channelSid, + url: this.url, + routingProperties: this.routingProperties, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InteractionChannelParticipantSolution { + interactionSid: string; + channelSid: string; +} + +export interface InteractionChannelParticipantListInstance { + _version: V1; + _solution: InteractionChannelParticipantSolution; + _uri: string; + + (sid: string, ): InteractionChannelParticipantContext; + get(sid: string, ): InteractionChannelParticipantContext; + + + + + /** + * Create a InteractionChannelParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelParticipantInstance + */ + create(params: InteractionChannelParticipantListInstanceCreateOptions, callback?: (error: Error | null, item?: InteractionChannelParticipantInstance) => any): Promise; + + /** + * Create a InteractionChannelParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionChannelParticipantInstance with HTTP metadata + */ + createWithHttpInfo(params: InteractionChannelParticipantListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams InteractionChannelParticipantInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InteractionChannelParticipantInstance, done: (err?: Error) => void) => void): void; + each(params: InteractionChannelParticipantListInstanceEachOptions, callback?: (item: InteractionChannelParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InteractionChannelParticipantInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InteractionChannelParticipantInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InteractionChannelParticipantListInstanceEachOptions, callback?: (item: InteractionChannelParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InteractionChannelParticipantInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InteractionChannelParticipantPage) => any): Promise; + /** + * Retrieve a single target page of InteractionChannelParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InteractionChannelParticipantInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InteractionChannelParticipantInstance[]) => any): Promise; + list(params: InteractionChannelParticipantListInstanceOptions, callback?: (error: Error | null, items: InteractionChannelParticipantInstance[]) => any): Promise; + /** + * Lists InteractionChannelParticipantInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InteractionChannelParticipantListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InteractionChannelParticipantInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InteractionChannelParticipantPage) => any): Promise; + page(params: InteractionChannelParticipantListInstancePageOptions, callback?: (error: Error | null, items: InteractionChannelParticipantPage) => any): Promise; + /** + * Retrieve a single page of InteractionChannelParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionChannelParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InteractionChannelParticipantListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InteractionChannelParticipantListInstance(version: V1, interactionSid: string, channelSid: string): InteractionChannelParticipantListInstance { + if (!isValidPathParam(interactionSid)) { + throw new Error('Parameter \'interactionSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as InteractionChannelParticipantListInstance; + + instance.get = function get(sid, ): InteractionChannelParticipantContext { + return new InteractionChannelParticipantContextImpl(version, interactionSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { interactionSid, channelSid, }; + instance._uri = `/Interactions/${interactionSid}/Channels/${channelSid}/Participants`; + + instance.create = function create(params: InteractionChannelParticipantListInstanceCreateOptions, callback?: (error: Error | null, items: InteractionChannelParticipantInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["mediaProperties"] === null || params["mediaProperties"] === undefined) { + throw new Error('Required parameter "params[\'mediaProperties\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + + data["MediaProperties"] = serialize.object(params["mediaProperties"]); + if (params["routingProperties"] !== undefined) + data["RoutingProperties"] = serialize.object(params["routingProperties"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InteractionChannelParticipantInstance(operationVersion, payload, instance._solution.interactionSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InteractionChannelParticipantListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["mediaProperties"] === null || params["mediaProperties"] === undefined) { + throw new Error('Required parameter "params[\'mediaProperties\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + + data["MediaProperties"] = serialize.object(params["mediaProperties"]); + if (params["routingProperties"] !== undefined) + data["RoutingProperties"] = serialize.object(params["routingProperties"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionChannelParticipantInstance(operationVersion, response.body, instance._solution.interactionSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InteractionChannelParticipantListInstancePageOptions | ((error: Error | null, items: InteractionChannelParticipantPage) => any), callback?: (error: Error | null, items: InteractionChannelParticipantPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InteractionChannelParticipantPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InteractionChannelParticipantPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InteractionChannelParticipantPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InteractionChannelParticipantListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InteractionChannelParticipantPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InteractionChannelParticipantPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InteractionChannelParticipantPage extends Page { +/** +* Initialize the InteractionChannelParticipantPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InteractionChannelParticipantSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InteractionChannelParticipantInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InteractionChannelParticipantResource): InteractionChannelParticipantInstance { + + return new InteractionChannelParticipantInstance( + this._version, + payload, + this._solution.interactionSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/interaction/interactionChannel/interactionTransfer.ts b/rest/flexApi/v1/interaction/interactionChannel/interactionTransfer.ts new file mode 100644 index 000000000..67235d165 --- /dev/null +++ b/rest/flexApi/v1/interaction/interactionChannel/interactionTransfer.ts @@ -0,0 +1,633 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The status of the Transfer. Can be: `active`, `completed`, `failed`. + */ +export type InteractionTransferTransferStatus = 'active'|'failed'|'completed'; + +/** + * The type of the Transfer. Can be: `cold`, `warm`. + */ +export type InteractionTransferTransferType = 'warm'|'cold'|'external'; + + + +/** + * Options to pass to update a InteractionTransferInstance + */ +export interface InteractionTransferContextUpdateOptions { + /** */ + "body"?: object; +} + +/** + * Options to pass to create a InteractionTransferInstance + */ +export interface InteractionTransferListInstanceCreateOptions { + /** */ + "body"?: object; +} + +export interface InteractionTransferContext { + + /** + * Fetch a InteractionTransferInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance + */ + fetch(callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise + + /** + * Fetch a InteractionTransferInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a InteractionTransferInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance + */ + update(callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise; + /** + * Update a InteractionTransferInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance + */ + update(params: object, headers?: any, callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise; + + /** + * Update a InteractionTransferInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a InteractionTransferInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance with HTTP metadata + */ + updateWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InteractionTransferContextSolution { + "interactionSid": string; + "channelSid": string; + "sid": string; +} + +export class InteractionTransferContextImpl implements InteractionTransferContext { + protected _solution: InteractionTransferContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, interactionSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(interactionSid)) { + throw new Error('Parameter \'interactionSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { interactionSid, channelSid, sid, }; + this._uri = `/Interactions/${interactionSid}/Channels/${channelSid}/Transfers/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InteractionTransferInstance(operationVersion, payload, instance._solution.interactionSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionTransferInstance(operationVersion, response.body, instance._solution.interactionSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: object | ((error: Error | null, item?: InteractionTransferInstance) => any), headers?: any,callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as object; + } else { + params = params || {} as Partial as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InteractionTransferInstance(operationVersion, payload, instance._solution.interactionSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: object | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as object; + } else { + params = params || {} as Partial as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionTransferInstance(operationVersion, response.body, instance._solution.interactionSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InteractionTransferPayload extends InteractionTransferResource {} + +interface InteractionTransferResource { + sid: string; + instance_sid: string; + account_sid: string; + interaction_sid: string; + channel_sid: string; + execution_sid: string; + type: InteractionTransferTransferType; + status: InteractionTransferTransferStatus; + from: string; + to: string; + note_sid: string; + summary_sid: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class InteractionTransferInstance { + protected _solution: InteractionTransferContextSolution; + protected _context?: InteractionTransferContext; + + constructor(protected _version: V1, payload: InteractionTransferResource, interactionSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.instanceSid = (payload.instance_sid); + this.accountSid = (payload.account_sid); + this.interactionSid = (payload.interaction_sid); + this.channelSid = (payload.channel_sid); + this.executionSid = (payload.execution_sid); + this.type = payload.type; + this.status = payload.status; + this.from = (payload.from); + this.to = (payload.to); + this.noteSid = (payload.note_sid); + this.summarySid = (payload.summary_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { interactionSid, channelSid, sid: sid, }; + } + + /** + * The unique string created by Twilio to identify an Interaction Transfer resource. + */ + sid: string; + /** + * The SID of the Instance associated with the Transfer. + */ + instanceSid: string; + /** + * The SID of the Account that created the Transfer. + */ + accountSid: string; + /** + * The Interaction Sid for this channel. + */ + interactionSid: string; + /** + * The Channel Sid for this Transfer. + */ + channelSid: string; + /** + * The Execution SID associated with the Transfer. + */ + executionSid: string; + type: InteractionTransferTransferType; + status: InteractionTransferTransferStatus; + /** + * The SID of the Participant initiating the Transfer. + */ + from: string; + /** + * The SID of the Participant receiving the Transfer. + */ + to: string; + /** + * The SID of the Note associated with the Transfer. + */ + noteSid: string; + /** + * The SID of the Summary associated with the Transfer. + */ + summarySid: string; + /** + * The date and time when the Transfer was created. + */ + dateCreated: Date; + /** + * The date and time when the Transfer was last updated. + */ + dateUpdated: Date; + url: string; + + private get _proxy(): InteractionTransferContext { + this._context = this._context || new InteractionTransferContextImpl(this._version, this._solution.interactionSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a InteractionTransferInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance + */ + fetch(callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InteractionTransferInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a InteractionTransferInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance + */ + update(callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise; + /** + * Update a InteractionTransferInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance + */ + update(params: object, headers?: any, callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a InteractionTransferInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a InteractionTransferInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance with HTTP metadata + */ + updateWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + instanceSid: this.instanceSid, + accountSid: this.accountSid, + interactionSid: this.interactionSid, + channelSid: this.channelSid, + executionSid: this.executionSid, + type: this.type, + status: this.status, + from: this.from, + to: this.to, + noteSid: this.noteSid, + summarySid: this.summarySid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InteractionTransferSolution { + interactionSid: string; + channelSid: string; +} + +export interface InteractionTransferListInstance { + _version: V1; + _solution: InteractionTransferSolution; + _uri: string; + + (sid: string, ): InteractionTransferContext; + get(sid: string, ): InteractionTransferContext; + + + + + + + /** + * Create a InteractionTransferInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance + */ + create(callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise; + /** + * Create a InteractionTransferInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance + */ + create(params: object, headers?: any, callback?: (error: Error | null, item?: InteractionTransferInstance) => any): Promise; + + /** + * Create a InteractionTransferInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a InteractionTransferInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionTransferInstance with HTTP metadata + */ + createWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InteractionTransferListInstance(version: V1, interactionSid: string, channelSid: string): InteractionTransferListInstance { + if (!isValidPathParam(interactionSid)) { + throw new Error('Parameter \'interactionSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as InteractionTransferListInstance; + + instance.get = function get(sid, ): InteractionTransferContext { + return new InteractionTransferContextImpl(version, interactionSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { interactionSid, channelSid, }; + instance._uri = `/Interactions/${interactionSid}/Channels/${channelSid}/Transfers`; + + instance.create = function create(params?: object | ((error: Error | null, items: InteractionTransferInstance) => any), headers?: any, callback?: (error: Error | null, items: InteractionTransferInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as object; + } else { + params = params || {} as Partial as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InteractionTransferInstance(operationVersion, payload, instance._solution.interactionSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: object | ((error: Error | null, items: ApiResponse) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as object; + } else { + params = params || {} as Partial as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InteractionTransferInstance(operationVersion, response.body, instance._solution.interactionSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/flexApi/v1/plugin.ts b/rest/flexApi/v1/plugin.ts new file mode 100644 index 000000000..b0d11ff61 --- /dev/null +++ b/rest/flexApi/v1/plugin.ts @@ -0,0 +1,960 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { PluginVersionsListInstance } from "./plugin/pluginVersions"; + + + +/** + * Options to pass to fetch a PluginInstance + */ +export interface PluginContextFetchOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; +} + +/** + * Options to pass to update a PluginInstance + */ +export interface PluginContextUpdateOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** The Flex Plugin\\\'s friendly name. */ + "friendlyName"?: string; + /** A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long */ + "description"?: string; +} + +/** + * Options to pass to create a PluginInstance + */ +export interface PluginListInstanceCreateOptions { + /** The Flex Plugin\\\'s unique name. */ + "uniqueName": string; + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** The Flex Plugin\\\'s friendly name. */ + "friendlyName"?: string; + /** A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long */ + "description"?: string; +} + +/** + * Options to pass to each + */ +export interface PluginListInstanceEachOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PluginInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PluginListInstanceOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PluginListInstancePageOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PluginContext { + pluginVersions: PluginVersionsListInstance; + + /** + * Fetch a PluginInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance + */ + fetch(callback?: (error: Error | null, item?: PluginInstance) => any): Promise; + /** + * Fetch a PluginInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance + */ + fetch(params: PluginContextFetchOptions, callback?: (error: Error | null, item?: PluginInstance) => any): Promise; + + /** + * Fetch a PluginInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a PluginInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PluginContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Update a PluginInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance + */ + update(callback?: (error: Error | null, item?: PluginInstance) => any): Promise; + /** + * Update a PluginInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance + */ + update(params: PluginContextUpdateOptions, callback?: (error: Error | null, item?: PluginInstance) => any): Promise; + + /** + * Update a PluginInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a PluginInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance with HTTP metadata + */ + updateWithHttpInfo(params: PluginContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PluginContextSolution { + "sid": string; +} + +export class PluginContextImpl implements PluginContext { + protected _solution: PluginContextSolution; + protected _uri: string; + + protected _pluginVersions?: PluginVersionsListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/PluginService/Plugins/${sid}`; + } + + get pluginVersions(): PluginVersionsListInstance { + this._pluginVersions = this._pluginVersions || PluginVersionsListInstance(this._version, this._solution.sid); + return this._pluginVersions; + } + + fetch(params?: PluginContextFetchOptions | ((error: Error | null, item?: PluginInstance) => any),callback?: (error: Error | null, item?: PluginInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new PluginInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: PluginContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: PluginContextUpdateOptions | ((error: Error | null, item?: PluginInstance) => any),callback?: (error: Error | null, item?: PluginInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PluginInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: PluginContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PluginPayload extends TwilioResponsePayload { + plugins: PluginResource[]; +} + +interface PluginResource { + sid: string; + account_sid: string; + unique_name: string; + friendly_name: string; + description: string; + archived: boolean; + date_created: Date; + date_updated: Date; + url: string; + links: Record; +} + +export class PluginInstance { + protected _solution: PluginContextSolution; + protected _context?: PluginContext; + + constructor(protected _version: V1, payload: PluginResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.uniqueName = (payload.unique_name); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.archived = (payload.archived); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Flex Plugin resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin resource and owns this resource. + */ + accountSid: string; + /** + * The name that uniquely identifies this Flex Plugin resource. + */ + uniqueName: string; + /** + * The friendly name this Flex Plugin resource. + */ + friendlyName: string; + /** + * A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + */ + description: string; + /** + * Whether the Flex Plugin is archived. The default value is false. + */ + archived: boolean; + /** + * The date and time in GMT-7 when the Flex Plugin was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT-7 when the Flex Plugin was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Flex Plugin resource. + */ + url: string; + links: Record; + + private get _proxy(): PluginContext { + this._context = this._context || new PluginContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a PluginInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance + */ + fetch(callback?: (error: Error | null, item?: PluginInstance) => any): Promise; + /** + * Fetch a PluginInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance + */ + fetch(params: PluginContextFetchOptions, callback?: (error: Error | null, item?: PluginInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: PluginInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a PluginInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a PluginInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PluginContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Update a PluginInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance + */ + update(callback?: (error: Error | null, item?: PluginInstance) => any): Promise; + /** + * Update a PluginInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance + */ + update(params: PluginContextUpdateOptions, callback?: (error: Error | null, item?: PluginInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: PluginInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a PluginInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a PluginInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance with HTTP metadata + */ + updateWithHttpInfo(params: PluginContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the pluginVersions. + */ + pluginVersions(): PluginVersionsListInstance { + return this._proxy.pluginVersions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + uniqueName: this.uniqueName, + friendlyName: this.friendlyName, + description: this.description, + archived: this.archived, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PluginSolution { +} + +export interface PluginListInstance { + _version: V1; + _solution: PluginSolution; + _uri: string; + + (sid: string, ): PluginContext; + get(sid: string, ): PluginContext; + + + + + + + /** + * Create a PluginInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance + */ + create(params: PluginListInstanceCreateOptions, callback?: (error: Error | null, item?: PluginInstance) => any): Promise; + + /** + * Create a PluginInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginInstance with HTTP metadata + */ + createWithHttpInfo(params: PluginListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams PluginInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PluginInstance, done: (err?: Error) => void) => void): void; + each(params: PluginListInstanceEachOptions, callback?: (item: PluginInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PluginInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PluginInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PluginListInstanceEachOptions, callback?: (item: PluginInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PluginInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PluginPage) => any): Promise; + /** + * Retrieve a single target page of PluginInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists PluginInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PluginInstance[]) => any): Promise; + list(params: PluginListInstanceOptions, callback?: (error: Error | null, items: PluginInstance[]) => any): Promise; + /** + * Lists PluginInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: PluginListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of PluginInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PluginPage) => any): Promise; + page(params: PluginListInstancePageOptions, callback?: (error: Error | null, items: PluginPage) => any): Promise; + /** + * Retrieve a single page of PluginInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: PluginListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PluginListInstance(version: V1): PluginListInstance { + const instance = ((sid, ) => instance.get(sid, )) as PluginListInstance; + + instance.get = function get(sid, ): PluginContext { + return new PluginContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/PluginService/Plugins`; + + instance.create = function create(params: PluginListInstanceCreateOptions, callback?: (error: Error | null, items: PluginInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PluginInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: PluginListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: PluginListInstancePageOptions | ((error: Error | null, items: PluginPage) => any), callback?: (error: Error | null, items: PluginPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PluginPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PluginPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PluginPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PluginListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PluginPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PluginPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PluginPage extends Page { +/** +* Initialize the PluginPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: PluginSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PluginInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PluginResource): PluginInstance { + + return new PluginInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/plugin/pluginVersions.ts b/rest/flexApi/v1/plugin/pluginVersions.ts new file mode 100644 index 000000000..e039bd74c --- /dev/null +++ b/rest/flexApi/v1/plugin/pluginVersions.ts @@ -0,0 +1,818 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a PluginVersionsInstance + */ +export interface PluginVersionsContextFetchOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; +} + +/** + * Options to pass to create a PluginVersionsInstance + */ +export interface PluginVersionsListInstanceCreateOptions { + /** The Flex Plugin Version\\\'s version. */ + "versionParam": string; + /** The URL of the Flex Plugin Version bundle */ + "pluginUrl": string; + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** The changelog of the Flex Plugin Version. */ + "changelog"?: string; + /** Whether this Flex Plugin Version requires authorization. */ + "private"?: boolean; + /** The version of Flex Plugins CLI used to create this plugin */ + "cliVersion"?: string; + /** The validation status of the plugin, indicating whether it has been validated */ + "validateStatus"?: string; +} + +/** + * Options to pass to each + */ +export interface PluginVersionsListInstanceEachOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PluginVersionsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PluginVersionsListInstanceOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PluginVersionsListInstancePageOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PluginVersionsContext { + + /** + * Fetch a PluginVersionsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionsInstance + */ + fetch(callback?: (error: Error | null, item?: PluginVersionsInstance) => any): Promise; + /** + * Fetch a PluginVersionsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionsInstance + */ + fetch(params: PluginVersionsContextFetchOptions, callback?: (error: Error | null, item?: PluginVersionsInstance) => any): Promise; + + /** + * Fetch a PluginVersionsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a PluginVersionsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PluginVersionsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PluginVersionsContextSolution { + "pluginSid": string; + "sid": string; +} + +export class PluginVersionsContextImpl implements PluginVersionsContext { + protected _solution: PluginVersionsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, pluginSid: string, sid: string) { + if (!isValidPathParam(pluginSid)) { + throw new Error('Parameter \'pluginSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { pluginSid, sid, }; + this._uri = `/PluginService/Plugins/${pluginSid}/Versions/${sid}`; + } + + fetch(params?: PluginVersionsContextFetchOptions | ((error: Error | null, item?: PluginVersionsInstance) => any),callback?: (error: Error | null, item?: PluginVersionsInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new PluginVersionsInstance(operationVersion, payload, instance._solution.pluginSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: PluginVersionsContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginVersionsInstance(operationVersion, response.body, instance._solution.pluginSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PluginVersionsPayload extends TwilioResponsePayload { + plugin_versions: PluginVersionsResource[]; +} + +interface PluginVersionsResource { + sid: string; + plugin_sid: string; + account_sid: string; + version: string; + plugin_url: string; + changelog: string; + private: boolean; + archived: boolean; + validated: boolean; + date_created: Date; + url: string; +} + +export class PluginVersionsInstance { + protected _solution: PluginVersionsContextSolution; + protected _context?: PluginVersionsContext; + + constructor(protected _version: V1, payload: PluginVersionsResource, pluginSid: string, sid?: string) { + + this.sid = (payload.sid); + this.pluginSid = (payload.plugin_sid); + this.accountSid = (payload.account_sid); + this.version = (payload.version); + this.pluginUrl = (payload.plugin_url); + this.changelog = (payload.changelog); + this._private = (payload.private); + this.archived = (payload.archived); + this.validated = (payload.validated); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { pluginSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Flex Plugin Version resource. + */ + sid: string; + /** + * The SID of the Flex Plugin resource this Flex Plugin Version belongs to. + */ + pluginSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Version resource and owns this resource. + */ + accountSid: string; + /** + * The unique version of this Flex Plugin Version. + */ + version: string; + /** + * The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + */ + pluginUrl: string; + /** + * A changelog that describes the changes this Flex Plugin Version brings. + */ + changelog: string; + /** + * Whether the Flex Plugin Version is validated. The default value is false. + */ + _private: boolean; + /** + * Whether the Flex Plugin Version is archived. The default value is false. + */ + archived: boolean; + validated: boolean; + /** + * The date and time in GMT when the Flex Plugin Version was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Flex Plugin Version resource. + */ + url: string; + + private get _proxy(): PluginVersionsContext { + this._context = this._context || new PluginVersionsContextImpl(this._version, this._solution.pluginSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a PluginVersionsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionsInstance + */ + fetch(callback?: (error: Error | null, item?: PluginVersionsInstance) => any): Promise; + /** + * Fetch a PluginVersionsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionsInstance + */ + fetch(params: PluginVersionsContextFetchOptions, callback?: (error: Error | null, item?: PluginVersionsInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: PluginVersionsInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a PluginVersionsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a PluginVersionsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PluginVersionsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + pluginSid: this.pluginSid, + accountSid: this.accountSid, + version: this.version, + pluginUrl: this.pluginUrl, + changelog: this.changelog, + _private: this._private, + archived: this.archived, + validated: this.validated, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PluginVersionsSolution { + pluginSid: string; +} + +export interface PluginVersionsListInstance { + _version: V1; + _solution: PluginVersionsSolution; + _uri: string; + + (sid: string, ): PluginVersionsContext; + get(sid: string, ): PluginVersionsContext; + + + + + /** + * Create a PluginVersionsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionsInstance + */ + create(params: PluginVersionsListInstanceCreateOptions, callback?: (error: Error | null, item?: PluginVersionsInstance) => any): Promise; + + /** + * Create a PluginVersionsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionsInstance with HTTP metadata + */ + createWithHttpInfo(params: PluginVersionsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams PluginVersionsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginVersionsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PluginVersionsInstance, done: (err?: Error) => void) => void): void; + each(params: PluginVersionsListInstanceEachOptions, callback?: (item: PluginVersionsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PluginVersionsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginVersionsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PluginVersionsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PluginVersionsListInstanceEachOptions, callback?: (item: PluginVersionsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PluginVersionsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PluginVersionsPage) => any): Promise; + /** + * Retrieve a single target page of PluginVersionsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists PluginVersionsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginVersionsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PluginVersionsInstance[]) => any): Promise; + list(params: PluginVersionsListInstanceOptions, callback?: (error: Error | null, items: PluginVersionsInstance[]) => any): Promise; + /** + * Lists PluginVersionsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginVersionsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: PluginVersionsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of PluginVersionsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginVersionsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PluginVersionsPage) => any): Promise; + page(params: PluginVersionsListInstancePageOptions, callback?: (error: Error | null, items: PluginVersionsPage) => any): Promise; + /** + * Retrieve a single page of PluginVersionsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginVersionsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: PluginVersionsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PluginVersionsListInstance(version: V1, pluginSid: string): PluginVersionsListInstance { + if (!isValidPathParam(pluginSid)) { + throw new Error('Parameter \'pluginSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as PluginVersionsListInstance; + + instance.get = function get(sid, ): PluginVersionsContext { + return new PluginVersionsContextImpl(version, pluginSid, sid); + } + + instance._version = version; + instance._solution = { pluginSid, }; + instance._uri = `/PluginService/Plugins/${pluginSid}/Versions`; + + instance.create = function create(params: PluginVersionsListInstanceCreateOptions, callback?: (error: Error | null, items: PluginVersionsInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["versionParam"] === null || params["versionParam"] === undefined) { + throw new Error('Required parameter "params[\'versionParam\']" missing.'); + } + + if (params["pluginUrl"] === null || params["pluginUrl"] === undefined) { + throw new Error('Required parameter "params[\'pluginUrl\']" missing.'); + } + + let data: any = {}; + + + + data["Version"] = params["versionParam"]; + + data["PluginUrl"] = params["pluginUrl"]; + if (params["changelog"] !== undefined) + data["Changelog"] = params["changelog"]; + if (params["private"] !== undefined) + data["Private"] = serialize.bool(params["private"]); + if (params["cliVersion"] !== undefined) + data["CliVersion"] = params["cliVersion"]; + if (params["validateStatus"] !== undefined) + data["ValidateStatus"] = params["validateStatus"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PluginVersionsInstance(operationVersion, payload, instance._solution.pluginSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: PluginVersionsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["versionParam"] === null || params["versionParam"] === undefined) { + throw new Error('Required parameter "params[\'versionParam\']" missing.'); + } + + if (params["pluginUrl"] === null || params["pluginUrl"] === undefined) { + throw new Error('Required parameter "params[\'pluginUrl\']" missing.'); + } + + let data: any = {}; + + + + data["Version"] = params["versionParam"]; + + data["PluginUrl"] = params["pluginUrl"]; + if (params["changelog"] !== undefined) + data["Changelog"] = params["changelog"]; + if (params["private"] !== undefined) + data["Private"] = serialize.bool(params["private"]); + if (params["cliVersion"] !== undefined) + data["CliVersion"] = params["cliVersion"]; + if (params["validateStatus"] !== undefined) + data["ValidateStatus"] = params["validateStatus"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginVersionsInstance(operationVersion, response.body, instance._solution.pluginSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: PluginVersionsListInstancePageOptions | ((error: Error | null, items: PluginVersionsPage) => any), callback?: (error: Error | null, items: PluginVersionsPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PluginVersionsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PluginVersionsPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PluginVersionsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PluginVersionsListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PluginVersionsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PluginVersionsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PluginVersionsPage extends Page { +/** +* Initialize the PluginVersionsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: PluginVersionsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PluginVersionsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PluginVersionsResource): PluginVersionsInstance { + + return new PluginVersionsInstance( + this._version, + payload, + this._solution.pluginSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/pluginArchive.ts b/rest/flexApi/v1/pluginArchive.ts new file mode 100644 index 000000000..c671b99fd --- /dev/null +++ b/rest/flexApi/v1/pluginArchive.ts @@ -0,0 +1,365 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to update a PluginArchiveInstance + */ +export interface PluginArchiveContextUpdateOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; +} + +export interface PluginArchiveContext { + + /** + * Update a PluginArchiveInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginArchiveInstance + */ + update(callback?: (error: Error | null, item?: PluginArchiveInstance) => any): Promise; + /** + * Update a PluginArchiveInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginArchiveInstance + */ + update(params: PluginArchiveContextUpdateOptions, callback?: (error: Error | null, item?: PluginArchiveInstance) => any): Promise; + + /** + * Update a PluginArchiveInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a PluginArchiveInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(params: PluginArchiveContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PluginArchiveContextSolution { + "sid": string; +} + +export class PluginArchiveContextImpl implements PluginArchiveContext { + protected _solution: PluginArchiveContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/PluginService/Plugins/${sid}/Archive`; + } + + update(params?: PluginArchiveContextUpdateOptions | ((error: Error | null, item?: PluginArchiveInstance) => any),callback?: (error: Error | null, item?: PluginArchiveInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PluginArchiveInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: PluginArchiveContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginArchiveInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PluginArchivePayload extends PluginArchiveResource {} + +interface PluginArchiveResource { + sid: string; + account_sid: string; + unique_name: string; + friendly_name: string; + description: string; + archived: boolean; + date_created: Date; + date_updated: Date; + url: string; +} + +export class PluginArchiveInstance { + protected _solution: PluginArchiveContextSolution; + protected _context?: PluginArchiveContext; + + constructor(protected _version: V1, payload: PluginArchiveResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.uniqueName = (payload.unique_name); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.archived = (payload.archived); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Flex Plugin resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin resource and owns this resource. + */ + accountSid: string; + /** + * The name that uniquely identifies this Flex Plugin resource. + */ + uniqueName: string; + /** + * The friendly name this Flex Plugin resource. + */ + friendlyName: string; + /** + * A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + */ + description: string; + /** + * Whether the Flex Plugin is archived. The default value is false. + */ + archived: boolean; + /** + * The date and time in GMT when the Flex Plugin was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Flex Plugin was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Flex Plugin resource. + */ + url: string; + + private get _proxy(): PluginArchiveContext { + this._context = this._context || new PluginArchiveContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Update a PluginArchiveInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginArchiveInstance + */ + update(callback?: (error: Error | null, item?: PluginArchiveInstance) => any): Promise; + /** + * Update a PluginArchiveInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginArchiveInstance + */ + update(params: PluginArchiveContextUpdateOptions, callback?: (error: Error | null, item?: PluginArchiveInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: PluginArchiveInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a PluginArchiveInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a PluginArchiveInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(params: PluginArchiveContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + uniqueName: this.uniqueName, + friendlyName: this.friendlyName, + description: this.description, + archived: this.archived, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PluginArchiveSolution { +} + +export interface PluginArchiveListInstance { + _version: V1; + _solution: PluginArchiveSolution; + _uri: string; + + (sid: string, ): PluginArchiveContext; + get(sid: string, ): PluginArchiveContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PluginArchiveListInstance(version: V1): PluginArchiveListInstance { + const instance = ((sid, ) => instance.get(sid, )) as PluginArchiveListInstance; + + instance.get = function get(sid, ): PluginArchiveContext { + return new PluginArchiveContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/flexApi/v1/pluginConfiguration.ts b/rest/flexApi/v1/pluginConfiguration.ts new file mode 100644 index 000000000..f5a876355 --- /dev/null +++ b/rest/flexApi/v1/pluginConfiguration.ts @@ -0,0 +1,775 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ConfiguredPluginListInstance } from "./pluginConfiguration/configuredPlugin"; + + + +/** + * Options to pass to fetch a PluginConfigurationInstance + */ +export interface PluginConfigurationContextFetchOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; +} + +/** + * Options to pass to create a PluginConfigurationInstance + */ +export interface PluginConfigurationListInstanceCreateOptions { + /** The Flex Plugin Configuration\\\'s name. */ + "name": string; + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. */ + "plugins"?: Array; + /** The Flex Plugin Configuration\\\'s description. */ + "description"?: string; +} + +/** + * Options to pass to each + */ +export interface PluginConfigurationListInstanceEachOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PluginConfigurationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PluginConfigurationListInstanceOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PluginConfigurationListInstancePageOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PluginConfigurationContext { + plugins: ConfiguredPluginListInstance; + + /** + * Fetch a PluginConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: PluginConfigurationInstance) => any): Promise; + /** + * Fetch a PluginConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationInstance + */ + fetch(params: PluginConfigurationContextFetchOptions, callback?: (error: Error | null, item?: PluginConfigurationInstance) => any): Promise; + + /** + * Fetch a PluginConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a PluginConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PluginConfigurationContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PluginConfigurationContextSolution { + "sid": string; +} + +export class PluginConfigurationContextImpl implements PluginConfigurationContext { + protected _solution: PluginConfigurationContextSolution; + protected _uri: string; + + protected _plugins?: ConfiguredPluginListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/PluginService/Configurations/${sid}`; + } + + get plugins(): ConfiguredPluginListInstance { + this._plugins = this._plugins || ConfiguredPluginListInstance(this._version, this._solution.sid); + return this._plugins; + } + + fetch(params?: PluginConfigurationContextFetchOptions | ((error: Error | null, item?: PluginConfigurationInstance) => any),callback?: (error: Error | null, item?: PluginConfigurationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new PluginConfigurationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: PluginConfigurationContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginConfigurationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PluginConfigurationPayload extends TwilioResponsePayload { + configurations: PluginConfigurationResource[]; +} + +interface PluginConfigurationResource { + sid: string; + account_sid: string; + name: string; + description: string; + archived: boolean; + date_created: Date; + url: string; + links: Record; +} + +export class PluginConfigurationInstance { + protected _solution: PluginConfigurationContextSolution; + protected _context?: PluginConfigurationContext; + + constructor(protected _version: V1, payload: PluginConfigurationResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.name = (payload.name); + this.description = (payload.description); + this.archived = (payload.archived); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Flex Plugin Configuration resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Configuration resource and owns this resource. + */ + accountSid: string; + /** + * The name of this Flex Plugin Configuration. + */ + name: string; + /** + * The description of the Flex Plugin Configuration resource. + */ + description: string; + /** + * Whether the Flex Plugin Configuration is archived. The default value is false. + */ + archived: boolean; + /** + * The date and time in GMT when the Flex Plugin Configuration was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Flex Plugin Configuration resource. + */ + url: string; + links: Record; + + private get _proxy(): PluginConfigurationContext { + this._context = this._context || new PluginConfigurationContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a PluginConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: PluginConfigurationInstance) => any): Promise; + /** + * Fetch a PluginConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationInstance + */ + fetch(params: PluginConfigurationContextFetchOptions, callback?: (error: Error | null, item?: PluginConfigurationInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: PluginConfigurationInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a PluginConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a PluginConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PluginConfigurationContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Access the plugins. + */ + plugins(): ConfiguredPluginListInstance { + return this._proxy.plugins; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + name: this.name, + description: this.description, + archived: this.archived, + dateCreated: this.dateCreated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PluginConfigurationSolution { +} + +export interface PluginConfigurationListInstance { + _version: V1; + _solution: PluginConfigurationSolution; + _uri: string; + + (sid: string, ): PluginConfigurationContext; + get(sid: string, ): PluginConfigurationContext; + + + + + /** + * Create a PluginConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationInstance + */ + create(params: PluginConfigurationListInstanceCreateOptions, callback?: (error: Error | null, item?: PluginConfigurationInstance) => any): Promise; + + /** + * Create a PluginConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: PluginConfigurationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams PluginConfigurationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PluginConfigurationInstance, done: (err?: Error) => void) => void): void; + each(params: PluginConfigurationListInstanceEachOptions, callback?: (item: PluginConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PluginConfigurationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PluginConfigurationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PluginConfigurationListInstanceEachOptions, callback?: (item: PluginConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PluginConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PluginConfigurationPage) => any): Promise; + /** + * Retrieve a single target page of PluginConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists PluginConfigurationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PluginConfigurationInstance[]) => any): Promise; + list(params: PluginConfigurationListInstanceOptions, callback?: (error: Error | null, items: PluginConfigurationInstance[]) => any): Promise; + /** + * Lists PluginConfigurationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: PluginConfigurationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of PluginConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PluginConfigurationPage) => any): Promise; + page(params: PluginConfigurationListInstancePageOptions, callback?: (error: Error | null, items: PluginConfigurationPage) => any): Promise; + /** + * Retrieve a single page of PluginConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: PluginConfigurationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PluginConfigurationListInstance(version: V1): PluginConfigurationListInstance { + const instance = ((sid, ) => instance.get(sid, )) as PluginConfigurationListInstance; + + instance.get = function get(sid, ): PluginConfigurationContext { + return new PluginConfigurationContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/PluginService/Configurations`; + + instance.create = function create(params: PluginConfigurationListInstanceCreateOptions, callback?: (error: Error | null, items: PluginConfigurationInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["name"] === null || params["name"] === undefined) { + throw new Error('Required parameter "params[\'name\']" missing.'); + } + + let data: any = {}; + + + + data["Name"] = params["name"]; + if (params["plugins"] !== undefined) + data["Plugins"] = serialize.map(params["plugins"], (e: any) => serialize.object(e)); + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PluginConfigurationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: PluginConfigurationListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["name"] === null || params["name"] === undefined) { + throw new Error('Required parameter "params[\'name\']" missing.'); + } + + let data: any = {}; + + + + data["Name"] = params["name"]; + if (params["plugins"] !== undefined) + data["Plugins"] = serialize.map(params["plugins"], (e: any) => serialize.object(e)); + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginConfigurationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: PluginConfigurationListInstancePageOptions | ((error: Error | null, items: PluginConfigurationPage) => any), callback?: (error: Error | null, items: PluginConfigurationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PluginConfigurationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PluginConfigurationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PluginConfigurationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PluginConfigurationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PluginConfigurationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PluginConfigurationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PluginConfigurationPage extends Page { +/** +* Initialize the PluginConfigurationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: PluginConfigurationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PluginConfigurationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PluginConfigurationResource): PluginConfigurationInstance { + + return new PluginConfigurationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/pluginConfiguration/configuredPlugin.ts b/rest/flexApi/v1/pluginConfiguration/configuredPlugin.ts new file mode 100644 index 000000000..c7f7df497 --- /dev/null +++ b/rest/flexApi/v1/pluginConfiguration/configuredPlugin.ts @@ -0,0 +1,715 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a ConfiguredPluginInstance + */ +export interface ConfiguredPluginContextFetchOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; +} + +/** + * Options to pass to each + */ +export interface ConfiguredPluginListInstanceEachOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConfiguredPluginInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConfiguredPluginListInstanceOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConfiguredPluginListInstancePageOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ConfiguredPluginContext { + + /** + * Fetch a ConfiguredPluginInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfiguredPluginInstance + */ + fetch(callback?: (error: Error | null, item?: ConfiguredPluginInstance) => any): Promise; + /** + * Fetch a ConfiguredPluginInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfiguredPluginInstance + */ + fetch(params: ConfiguredPluginContextFetchOptions, callback?: (error: Error | null, item?: ConfiguredPluginInstance) => any): Promise; + + /** + * Fetch a ConfiguredPluginInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfiguredPluginInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a ConfiguredPluginInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfiguredPluginInstance with HTTP metadata + */ + fetchWithHttpInfo(params: ConfiguredPluginContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConfiguredPluginContextSolution { + "configurationSid": string; + "pluginSid": string; +} + +export class ConfiguredPluginContextImpl implements ConfiguredPluginContext { + protected _solution: ConfiguredPluginContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, configurationSid: string, pluginSid: string) { + if (!isValidPathParam(configurationSid)) { + throw new Error('Parameter \'configurationSid\' is not valid.'); + } + + if (!isValidPathParam(pluginSid)) { + throw new Error('Parameter \'pluginSid\' is not valid.'); + } + + this._solution = { configurationSid, pluginSid, }; + this._uri = `/PluginService/Configurations/${configurationSid}/Plugins/${pluginSid}`; + } + + fetch(params?: ConfiguredPluginContextFetchOptions | ((error: Error | null, item?: ConfiguredPluginInstance) => any),callback?: (error: Error | null, item?: ConfiguredPluginInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new ConfiguredPluginInstance(operationVersion, payload, instance._solution.configurationSid, instance._solution.pluginSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: ConfiguredPluginContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfiguredPluginInstance(operationVersion, response.body, instance._solution.configurationSid, instance._solution.pluginSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConfiguredPluginPayload extends TwilioResponsePayload { + plugins: ConfiguredPluginResource[]; +} + +interface ConfiguredPluginResource { + account_sid: string; + configuration_sid: string; + plugin_sid: string; + plugin_version_sid: string; + phase: number; + plugin_url: string; + unique_name: string; + friendly_name: string; + description: string; + plugin_archived: boolean; + version: string; + changelog: string; + plugin_version_archived: boolean; + private: boolean; + date_created: Date; + url: string; +} + +export class ConfiguredPluginInstance { + protected _solution: ConfiguredPluginContextSolution; + protected _context?: ConfiguredPluginContext; + + constructor(protected _version: V1, payload: ConfiguredPluginResource, configurationSid: string, pluginSid?: string) { + + this.accountSid = (payload.account_sid); + this.configurationSid = (payload.configuration_sid); + this.pluginSid = (payload.plugin_sid); + this.pluginVersionSid = (payload.plugin_version_sid); + this.phase = deserialize.integer(payload.phase); + this.pluginUrl = (payload.plugin_url); + this.uniqueName = (payload.unique_name); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.pluginArchived = (payload.plugin_archived); + this.version = (payload.version); + this.changelog = (payload.changelog); + this.pluginVersionArchived = (payload.plugin_version_archived); + this._private = (payload.private); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { configurationSid, pluginSid: pluginSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Flex Plugin resource is installed for. + */ + accountSid: string; + /** + * The SID of the Flex Plugin Configuration that this Flex Plugin belongs to. + */ + configurationSid: string; + /** + * The SID of the Flex Plugin. + */ + pluginSid: string; + /** + * The SID of the Flex Plugin Version. + */ + pluginVersionSid: string; + /** + * The phase this Flex Plugin would initialize at runtime. + */ + phase: number; + /** + * The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + */ + pluginUrl: string; + /** + * The name that uniquely identifies this Flex Plugin resource. + */ + uniqueName: string; + /** + * The friendly name of this Flex Plugin resource. + */ + friendlyName: string; + /** + * A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + */ + description: string; + /** + * Whether the Flex Plugin is archived. The default value is false. + */ + pluginArchived: boolean; + /** + * The latest version of this Flex Plugin Version. + */ + version: string; + /** + * A changelog that describes the changes this Flex Plugin Version brings. + */ + changelog: string; + /** + * Whether the Flex Plugin Version is archived. The default value is false. + */ + pluginVersionArchived: boolean; + /** + * Whether to validate the request is authorized to access the Flex Plugin Version. + */ + _private: boolean; + /** + * The date and time in GMT when the Flex Plugin was installed specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Flex Plugin resource. + */ + url: string; + + private get _proxy(): ConfiguredPluginContext { + this._context = this._context || new ConfiguredPluginContextImpl(this._version, this._solution.configurationSid, this._solution.pluginSid); + return this._context; + } + + /** + * Fetch a ConfiguredPluginInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfiguredPluginInstance + */ + fetch(callback?: (error: Error | null, item?: ConfiguredPluginInstance) => any): Promise; + /** + * Fetch a ConfiguredPluginInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfiguredPluginInstance + */ + fetch(params: ConfiguredPluginContextFetchOptions, callback?: (error: Error | null, item?: ConfiguredPluginInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: ConfiguredPluginInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a ConfiguredPluginInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfiguredPluginInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a ConfiguredPluginInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfiguredPluginInstance with HTTP metadata + */ + fetchWithHttpInfo(params: ConfiguredPluginContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + configurationSid: this.configurationSid, + pluginSid: this.pluginSid, + pluginVersionSid: this.pluginVersionSid, + phase: this.phase, + pluginUrl: this.pluginUrl, + uniqueName: this.uniqueName, + friendlyName: this.friendlyName, + description: this.description, + pluginArchived: this.pluginArchived, + version: this.version, + changelog: this.changelog, + pluginVersionArchived: this.pluginVersionArchived, + _private: this._private, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConfiguredPluginSolution { + configurationSid: string; +} + +export interface ConfiguredPluginListInstance { + _version: V1; + _solution: ConfiguredPluginSolution; + _uri: string; + + (pluginSid: string, ): ConfiguredPluginContext; + get(pluginSid: string, ): ConfiguredPluginContext; + + + + + + /** + * Streams ConfiguredPluginInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfiguredPluginListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConfiguredPluginInstance, done: (err?: Error) => void) => void): void; + each(params: ConfiguredPluginListInstanceEachOptions, callback?: (item: ConfiguredPluginInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConfiguredPluginInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfiguredPluginListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConfiguredPluginInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConfiguredPluginListInstanceEachOptions, callback?: (item: ConfiguredPluginInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConfiguredPluginInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConfiguredPluginPage) => any): Promise; + /** + * Retrieve a single target page of ConfiguredPluginInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConfiguredPluginInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfiguredPluginListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConfiguredPluginInstance[]) => any): Promise; + list(params: ConfiguredPluginListInstanceOptions, callback?: (error: Error | null, items: ConfiguredPluginInstance[]) => any): Promise; + /** + * Lists ConfiguredPluginInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfiguredPluginListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConfiguredPluginListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConfiguredPluginInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfiguredPluginListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConfiguredPluginPage) => any): Promise; + page(params: ConfiguredPluginListInstancePageOptions, callback?: (error: Error | null, items: ConfiguredPluginPage) => any): Promise; + /** + * Retrieve a single page of ConfiguredPluginInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfiguredPluginListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConfiguredPluginListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConfiguredPluginListInstance(version: V1, configurationSid: string): ConfiguredPluginListInstance { + if (!isValidPathParam(configurationSid)) { + throw new Error('Parameter \'configurationSid\' is not valid.'); + } + + const instance = ((pluginSid, ) => instance.get(pluginSid, )) as ConfiguredPluginListInstance; + + instance.get = function get(pluginSid, ): ConfiguredPluginContext { + return new ConfiguredPluginContextImpl(version, configurationSid, pluginSid); + } + + instance._version = version; + instance._solution = { configurationSid, }; + instance._uri = `/PluginService/Configurations/${configurationSid}/Plugins`; + + instance.page = function page(params?: ConfiguredPluginListInstancePageOptions | ((error: Error | null, items: ConfiguredPluginPage) => any), callback?: (error: Error | null, items: ConfiguredPluginPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConfiguredPluginPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConfiguredPluginPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConfiguredPluginPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConfiguredPluginListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConfiguredPluginPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConfiguredPluginPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConfiguredPluginPage extends Page { +/** +* Initialize the ConfiguredPluginPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ConfiguredPluginSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ConfiguredPluginInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConfiguredPluginResource): ConfiguredPluginInstance { + + return new ConfiguredPluginInstance( + this._version, + payload, + this._solution.configurationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/pluginConfigurationArchive.ts b/rest/flexApi/v1/pluginConfigurationArchive.ts new file mode 100644 index 000000000..41670ec38 --- /dev/null +++ b/rest/flexApi/v1/pluginConfigurationArchive.ts @@ -0,0 +1,351 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to update a PluginConfigurationArchiveInstance + */ +export interface PluginConfigurationArchiveContextUpdateOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; +} + +export interface PluginConfigurationArchiveContext { + + /** + * Update a PluginConfigurationArchiveInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationArchiveInstance + */ + update(callback?: (error: Error | null, item?: PluginConfigurationArchiveInstance) => any): Promise; + /** + * Update a PluginConfigurationArchiveInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationArchiveInstance + */ + update(params: PluginConfigurationArchiveContextUpdateOptions, callback?: (error: Error | null, item?: PluginConfigurationArchiveInstance) => any): Promise; + + /** + * Update a PluginConfigurationArchiveInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a PluginConfigurationArchiveInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(params: PluginConfigurationArchiveContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PluginConfigurationArchiveContextSolution { + "sid": string; +} + +export class PluginConfigurationArchiveContextImpl implements PluginConfigurationArchiveContext { + protected _solution: PluginConfigurationArchiveContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/PluginService/Configurations/${sid}/Archive`; + } + + update(params?: PluginConfigurationArchiveContextUpdateOptions | ((error: Error | null, item?: PluginConfigurationArchiveInstance) => any),callback?: (error: Error | null, item?: PluginConfigurationArchiveInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PluginConfigurationArchiveInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: PluginConfigurationArchiveContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginConfigurationArchiveInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PluginConfigurationArchivePayload extends PluginConfigurationArchiveResource {} + +interface PluginConfigurationArchiveResource { + sid: string; + account_sid: string; + name: string; + description: string; + archived: boolean; + date_created: Date; + url: string; +} + +export class PluginConfigurationArchiveInstance { + protected _solution: PluginConfigurationArchiveContextSolution; + protected _context?: PluginConfigurationArchiveContext; + + constructor(protected _version: V1, payload: PluginConfigurationArchiveResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.name = (payload.name); + this.description = (payload.description); + this.archived = (payload.archived); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Flex Plugin Configuration resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Configuration resource and owns this resource. + */ + accountSid: string; + /** + * The name of this Flex Plugin Configuration. + */ + name: string; + /** + * The description of the Flex Plugin Configuration resource. + */ + description: string; + /** + * Whether the Flex Plugin Configuration is archived. The default value is false. + */ + archived: boolean; + /** + * The date and time in GMT when the Flex Plugin Configuration was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Flex Plugin Configuration resource. + */ + url: string; + + private get _proxy(): PluginConfigurationArchiveContext { + this._context = this._context || new PluginConfigurationArchiveContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Update a PluginConfigurationArchiveInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationArchiveInstance + */ + update(callback?: (error: Error | null, item?: PluginConfigurationArchiveInstance) => any): Promise; + /** + * Update a PluginConfigurationArchiveInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationArchiveInstance + */ + update(params: PluginConfigurationArchiveContextUpdateOptions, callback?: (error: Error | null, item?: PluginConfigurationArchiveInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: PluginConfigurationArchiveInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a PluginConfigurationArchiveInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a PluginConfigurationArchiveInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginConfigurationArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(params: PluginConfigurationArchiveContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + name: this.name, + description: this.description, + archived: this.archived, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PluginConfigurationArchiveSolution { +} + +export interface PluginConfigurationArchiveListInstance { + _version: V1; + _solution: PluginConfigurationArchiveSolution; + _uri: string; + + (sid: string, ): PluginConfigurationArchiveContext; + get(sid: string, ): PluginConfigurationArchiveContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PluginConfigurationArchiveListInstance(version: V1): PluginConfigurationArchiveListInstance { + const instance = ((sid, ) => instance.get(sid, )) as PluginConfigurationArchiveListInstance; + + instance.get = function get(sid, ): PluginConfigurationArchiveContext { + return new PluginConfigurationArchiveContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/flexApi/v1/pluginRelease.ts b/rest/flexApi/v1/pluginRelease.ts new file mode 100644 index 000000000..77f13679d --- /dev/null +++ b/rest/flexApi/v1/pluginRelease.ts @@ -0,0 +1,730 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a PluginReleaseInstance + */ +export interface PluginReleaseContextFetchOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; +} + +/** + * Options to pass to create a PluginReleaseInstance + */ +export interface PluginReleaseListInstanceCreateOptions { + /** The SID or the Version of the Flex Plugin Configuration to release. */ + "configurationId": string; + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; +} + +/** + * Options to pass to each + */ +export interface PluginReleaseListInstanceEachOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PluginReleaseInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PluginReleaseListInstanceOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PluginReleaseListInstancePageOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PluginReleaseContext { + + /** + * Fetch a PluginReleaseInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginReleaseInstance + */ + fetch(callback?: (error: Error | null, item?: PluginReleaseInstance) => any): Promise; + /** + * Fetch a PluginReleaseInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginReleaseInstance + */ + fetch(params: PluginReleaseContextFetchOptions, callback?: (error: Error | null, item?: PluginReleaseInstance) => any): Promise; + + /** + * Fetch a PluginReleaseInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginReleaseInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a PluginReleaseInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginReleaseInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PluginReleaseContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PluginReleaseContextSolution { + "sid": string; +} + +export class PluginReleaseContextImpl implements PluginReleaseContext { + protected _solution: PluginReleaseContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/PluginService/Releases/${sid}`; + } + + fetch(params?: PluginReleaseContextFetchOptions | ((error: Error | null, item?: PluginReleaseInstance) => any),callback?: (error: Error | null, item?: PluginReleaseInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new PluginReleaseInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: PluginReleaseContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginReleaseInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PluginReleasePayload extends TwilioResponsePayload { + releases: PluginReleaseResource[]; +} + +interface PluginReleaseResource { + sid: string; + account_sid: string; + configuration_sid: string; + date_created: Date; + url: string; +} + +export class PluginReleaseInstance { + protected _solution: PluginReleaseContextSolution; + protected _context?: PluginReleaseContext; + + constructor(protected _version: V1, payload: PluginReleaseResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.configurationSid = (payload.configuration_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Plugin Release resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Plugin Release resource and owns this resource. + */ + accountSid: string; + /** + * The SID of the Plugin Configuration resource to release. + */ + configurationSid: string; + /** + * The date and time in GMT when the Flex Plugin Release was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Plugin Release resource. + */ + url: string; + + private get _proxy(): PluginReleaseContext { + this._context = this._context || new PluginReleaseContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a PluginReleaseInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginReleaseInstance + */ + fetch(callback?: (error: Error | null, item?: PluginReleaseInstance) => any): Promise; + /** + * Fetch a PluginReleaseInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginReleaseInstance + */ + fetch(params: PluginReleaseContextFetchOptions, callback?: (error: Error | null, item?: PluginReleaseInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: PluginReleaseInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a PluginReleaseInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginReleaseInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a PluginReleaseInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginReleaseInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PluginReleaseContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + configurationSid: this.configurationSid, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PluginReleaseSolution { +} + +export interface PluginReleaseListInstance { + _version: V1; + _solution: PluginReleaseSolution; + _uri: string; + + (sid: string, ): PluginReleaseContext; + get(sid: string, ): PluginReleaseContext; + + + + + /** + * Create a PluginReleaseInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginReleaseInstance + */ + create(params: PluginReleaseListInstanceCreateOptions, callback?: (error: Error | null, item?: PluginReleaseInstance) => any): Promise; + + /** + * Create a PluginReleaseInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginReleaseInstance with HTTP metadata + */ + createWithHttpInfo(params: PluginReleaseListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams PluginReleaseInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginReleaseListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PluginReleaseInstance, done: (err?: Error) => void) => void): void; + each(params: PluginReleaseListInstanceEachOptions, callback?: (item: PluginReleaseInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PluginReleaseInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginReleaseListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PluginReleaseInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PluginReleaseListInstanceEachOptions, callback?: (item: PluginReleaseInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PluginReleaseInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PluginReleasePage) => any): Promise; + /** + * Retrieve a single target page of PluginReleaseInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists PluginReleaseInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginReleaseListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PluginReleaseInstance[]) => any): Promise; + list(params: PluginReleaseListInstanceOptions, callback?: (error: Error | null, items: PluginReleaseInstance[]) => any): Promise; + /** + * Lists PluginReleaseInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginReleaseListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: PluginReleaseListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of PluginReleaseInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginReleaseListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PluginReleasePage) => any): Promise; + page(params: PluginReleaseListInstancePageOptions, callback?: (error: Error | null, items: PluginReleasePage) => any): Promise; + /** + * Retrieve a single page of PluginReleaseInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PluginReleaseListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: PluginReleaseListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PluginReleaseListInstance(version: V1): PluginReleaseListInstance { + const instance = ((sid, ) => instance.get(sid, )) as PluginReleaseListInstance; + + instance.get = function get(sid, ): PluginReleaseContext { + return new PluginReleaseContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/PluginService/Releases`; + + instance.create = function create(params: PluginReleaseListInstanceCreateOptions, callback?: (error: Error | null, items: PluginReleaseInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["configurationId"] === null || params["configurationId"] === undefined) { + throw new Error('Required parameter "params[\'configurationId\']" missing.'); + } + + let data: any = {}; + + + + data["ConfigurationId"] = params["configurationId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PluginReleaseInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: PluginReleaseListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["configurationId"] === null || params["configurationId"] === undefined) { + throw new Error('Required parameter "params[\'configurationId\']" missing.'); + } + + let data: any = {}; + + + + data["ConfigurationId"] = params["configurationId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginReleaseInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: PluginReleaseListInstancePageOptions | ((error: Error | null, items: PluginReleasePage) => any), callback?: (error: Error | null, items: PluginReleasePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PluginReleasePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PluginReleasePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PluginReleasePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PluginReleaseListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PluginReleasePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PluginReleasePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PluginReleasePage extends Page { +/** +* Initialize the PluginReleasePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: PluginReleaseSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PluginReleaseInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PluginReleaseResource): PluginReleaseInstance { + + return new PluginReleaseInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v1/pluginVersionArchive.ts b/rest/flexApi/v1/pluginVersionArchive.ts new file mode 100644 index 000000000..6c09dd17a --- /dev/null +++ b/rest/flexApi/v1/pluginVersionArchive.ts @@ -0,0 +1,377 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to update a PluginVersionArchiveInstance + */ +export interface PluginVersionArchiveContextUpdateOptions { + /** The Flex-Metadata HTTP request header */ + "flexMetadata"?: string; +} + +export interface PluginVersionArchiveContext { + + /** + * Update a PluginVersionArchiveInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionArchiveInstance + */ + update(callback?: (error: Error | null, item?: PluginVersionArchiveInstance) => any): Promise; + /** + * Update a PluginVersionArchiveInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionArchiveInstance + */ + update(params: PluginVersionArchiveContextUpdateOptions, callback?: (error: Error | null, item?: PluginVersionArchiveInstance) => any): Promise; + + /** + * Update a PluginVersionArchiveInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a PluginVersionArchiveInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(params: PluginVersionArchiveContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PluginVersionArchiveContextSolution { + "pluginSid": string; + "sid": string; +} + +export class PluginVersionArchiveContextImpl implements PluginVersionArchiveContext { + protected _solution: PluginVersionArchiveContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, pluginSid: string, sid: string) { + if (!isValidPathParam(pluginSid)) { + throw new Error('Parameter \'pluginSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { pluginSid, sid, }; + this._uri = `/PluginService/Plugins/${pluginSid}/Versions/${sid}/Archive`; + } + + update(params?: PluginVersionArchiveContextUpdateOptions | ((error: Error | null, item?: PluginVersionArchiveInstance) => any),callback?: (error: Error | null, item?: PluginVersionArchiveInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PluginVersionArchiveInstance(operationVersion, payload, instance._solution.pluginSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: PluginVersionArchiveContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["flexMetadata"] !== undefined) headers["Flex-Metadata"] = params["flexMetadata"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new PluginVersionArchiveInstance(operationVersion, response.body, instance._solution.pluginSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PluginVersionArchivePayload extends PluginVersionArchiveResource {} + +interface PluginVersionArchiveResource { + sid: string; + plugin_sid: string; + account_sid: string; + version: string; + plugin_url: string; + changelog: string; + private: boolean; + archived: boolean; + date_created: Date; + url: string; +} + +export class PluginVersionArchiveInstance { + protected _solution: PluginVersionArchiveContextSolution; + protected _context?: PluginVersionArchiveContext; + + constructor(protected _version: V1, payload: PluginVersionArchiveResource, pluginSid?: string, sid?: string) { + + this.sid = (payload.sid); + this.pluginSid = (payload.plugin_sid); + this.accountSid = (payload.account_sid); + this.version = (payload.version); + this.pluginUrl = (payload.plugin_url); + this.changelog = (payload.changelog); + this._private = (payload.private); + this.archived = (payload.archived); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { pluginSid: pluginSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Flex Plugin Version resource. + */ + sid: string; + /** + * The SID of the Flex Plugin resource this Flex Plugin Version belongs to. + */ + pluginSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Version resource and owns this resource. + */ + accountSid: string; + /** + * The unique version of this Flex Plugin Version. + */ + version: string; + /** + * The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + */ + pluginUrl: string; + /** + * A changelog that describes the changes this Flex Plugin Version brings. + */ + changelog: string; + /** + * Whether to inject credentials while accessing this Plugin Version. The default value is false. + */ + _private: boolean; + /** + * Whether the Flex Plugin Version is archived. The default value is false. + */ + archived: boolean; + /** + * The date and time in GMT when the Flex Plugin Version was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Flex Plugin Version resource. + */ + url: string; + + private get _proxy(): PluginVersionArchiveContext { + this._context = this._context || new PluginVersionArchiveContextImpl(this._version, this._solution.pluginSid, this._solution.sid); + return this._context; + } + + /** + * Update a PluginVersionArchiveInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionArchiveInstance + */ + update(callback?: (error: Error | null, item?: PluginVersionArchiveInstance) => any): Promise; + /** + * Update a PluginVersionArchiveInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionArchiveInstance + */ + update(params: PluginVersionArchiveContextUpdateOptions, callback?: (error: Error | null, item?: PluginVersionArchiveInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: PluginVersionArchiveInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a PluginVersionArchiveInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a PluginVersionArchiveInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PluginVersionArchiveInstance with HTTP metadata + */ + updateWithHttpInfo(params: PluginVersionArchiveContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + pluginSid: this.pluginSid, + accountSid: this.accountSid, + version: this.version, + pluginUrl: this.pluginUrl, + changelog: this.changelog, + _private: this._private, + archived: this.archived, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PluginVersionArchiveSolution { +} + +export interface PluginVersionArchiveListInstance { + _version: V1; + _solution: PluginVersionArchiveSolution; + _uri: string; + + (pluginSid: string, sid: string, ): PluginVersionArchiveContext; + get(pluginSid: string, sid: string, ): PluginVersionArchiveContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PluginVersionArchiveListInstance(version: V1): PluginVersionArchiveListInstance { + const instance = ((pluginSid, sid, ) => instance.get(pluginSid, sid, )) as PluginVersionArchiveListInstance; + + instance.get = function get(pluginSid, sid, ): PluginVersionArchiveContext { + return new PluginVersionArchiveContextImpl(version, pluginSid, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/flexApi/v1/provisioningStatus.ts b/rest/flexApi/v1/provisioningStatus.ts new file mode 100644 index 000000000..0fb77f6da --- /dev/null +++ b/rest/flexApi/v1/provisioningStatus.ts @@ -0,0 +1,238 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Email Provisioning Status + */ +export type ProvisioningStatusStatus = 'active'|'in-progress'|'not-configured'|'failed'; + + + +export interface ProvisioningStatusContext { + + /** + * Fetch a ProvisioningStatusInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProvisioningStatusInstance + */ + fetch(callback?: (error: Error | null, item?: ProvisioningStatusInstance) => any): Promise + + /** + * Fetch a ProvisioningStatusInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProvisioningStatusInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ProvisioningStatusContextSolution { +} + +export class ProvisioningStatusContextImpl implements ProvisioningStatusContext { + protected _solution: ProvisioningStatusContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/account/provision/status`; + } + + fetch(callback?: (error: Error | null, item?: ProvisioningStatusInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ProvisioningStatusInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ProvisioningStatusInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ProvisioningStatusPayload extends ProvisioningStatusResource {} + +interface ProvisioningStatusResource { + status: ProvisioningStatusStatus; + url: string; +} + +export class ProvisioningStatusInstance { + protected _solution: ProvisioningStatusContextSolution; + protected _context?: ProvisioningStatusContext; + + constructor(protected _version: V1, payload: ProvisioningStatusResource) { + + this.status = payload.status; + this.url = (payload.url); + + this._solution = { }; + } + + status: ProvisioningStatusStatus; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): ProvisioningStatusContext { + this._context = this._context || new ProvisioningStatusContextImpl(this._version); + return this._context; + } + + /** + * Fetch a ProvisioningStatusInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProvisioningStatusInstance + */ + fetch(callback?: (error: Error | null, item?: ProvisioningStatusInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ProvisioningStatusInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProvisioningStatusInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + status: this.status, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ProvisioningStatusSolution { +} + +export interface ProvisioningStatusListInstance { + _version: V1; + _solution: ProvisioningStatusSolution; + _uri: string; + + (): ProvisioningStatusContext; + get(): ProvisioningStatusContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ProvisioningStatusListInstance(version: V1): ProvisioningStatusListInstance { + const instance = (() => instance.get()) as ProvisioningStatusListInstance; + + instance.get = function get(): ProvisioningStatusContext { + return new ProvisioningStatusContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/flexApi/v1/webChannel.ts b/rest/flexApi/v1/webChannel.ts new file mode 100644 index 000000000..628fdd10a --- /dev/null +++ b/rest/flexApi/v1/webChannel.ts @@ -0,0 +1,951 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export type WebChannelChatStatus = 'inactive'; + + + + +/** + * Options to pass to update a WebChannelInstance + */ +export interface WebChannelContextUpdateOptions { + /** */ + "chatStatus"?: WebChannelChatStatus; + /** The post-engagement data. */ + "postEngagementData"?: string; +} + +/** + * Options to pass to create a WebChannelInstance + */ +export interface WebChannelListInstanceCreateOptions { + /** The SID of the Flex Flow. */ + "flexFlowSid": string; + /** The chat identity. */ + "identity": string; + /** The chat participant\\\'s friendly name. */ + "customerFriendlyName": string; + /** The chat channel\\\'s friendly name. */ + "chatFriendlyName": string; + /** The chat channel\\\'s unique name. */ + "chatUniqueName"?: string; + /** The pre-engagement data. */ + "preEngagementData"?: string; +} + +/** + * Options to pass to each + */ +export interface WebChannelListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: WebChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface WebChannelListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface WebChannelListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface WebChannelContext { + + /** + * Remove a WebChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a WebChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a WebChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance + */ + fetch(callback?: (error: Error | null, item?: WebChannelInstance) => any): Promise + + /** + * Fetch a WebChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a WebChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance + */ + update(callback?: (error: Error | null, item?: WebChannelInstance) => any): Promise; + /** + * Update a WebChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance + */ + update(params: WebChannelContextUpdateOptions, callback?: (error: Error | null, item?: WebChannelInstance) => any): Promise; + + /** + * Update a WebChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WebChannelContextSolution { + "sid": string; +} + +export class WebChannelContextImpl implements WebChannelContext { + protected _solution: WebChannelContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/WebChannels/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: WebChannelInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WebChannelInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebChannelInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WebChannelContextUpdateOptions | ((error: Error | null, item?: WebChannelInstance) => any),callback?: (error: Error | null, item?: WebChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["chatStatus"] !== undefined) + data["ChatStatus"] = params["chatStatus"]; + if (params["postEngagementData"] !== undefined) + data["PostEngagementData"] = params["postEngagementData"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebChannelInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WebChannelContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["chatStatus"] !== undefined) + data["ChatStatus"] = params["chatStatus"]; + if (params["postEngagementData"] !== undefined) + data["PostEngagementData"] = params["postEngagementData"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebChannelInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WebChannelPayload extends TwilioResponsePayload { + flex_chat_channels: WebChannelResource[]; +} + +interface WebChannelResource { + account_sid: string; + flex_flow_sid: string; + sid: string; + url: string; + date_created: Date; + date_updated: Date; +} + +export class WebChannelInstance { + protected _solution: WebChannelContextSolution; + protected _context?: WebChannelContext; + + constructor(protected _version: V1, payload: WebChannelResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.flexFlowSid = (payload.flex_flow_sid); + this.sid = (payload.sid); + this.url = (payload.url); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the WebChannel resource and owns this Workflow. + */ + accountSid: string; + /** + * The SID of the Flex Flow. + */ + flexFlowSid: string; + /** + * The unique string that we created to identify the WebChannel resource. + */ + sid: string; + /** + * The absolute URL of the WebChannel resource. + */ + url: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + private get _proxy(): WebChannelContext { + this._context = this._context || new WebChannelContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a WebChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a WebChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a WebChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance + */ + fetch(callback?: (error: Error | null, item?: WebChannelInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WebChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WebChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance + */ + update(callback?: (error: Error | null, item?: WebChannelInstance) => any): Promise; + /** + * Update a WebChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance + */ + update(params: WebChannelContextUpdateOptions, callback?: (error: Error | null, item?: WebChannelInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: WebChannelInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a WebChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + flexFlowSid: this.flexFlowSid, + sid: this.sid, + url: this.url, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WebChannelSolution { +} + +export interface WebChannelListInstance { + _version: V1; + _solution: WebChannelSolution; + _uri: string; + + (sid: string, ): WebChannelContext; + get(sid: string, ): WebChannelContext; + + + + + + + + + /** + * Create a WebChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance + */ + create(params: WebChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: WebChannelInstance) => any): Promise; + + /** + * Create a WebChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelInstance with HTTP metadata + */ + createWithHttpInfo(params: WebChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams WebChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: WebChannelInstance, done: (err?: Error) => void) => void): void; + each(params: WebChannelListInstanceEachOptions, callback?: (item: WebChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams WebChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: WebChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: WebChannelListInstanceEachOptions, callback?: (item: WebChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of WebChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: WebChannelPage) => any): Promise; + /** + * Retrieve a single target page of WebChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists WebChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: WebChannelInstance[]) => any): Promise; + list(params: WebChannelListInstanceOptions, callback?: (error: Error | null, items: WebChannelInstance[]) => any): Promise; + /** + * Lists WebChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: WebChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of WebChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: WebChannelPage) => any): Promise; + page(params: WebChannelListInstancePageOptions, callback?: (error: Error | null, items: WebChannelPage) => any): Promise; + /** + * Retrieve a single page of WebChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: WebChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WebChannelListInstance(version: V1): WebChannelListInstance { + const instance = ((sid, ) => instance.get(sid, )) as WebChannelListInstance; + + instance.get = function get(sid, ): WebChannelContext { + return new WebChannelContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/WebChannels`; + + instance.create = function create(params: WebChannelListInstanceCreateOptions, callback?: (error: Error | null, items: WebChannelInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["flexFlowSid"] === null || params["flexFlowSid"] === undefined) { + throw new Error('Required parameter "params[\'flexFlowSid\']" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + if (params["customerFriendlyName"] === null || params["customerFriendlyName"] === undefined) { + throw new Error('Required parameter "params[\'customerFriendlyName\']" missing.'); + } + + if (params["chatFriendlyName"] === null || params["chatFriendlyName"] === undefined) { + throw new Error('Required parameter "params[\'chatFriendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FlexFlowSid"] = params["flexFlowSid"]; + + data["Identity"] = params["identity"]; + + data["CustomerFriendlyName"] = params["customerFriendlyName"]; + + data["ChatFriendlyName"] = params["chatFriendlyName"]; + if (params["chatUniqueName"] !== undefined) + data["ChatUniqueName"] = params["chatUniqueName"]; + if (params["preEngagementData"] !== undefined) + data["PreEngagementData"] = params["preEngagementData"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebChannelInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: WebChannelListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["flexFlowSid"] === null || params["flexFlowSid"] === undefined) { + throw new Error('Required parameter "params[\'flexFlowSid\']" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + if (params["customerFriendlyName"] === null || params["customerFriendlyName"] === undefined) { + throw new Error('Required parameter "params[\'customerFriendlyName\']" missing.'); + } + + if (params["chatFriendlyName"] === null || params["chatFriendlyName"] === undefined) { + throw new Error('Required parameter "params[\'chatFriendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FlexFlowSid"] = params["flexFlowSid"]; + + data["Identity"] = params["identity"]; + + data["CustomerFriendlyName"] = params["customerFriendlyName"]; + + data["ChatFriendlyName"] = params["chatFriendlyName"]; + if (params["chatUniqueName"] !== undefined) + data["ChatUniqueName"] = params["chatUniqueName"]; + if (params["preEngagementData"] !== undefined) + data["PreEngagementData"] = params["preEngagementData"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebChannelInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: WebChannelListInstancePageOptions | ((error: Error | null, items: WebChannelPage) => any), callback?: (error: Error | null, items: WebChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new WebChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: WebChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new WebChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: WebChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class WebChannelPage extends Page { +/** +* Initialize the WebChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: WebChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of WebChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: WebChannelResource): WebChannelInstance { + + return new WebChannelInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/flexApi/v2/flexUser.ts b/rest/flexApi/v2/flexUser.ts new file mode 100644 index 000000000..df19d825f --- /dev/null +++ b/rest/flexApi/v2/flexUser.ts @@ -0,0 +1,507 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a FlexUserInstance + */ +export interface FlexUserContextUpdateOptions { + /** Email of the User. */ + "email"?: string; + /** The unique SID identifier of the Twilio Unified User. */ + "userSid"?: string; + /** The locale preference of the user. */ + "locale"?: string; +} + +export interface FlexUserContext { + + /** + * Fetch a FlexUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance + */ + fetch(callback?: (error: Error | null, item?: FlexUserInstance) => any): Promise + + /** + * Fetch a FlexUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a FlexUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance + */ + update(callback?: (error: Error | null, item?: FlexUserInstance) => any): Promise; + /** + * Update a FlexUserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance + */ + update(params: FlexUserContextUpdateOptions, callback?: (error: Error | null, item?: FlexUserInstance) => any): Promise; + + /** + * Update a FlexUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a FlexUserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance with HTTP metadata + */ + updateWithHttpInfo(params: FlexUserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FlexUserContextSolution { + "instanceSid": string; + "flexUserSid": string; +} + +export class FlexUserContextImpl implements FlexUserContext { + protected _solution: FlexUserContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, instanceSid: string, flexUserSid: string) { + if (!isValidPathParam(instanceSid)) { + throw new Error('Parameter \'instanceSid\' is not valid.'); + } + + if (!isValidPathParam(flexUserSid)) { + throw new Error('Parameter \'flexUserSid\' is not valid.'); + } + + this._solution = { instanceSid, flexUserSid, }; + this._uri = `/Instances/${instanceSid}/Users/${flexUserSid}`; + } + + fetch(callback?: (error: Error | null, item?: FlexUserInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FlexUserInstance(operationVersion, payload, instance._solution.instanceSid, instance._solution.flexUserSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new FlexUserInstance(operationVersion, response.body, instance._solution.instanceSid, instance._solution.flexUserSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: FlexUserContextUpdateOptions | ((error: Error | null, item?: FlexUserInstance) => any),callback?: (error: Error | null, item?: FlexUserInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["userSid"] !== undefined) + data["UserSid"] = params["userSid"]; + if (params["locale"] !== undefined) + data["Locale"] = params["locale"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FlexUserInstance(operationVersion, payload, instance._solution.instanceSid, instance._solution.flexUserSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: FlexUserContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["userSid"] !== undefined) + data["UserSid"] = params["userSid"]; + if (params["locale"] !== undefined) + data["Locale"] = params["locale"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new FlexUserInstance(operationVersion, response.body, instance._solution.instanceSid, instance._solution.flexUserSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FlexUserPayload extends FlexUserResource {} + +interface FlexUserResource { + account_sid: string; + instance_sid: string; + user_sid: string; + flex_user_sid: string; + worker_sid: string; + workspace_sid: string; + flex_team_sid: string; + username: string; + email: string; + locale: string; + roles: Array; + created_date: Date; + updated_date: Date; + version: number; + url: string; +} + +export class FlexUserInstance { + protected _solution: FlexUserContextSolution; + protected _context?: FlexUserContext; + + constructor(protected _version: V2, payload: FlexUserResource, instanceSid?: string, flexUserSid?: string) { + + this.accountSid = (payload.account_sid); + this.instanceSid = (payload.instance_sid); + this.userSid = (payload.user_sid); + this.flexUserSid = (payload.flex_user_sid); + this.workerSid = (payload.worker_sid); + this.workspaceSid = (payload.workspace_sid); + this.flexTeamSid = (payload.flex_team_sid); + this.username = (payload.username); + this.email = (payload.email); + this.locale = (payload.locale); + this.roles = (payload.roles); + this.createdDate = deserialize.iso8601DateTime(payload.created_date); + this.updatedDate = deserialize.iso8601DateTime(payload.updated_date); + this.version = deserialize.integer(payload.version); + this.url = (payload.url); + + this._solution = { instanceSid: instanceSid, flexUserSid: flexUserSid, }; + } + + /** + * The unique SID of the account that created the resource. + */ + accountSid: string; + /** + * The unique ID created by Twilio to identify a Flex instance. + */ + instanceSid: string; + /** + * The unique SID identifier of the Twilio Unified User. + */ + userSid: string; + /** + * The unique SID identifier of the Flex User. + */ + flexUserSid: string; + /** + * The unique SID identifier of the worker. + */ + workerSid: string; + /** + * The unique SID identifier of the workspace. + */ + workspaceSid: string; + /** + * The unique SID identifier of the Flex Team. + */ + flexTeamSid: string; + /** + * Username of the User. + */ + username: string; + /** + * Email of the User. + */ + email: string; + /** + * The locale preference of the user. + */ + locale: string; + /** + * The roles of the user. + */ + roles: Array; + /** + * The date that this user was created, given in ISO 8601 format. + */ + createdDate: Date; + /** + * The date that this user was updated, given in ISO 8601 format. + */ + updatedDate: Date; + /** + * The current version of the user. + */ + version: number; + url: string; + + private get _proxy(): FlexUserContext { + this._context = this._context || new FlexUserContextImpl(this._version, this._solution.instanceSid, this._solution.flexUserSid); + return this._context; + } + + /** + * Fetch a FlexUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance + */ + fetch(callback?: (error: Error | null, item?: FlexUserInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FlexUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a FlexUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance + */ + update(callback?: (error: Error | null, item?: FlexUserInstance) => any): Promise; + /** + * Update a FlexUserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance + */ + update(params: FlexUserContextUpdateOptions, callback?: (error: Error | null, item?: FlexUserInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: FlexUserInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a FlexUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a FlexUserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlexUserInstance with HTTP metadata + */ + updateWithHttpInfo(params: FlexUserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + instanceSid: this.instanceSid, + userSid: this.userSid, + flexUserSid: this.flexUserSid, + workerSid: this.workerSid, + workspaceSid: this.workspaceSid, + flexTeamSid: this.flexTeamSid, + username: this.username, + email: this.email, + locale: this.locale, + roles: this.roles, + createdDate: this.createdDate, + updatedDate: this.updatedDate, + version: this.version, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FlexUserSolution { +} + +export interface FlexUserListInstance { + _version: V2; + _solution: FlexUserSolution; + _uri: string; + + (instanceSid: string, flexUserSid: string, ): FlexUserContext; + get(instanceSid: string, flexUserSid: string, ): FlexUserContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FlexUserListInstance(version: V2): FlexUserListInstance { + const instance = ((instanceSid, flexUserSid, ) => instance.get(instanceSid, flexUserSid, )) as FlexUserListInstance; + + instance.get = function get(instanceSid, flexUserSid, ): FlexUserContext { + return new FlexUserContextImpl(version, instanceSid, flexUserSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/flexApi/v2/webChannels.ts b/rest/flexApi/v2/webChannels.ts new file mode 100644 index 000000000..0b6d642fa --- /dev/null +++ b/rest/flexApi/v2/webChannels.ts @@ -0,0 +1,230 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Flex + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a WebChannelsInstance + */ +export interface WebChannelsListInstanceCreateOptions { + /** The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. */ + "addressSid": string; + /** The Ui-Version HTTP request header */ + "uiVersion"?: string; + /** The Conversation\\\'s friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. */ + "chatFriendlyName"?: string; + /** The Conversation participant\\\'s friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. */ + "customerFriendlyName"?: string; + /** The pre-engagement data. */ + "preEngagementData"?: string; + /** The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. */ + "identity"?: string; +} + + +export interface WebChannelsSolution { +} + +export interface WebChannelsListInstance { + _version: V2; + _solution: WebChannelsSolution; + _uri: string; + + + + /** + * Create a WebChannelsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelsInstance + */ + create(params: WebChannelsListInstanceCreateOptions, callback?: (error: Error | null, item?: WebChannelsInstance) => any): Promise; + + /** + * Create a WebChannelsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebChannelsInstance with HTTP metadata + */ + createWithHttpInfo(params: WebChannelsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WebChannelsListInstance(version: V2): WebChannelsListInstance { + const instance = {} as WebChannelsListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/WebChats`; + + instance.create = function create(params: WebChannelsListInstanceCreateOptions, callback?: (error: Error | null, items: WebChannelsInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["addressSid"] === null || params["addressSid"] === undefined) { + throw new Error('Required parameter "params[\'addressSid\']" missing.'); + } + + let data: any = {}; + + + + data["AddressSid"] = params["addressSid"]; + if (params["chatFriendlyName"] !== undefined) + data["ChatFriendlyName"] = params["chatFriendlyName"]; + if (params["customerFriendlyName"] !== undefined) + data["CustomerFriendlyName"] = params["customerFriendlyName"]; + if (params["preEngagementData"] !== undefined) + data["PreEngagementData"] = params["preEngagementData"]; + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["uiVersion"] !== undefined) headers["Ui-Version"] = params["uiVersion"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebChannelsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: WebChannelsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["addressSid"] === null || params["addressSid"] === undefined) { + throw new Error('Required parameter "params[\'addressSid\']" missing.'); + } + + let data: any = {}; + + + + data["AddressSid"] = params["addressSid"]; + if (params["chatFriendlyName"] !== undefined) + data["ChatFriendlyName"] = params["chatFriendlyName"]; + if (params["customerFriendlyName"] !== undefined) + data["CustomerFriendlyName"] = params["customerFriendlyName"]; + if (params["preEngagementData"] !== undefined) + data["PreEngagementData"] = params["preEngagementData"]; + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["uiVersion"] !== undefined) headers["Ui-Version"] = params["uiVersion"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebChannelsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface WebChannelsPayload extends WebChannelsResource {} + +interface WebChannelsResource { + conversation_sid: string; + identity: string; +} + +export class WebChannelsInstance { + + constructor(protected _version: V2, payload: WebChannelsResource) { + + this.conversationSid = (payload.conversation_sid); + this.identity = (payload.identity); + + } + + /** + * The unique string representing the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) created. + */ + conversationSid: string; + /** + * The unique string representing the User created and should be authorized to participate in the Conversation. For more details, see [User Identity & Access Tokens](https://www.twilio.com/docs/conversations/identity). + */ + identity: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + conversationSid: this.conversationSid, + identity: this.identity, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/frontlineApi/V1.ts b/rest/frontlineApi/V1.ts new file mode 100644 index 000000000..de68b2956 --- /dev/null +++ b/rest/frontlineApi/V1.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Frontline + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import FrontlineApiBase from "../FrontlineApiBase"; +import Version from "../../base/Version"; +import { UserListInstance } from "./v1/user"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of FrontlineApi + * + * @param domain - The Twilio (Twilio.FrontlineApi) domain + */ + constructor(domain: FrontlineApiBase) { + super(domain, "v1"); + } + + /** users - { Twilio.FrontlineApi.V1.UserListInstance } resource */ + protected _users?: UserListInstance; + + /** Getter for users resource */ + get users(): UserListInstance { + this._users = this._users || UserListInstance(this); + return this._users; + } + +} diff --git a/rest/frontlineApi/v1/user.ts b/rest/frontlineApi/v1/user.ts new file mode 100644 index 000000000..9438da39c --- /dev/null +++ b/rest/frontlineApi/v1/user.ts @@ -0,0 +1,457 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Frontline + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Current state of this user. Can be either `active` or `deactivated` and defaults to `active` + */ +export type UserStateType = 'active'|'deactivated'; + + + +/** + * Options to pass to update a UserInstance + */ +export interface UserContextUpdateOptions { + /** The string that you assigned to describe the User. */ + "friendlyName"?: string; + /** The avatar URL which will be shown in Frontline application. */ + "avatar"?: string; + /** */ + "state"?: UserStateType; + /** Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). */ + "isAvailable"?: boolean; +} + +export interface UserContext { + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserContextSolution { + "sid": string; +} + +export class UserContextImpl implements UserContext { + protected _solution: UserContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Users/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserContextUpdateOptions | ((error: Error | null, item?: UserInstance) => any),callback?: (error: Error | null, item?: UserInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["avatar"] !== undefined) + data["Avatar"] = params["avatar"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["isAvailable"] !== undefined) + data["IsAvailable"] = serialize.bool(params["isAvailable"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["avatar"] !== undefined) + data["Avatar"] = params["avatar"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["isAvailable"] !== undefined) + data["IsAvailable"] = serialize.bool(params["isAvailable"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserPayload extends UserResource {} + +interface UserResource { + sid: string; + identity: string; + friendly_name: string; + avatar: string; + state: UserStateType; + is_available: boolean; + url: string; +} + +export class UserInstance { + protected _solution: UserContextSolution; + protected _context?: UserContext; + + constructor(protected _version: V1, payload: UserResource, sid?: string) { + + this.sid = (payload.sid); + this.identity = (payload.identity); + this.friendlyName = (payload.friendly_name); + this.avatar = (payload.avatar); + this.state = payload.state; + this.isAvailable = (payload.is_available); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the User resource. + */ + sid: string; + /** + * The application-defined string that uniquely identifies the resource\'s User. This value is often a username or an email address, and is case-sensitive. + */ + identity: string; + /** + * The string that you assigned to describe the User. + */ + friendlyName: string; + /** + * The avatar URL which will be shown in Frontline application. + */ + avatar: string; + state: UserStateType; + /** + * Whether the User is available for new conversations. Defaults to `false` for new users. + */ + isAvailable: boolean; + /** + * An absolute API resource URL for this user. + */ + url: string; + + private get _proxy(): UserContext { + this._context = this._context || new UserContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + identity: this.identity, + friendlyName: this.friendlyName, + avatar: this.avatar, + state: this.state, + isAvailable: this.isAvailable, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserSolution { +} + +export interface UserListInstance { + _version: V1; + _solution: UserSolution; + _uri: string; + + (sid: string, ): UserContext; + get(sid: string, ): UserContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserListInstance(version: V1): UserListInstance { + const instance = ((sid, ) => instance.get(sid, )) as UserListInstance; + + instance.get = function get(sid, ): UserContext { + return new UserContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/iam/V1.ts b/rest/iam/V1.ts new file mode 100644 index 000000000..18f1494f0 --- /dev/null +++ b/rest/iam/V1.ts @@ -0,0 +1,80 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Iam + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import IamBase from "../IamBase"; +import Version from "../../base/Version"; +import { ApiKeyListInstance } from "./v1/apiKey"; +import { GetApiKeysListInstance } from "./v1/getApiKeys"; +import { NewApiKeyListInstance } from "./v1/newApiKey"; +import { OAuthAppListInstance } from "./v1/oAuthApp"; +import { RolePermissionListInstance } from "./v1/rolePermission"; +import { TokenListInstance } from "./v1/token"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Iam + * + * @param domain - The Twilio (Twilio.Iam) domain + */ + constructor(domain: IamBase) { + super(domain, "v1"); + } + + /** apiKey - { Twilio.Iam.V1.ApiKeyListInstance } resource */ + protected _apiKey?: ApiKeyListInstance; + /** getApiKeys - { Twilio.Iam.V1.GetApiKeysListInstance } resource */ + protected _getApiKeys?: GetApiKeysListInstance; + /** newApiKey - { Twilio.Iam.V1.NewApiKeyListInstance } resource */ + protected _newApiKey?: NewApiKeyListInstance; + /** oAuthApps - { Twilio.Iam.V1.OAuthAppListInstance } resource */ + protected _oAuthApps?: OAuthAppListInstance; + /** token - { Twilio.Iam.V1.TokenListInstance } resource */ + protected _token?: TokenListInstance; + + /** Getter for apiKey resource */ + get apiKey(): ApiKeyListInstance { + this._apiKey = this._apiKey || ApiKeyListInstance(this); + return this._apiKey; + } + + /** Getter for getApiKeys resource */ + get getApiKeys(): GetApiKeysListInstance { + this._getApiKeys = this._getApiKeys || GetApiKeysListInstance(this); + return this._getApiKeys; + } + + /** Getter for newApiKey resource */ + get newApiKey(): NewApiKeyListInstance { + this._newApiKey = this._newApiKey || NewApiKeyListInstance(this); + return this._newApiKey; + } + + /** Getter for oAuthApps resource */ + get oAuthApps(): OAuthAppListInstance { + this._oAuthApps = this._oAuthApps || OAuthAppListInstance(this); + return this._oAuthApps; + } + + /** Accessor for rolePermission resource */ + rolePermission(RoleSid: string): RolePermissionListInstance { + return RolePermissionListInstance(this, RoleSid); + } + + /** Getter for token resource */ + get token(): TokenListInstance { + this._token = this._token || TokenListInstance(this); + return this._token; + } + +} diff --git a/rest/iam/v1/apiKey.ts b/rest/iam/v1/apiKey.ts new file mode 100644 index 000000000..1e432a84e --- /dev/null +++ b/rest/iam/v1/apiKey.ts @@ -0,0 +1,507 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Iam + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a ApiKeyInstance + */ +export interface ApiKeyContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). */ + "policy"?: any; +} + +export interface ApiKeyContext { + + /** + * Remove a ApiKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ApiKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ApiKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance + */ + fetch(callback?: (error: Error | null, item?: ApiKeyInstance) => any): Promise + + /** + * Fetch a ApiKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ApiKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance + */ + update(callback?: (error: Error | null, item?: ApiKeyInstance) => any): Promise; + /** + * Update a ApiKeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance + */ + update(params: ApiKeyContextUpdateOptions, callback?: (error: Error | null, item?: ApiKeyInstance) => any): Promise; + + /** + * Update a ApiKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ApiKeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance with HTTP metadata + */ + updateWithHttpInfo(params: ApiKeyContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ApiKeyContextSolution { + "sid": string; +} + +export class ApiKeyContextImpl implements ApiKeyContext { + protected _solution: ApiKeyContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Keys/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ApiKeyInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ApiKeyInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ApiKeyInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ApiKeyContextUpdateOptions | ((error: Error | null, item?: ApiKeyInstance) => any),callback?: (error: Error | null, item?: ApiKeyInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["policy"] !== undefined) + data["Policy"] = serialize.object(params["policy"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ApiKeyInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ApiKeyContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["policy"] !== undefined) + data["Policy"] = serialize.object(params["policy"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ApiKeyInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ApiKeyPayload extends ApiKeyResource {} + +interface ApiKeyResource { + sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + policy: Record; +} + +export class ApiKeyInstance { + protected _solution: ApiKeyContextSolution; + protected _context?: ApiKeyContext; + + constructor(protected _version: V1, payload: ApiKeyResource, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.policy = (payload.policy); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Key resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The \\`Policy\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + */ + policy: Record; + + private get _proxy(): ApiKeyContext { + this._context = this._context || new ApiKeyContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ApiKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ApiKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ApiKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance + */ + fetch(callback?: (error: Error | null, item?: ApiKeyInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ApiKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ApiKeyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance + */ + update(callback?: (error: Error | null, item?: ApiKeyInstance) => any): Promise; + /** + * Update a ApiKeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance + */ + update(params: ApiKeyContextUpdateOptions, callback?: (error: Error | null, item?: ApiKeyInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ApiKeyInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ApiKeyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ApiKeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApiKeyInstance with HTTP metadata + */ + updateWithHttpInfo(params: ApiKeyContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + policy: this.policy, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ApiKeySolution { +} + +export interface ApiKeyListInstance { + _version: V1; + _solution: ApiKeySolution; + _uri: string; + + (sid: string, ): ApiKeyContext; + get(sid: string, ): ApiKeyContext; + + + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ApiKeyListInstance(version: V1): ApiKeyListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ApiKeyListInstance; + + instance.get = function get(sid, ): ApiKeyContext { + return new ApiKeyContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/iam/v1/getApiKeys.ts b/rest/iam/v1/getApiKeys.ts new file mode 100644 index 000000000..84645796c --- /dev/null +++ b/rest/iam/v1/getApiKeys.ts @@ -0,0 +1,415 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Iam + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface GetApiKeysListInstanceEachOptions { + /** The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. */ + "accountSid": string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: GetApiKeysInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface GetApiKeysListInstanceOptions { + /** The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. */ + "accountSid": string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface GetApiKeysListInstancePageOptions { + /** The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. */ + "accountSid": string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface GetApiKeysSolution { +} + +export interface GetApiKeysListInstance { + _version: V1; + _solution: GetApiKeysSolution; + _uri: string; + + + + + /** + * Streams GetApiKeysInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { GetApiKeysListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + + each(params: GetApiKeysListInstanceEachOptions, callback?: (item: GetApiKeysInstance, done: (err?: Error) => void) => void): void; + /** + * Streams GetApiKeysInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { GetApiKeysListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + + eachWithHttpInfo(params: GetApiKeysListInstanceEachOptions, callback?: (item: GetApiKeysInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of GetApiKeysInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: GetApiKeysPage) => any): Promise; + /** + * Retrieve a single target page of GetApiKeysInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists GetApiKeysInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { GetApiKeysListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + + list(params: GetApiKeysListInstanceOptions, callback?: (error: Error | null, items: GetApiKeysInstance[]) => any): Promise; + /** + * Lists GetApiKeysInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { GetApiKeysListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + + listWithHttpInfo(params: GetApiKeysListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of GetApiKeysInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { GetApiKeysListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + + page(params: GetApiKeysListInstancePageOptions, callback?: (error: Error | null, items: GetApiKeysPage) => any): Promise; + /** + * Retrieve a single page of GetApiKeysInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { GetApiKeysListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + + pageWithHttpInfo(params: GetApiKeysListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function GetApiKeysListInstance(version: V1): GetApiKeysListInstance { + const instance = {} as GetApiKeysListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Keys`; + + instance.page = function page(params: GetApiKeysListInstancePageOptions, callback?: (error: Error | null, items: GetApiKeysPage) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["accountSid"] === null || params["accountSid"] === undefined) { + throw new Error('Required parameter "params[\'accountSid\']" missing.'); + } + + let data: any = {}; + + + data["AccountSid"] = params["accountSid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new GetApiKeysPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: GetApiKeysPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new GetApiKeysPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params: GetApiKeysListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["accountSid"] === null || params["accountSid"] === undefined) { + throw new Error('Required parameter "params[\'accountSid\']" missing.'); + } + + let data: any = {}; + + + data["AccountSid"] = params["accountSid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new GetApiKeysPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new GetApiKeysPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface GetApiKeysPayload extends TwilioResponsePayload { + keys: GetApiKeysResource[]; +} + +interface GetApiKeysResource { + sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + flags: Array; +} + +export class GetApiKeysInstance { + + constructor(protected _version: V1, payload: GetApiKeysResource) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.flags = (payload.flags); + + } + + /** + * The unique string that we created to identify the Key resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + flags: Array; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + flags: this.flags, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class GetApiKeysPage extends Page { +/** +* Initialize the GetApiKeysPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: GetApiKeysSolution) { + super(version, response, solution); + } + + /** + * Build an instance of GetApiKeysInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: GetApiKeysResource): GetApiKeysInstance { + + return new GetApiKeysInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/iam/v1/newApiKey.ts b/rest/iam/v1/newApiKey.ts new file mode 100644 index 000000000..30853c943 --- /dev/null +++ b/rest/iam/v1/newApiKey.ts @@ -0,0 +1,248 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Iam + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a NewApiKeyInstance + */ +export interface NewApiKeyListInstanceCreateOptions { + /** The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. */ + "accountSid": string; + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The \\\\`KeyType\\\\` form parameter is used to specify the type of key you want to create. **Default Behavior**: If \\\\`KeyType\\\\` is not specified, the API will generate a standard key. **Restricted Key**: If \\\\`KeyType\\\\` is set to \\\\`restricted\\\\`, the API will create a new restricted key. In this case, a policy object is required to define the permissions. */ + "keyType"?: string; + /** The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). */ + "policy"?: any; +} + + +export interface NewApiKeySolution { +} + +export interface NewApiKeyListInstance { + _version: V1; + _solution: NewApiKeySolution; + _uri: string; + + + + /** + * Create a NewApiKeyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewApiKeyInstance + */ + create(params: NewApiKeyListInstanceCreateOptions, callback?: (error: Error | null, item?: NewApiKeyInstance) => any): Promise; + + /** + * Create a NewApiKeyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewApiKeyInstance with HTTP metadata + */ + createWithHttpInfo(params: NewApiKeyListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NewApiKeyListInstance(version: V1): NewApiKeyListInstance { + const instance = {} as NewApiKeyListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Keys`; + + instance.create = function create(params: NewApiKeyListInstanceCreateOptions, callback?: (error: Error | null, items: NewApiKeyInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["accountSid"] === null || params["accountSid"] === undefined) { + throw new Error('Required parameter "params[\'accountSid\']" missing.'); + } + + let data: any = {}; + + + + data["AccountSid"] = params["accountSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["keyType"] !== undefined) + data["KeyType"] = params["keyType"]; + if (params["policy"] !== undefined) + data["Policy"] = serialize.object(params["policy"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NewApiKeyInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: NewApiKeyListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["accountSid"] === null || params["accountSid"] === undefined) { + throw new Error('Required parameter "params[\'accountSid\']" missing.'); + } + + let data: any = {}; + + + + data["AccountSid"] = params["accountSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["keyType"] !== undefined) + data["KeyType"] = params["keyType"]; + if (params["policy"] !== undefined) + data["Policy"] = serialize.object(params["policy"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new NewApiKeyInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface NewApiKeyPayload extends NewApiKeyResource {} + +interface NewApiKeyResource { + sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + secret: string; + policy: Record; +} + +export class NewApiKeyInstance { + + constructor(protected _version: V1, payload: NewApiKeyResource) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.rfc2822DateTime(payload.date_created); + this.dateUpdated = deserialize.rfc2822DateTime(payload.date_updated); + this.secret = (payload.secret); + this.policy = (payload.policy); + + } + + /** + * The unique string that that we created to identify the NewKey resource. You will use this as the basic-auth `user` when authenticating to the API. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT that the API Key was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the new API Key was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + */ + secret: string; + /** + * Collection of allow assertions. + */ + policy: Record; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + secret: this.secret, + policy: this.policy, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/iam/v1/oAuthApp.ts b/rest/iam/v1/oAuthApp.ts new file mode 100644 index 000000000..0a75feb3e --- /dev/null +++ b/rest/iam/v1/oAuthApp.ts @@ -0,0 +1,588 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Iam + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class IamV1AccountVendorOauthAppCreateRequest { + "type"?: string; + "friendlyName"?: string; + "ownerSid"?: string | null; + "description"?: string; + "clientSid"?: string | null; + /** + * Determines how the client authenticates. Account OAuth apps on v1 only support \'client_secret_basic\'. For PKCE (none), use the v2 API. + */ + "tokenEndpointAuthMethod"?: string; + "policy"?: IamV1OrganizationVendoroauthappPolicy; + "accessTokenTtl"?: number; + + constructor(payload) { + this.type = payload["type"]; + this.friendlyName = payload["friendly_name"]; + this.ownerSid = payload["owner_sid"]; + this.description = payload["description"]; + this.clientSid = payload["client_sid"]; + this.tokenEndpointAuthMethod = payload["token_endpoint_auth_method"]; + this.policy = payload["policy"]; + this.accessTokenTtl = payload["access_token_ttl"]; + } +} + + +export class IamV1AccountVendorOauthAppUpdateRequest { + "type"?: string | null; + "friendlyName"?: string | null; + "description"?: string | null; + "policy"?: IamV1OrganizationVendorOauthAppUpdateRequestPolicy | null; + "accessTokenTtl"?: number | null; + + constructor(payload) { + this.type = payload["type"]; + this.friendlyName = payload["friendly_name"]; + this.description = payload["description"]; + this.policy = payload["policy"]; + this.accessTokenTtl = payload["access_token_ttl"]; + } +} + + +export class IamV1OrganizationVendorOauthAppUpdateRequestPolicy { + /** + * Set of permissions explicitly allowed + */ + "allow"?: Array; + /** + * Set of permissions explicitly denied + */ + "deny"?: Array; + + constructor(payload) { + this.allow = payload["allow"]; + this.deny = payload["deny"]; + } +} + + +export class IamV1OrganizationVendoroauthappPolicy { + /** + * Set of permissions explicitly allowed + */ + "allow"?: Array; + /** + * Set of permissions explicitly denied + */ + "deny"?: Array; + + constructor(payload) { + this.allow = payload["allow"]; + this.deny = payload["deny"]; + } +} + + + + +/** + * Options to pass to update a OAuthAppInstance + */ +export interface OAuthAppContextUpdateOptions { + /** */ + "iamV1AccountVendorOauthAppUpdateRequest": IamV1AccountVendorOauthAppUpdateRequest; +} + +/** + * Options to pass to create a OAuthAppInstance + */ +export interface OAuthAppListInstanceCreateOptions { + /** */ + "iamV1AccountVendorOauthAppCreateRequest": IamV1AccountVendorOauthAppCreateRequest; +} + +export interface OAuthAppContext { + + /** + * Remove a OAuthAppInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a OAuthAppInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a OAuthAppInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OAuthAppInstance + */ + update(params: IamV1AccountVendorOauthAppUpdateRequest, headers?: any, callback?: (error: Error | null, item?: OAuthAppInstance) => any): Promise; + + /** + * Update a OAuthAppInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OAuthAppInstance with HTTP metadata + */ + updateWithHttpInfo(params: IamV1AccountVendorOauthAppUpdateRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OAuthAppContextSolution { + "sid": string; +} + +export class OAuthAppContextImpl implements OAuthAppContext { + protected _solution: OAuthAppContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Account/OAuthApps/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: IamV1AccountVendorOauthAppUpdateRequest, headers?: any,callback?: (error: Error | null, item?: OAuthAppInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new OAuthAppInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: IamV1AccountVendorOauthAppUpdateRequest, headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new OAuthAppInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface OAuthAppPayload extends OAuthAppResource {} + +interface OAuthAppResource { + type: string; + sid: string; + friendly_name: string; + description: string; + date_created: Date; + created_by: string; + creator_sid: string; + secret: string; + status: string; + policy: IamV1OrganizationVendoroauthappPolicy; + access_token_ttl: number; + code: number; + message: string; + more_info: string; +} + +export class OAuthAppInstance { + protected _solution: OAuthAppContextSolution; + protected _context?: OAuthAppContext; + + constructor(protected _version: V1, payload: OAuthAppResource, sid?: string) { + + this.type = (payload.type); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.createdBy = (payload.created_by); + this.creatorSid = (payload.creator_sid); + this.secret = (payload.secret); + this.status = (payload.status); + this.policy = payload.policy !== null && payload.policy !== undefined ? new IamV1OrganizationVendoroauthappPolicy(payload.policy) : null; + this.accessTokenTtl = deserialize.integer(payload.access_token_ttl); + this.code = (payload.code); + this.message = (payload.message); + this.moreInfo = (payload.more_info); + + this._solution = { sid: sid, }; + } + + type: string; + sid: string; + friendlyName: string; + description: string; + dateCreated: Date; + createdBy: string; + /** + * The unique identifier (SID) of the user who created this OAuth app. + */ + creatorSid: string; + secret: string; + status: string; + policy: IamV1OrganizationVendoroauthappPolicy; + accessTokenTtl: number; + /** + * Twilio-specific error code + */ + code: number; + /** + * Error message + */ + message: string; + /** + * Link to Error Code References + */ + moreInfo: string; + + private get _proxy(): OAuthAppContext { + this._context = this._context || new OAuthAppContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a OAuthAppInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a OAuthAppInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Update a OAuthAppInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OAuthAppInstance + */ + update(params: IamV1AccountVendorOauthAppUpdateRequest, headers?: any, callback?: (error: Error | null, item?: OAuthAppInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: OAuthAppInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a OAuthAppInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OAuthAppInstance with HTTP metadata + */ + updateWithHttpInfo(params: IamV1AccountVendorOauthAppUpdateRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + type: this.type, + sid: this.sid, + friendlyName: this.friendlyName, + description: this.description, + dateCreated: this.dateCreated, + createdBy: this.createdBy, + creatorSid: this.creatorSid, + secret: this.secret, + status: this.status, + policy: this.policy, + accessTokenTtl: this.accessTokenTtl, + code: this.code, + message: this.message, + moreInfo: this.moreInfo, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OAuthAppSolution { +} + +export interface OAuthAppListInstance { + _version: V1; + _solution: OAuthAppSolution; + _uri: string; + + (sid: string, ): OAuthAppContext; + get(sid: string, ): OAuthAppContext; + + + + + + + /** + * Create a OAuthAppInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OAuthAppInstance + */ + create(params: IamV1AccountVendorOauthAppCreateRequest, headers?: any, callback?: (error: Error | null, item?: OAuthAppInstance) => any): Promise; + + /** + * Create a OAuthAppInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OAuthAppInstance with HTTP metadata + */ + createWithHttpInfo(params: IamV1AccountVendorOauthAppCreateRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OAuthAppListInstance(version: V1): OAuthAppListInstance { + const instance = ((sid, ) => instance.get(sid, )) as OAuthAppListInstance; + + instance.get = function get(sid, ): OAuthAppContext { + return new OAuthAppContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Account/OAuthApps`; + + instance.create = function create(params: IamV1AccountVendorOauthAppCreateRequest, headers?: any, callback?: (error: Error | null, items: OAuthAppInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new OAuthAppInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: IamV1AccountVendorOauthAppCreateRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new OAuthAppInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/iam/v1/rolePermission.ts b/rest/iam/v1/rolePermission.ts new file mode 100644 index 000000000..e7c501c58 --- /dev/null +++ b/rest/iam/v1/rolePermission.ts @@ -0,0 +1,419 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Iam + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface RolePermissionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RolePermissionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RolePermissionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RolePermissionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface RolePermissionSolution { + roleSid: string; +} + +export interface RolePermissionListInstance { + _version: V1; + _solution: RolePermissionSolution; + _uri: string; + + + + + /** + * Streams RolePermissionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RolePermissionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RolePermissionInstance, done: (err?: Error) => void) => void): void; + each(params: RolePermissionListInstanceEachOptions, callback?: (item: RolePermissionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RolePermissionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RolePermissionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RolePermissionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RolePermissionListInstanceEachOptions, callback?: (item: RolePermissionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RolePermissionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RolePermissionPage) => any): Promise; + /** + * Retrieve a single target page of RolePermissionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RolePermissionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RolePermissionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RolePermissionInstance[]) => any): Promise; + list(params: RolePermissionListInstanceOptions, callback?: (error: Error | null, items: RolePermissionInstance[]) => any): Promise; + /** + * Lists RolePermissionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RolePermissionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RolePermissionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RolePermissionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RolePermissionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RolePermissionPage) => any): Promise; + page(params: RolePermissionListInstancePageOptions, callback?: (error: Error | null, items: RolePermissionPage) => any): Promise; + /** + * Retrieve a single page of RolePermissionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RolePermissionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RolePermissionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RolePermissionListInstance(version: V1, roleSid: string): RolePermissionListInstance { + if (!isValidPathParam(roleSid)) { + throw new Error('Parameter \'roleSid\' is not valid.'); + } + + const instance = {} as RolePermissionListInstance; + + instance._version = version; + instance._solution = { roleSid, }; + instance._uri = `/Roles/${roleSid}/Permissions`; + + instance.page = function page(params?: RolePermissionListInstancePageOptions | ((error: Error | null, items: RolePermissionPage) => any), callback?: (error: Error | null, items: RolePermissionPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RolePermissionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RolePermissionPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RolePermissionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RolePermissionListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePermissionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePermissionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface RolePermissionPayload extends TwilioResponsePayload { + permissions: RolePermissionResource[]; +} + +interface RolePermissionResource { + sid: string; + namespace: string; + product: string; + resource: string; + action: string; + externalDescription: string; +} + +export class RolePermissionInstance { + + constructor(protected _version: V1, payload: RolePermissionResource, roleSid?: string) { + + this.sid = (payload.sid); + this.namespace = (payload.namespace); + this.product = (payload.product); + this.resource = (payload.resource); + this.action = (payload.action); + this.externalDescription = (payload.externalDescription); + + } + + /** + * The unique string that identifies the Permission resource. + */ + sid: string; + /** + * The namespace of the permission (e.g., twilio). + */ + namespace: string; + /** + * The product the permission belongs to (e.g., iam). + */ + product: string; + /** + * The resource the permission applies to (e.g., roles). + */ + resource: string; + /** + * The action granted by the permission (e.g., read). + */ + action: string; + /** + * The external description of the permission. + */ + externalDescription: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + namespace: this.namespace, + product: this.product, + resource: this.resource, + action: this.action, + externalDescription: this.externalDescription, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class RolePermissionPage extends Page { +/** +* Initialize the RolePermissionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: RolePermissionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RolePermissionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RolePermissionResource): RolePermissionInstance { + + return new RolePermissionInstance( + this._version, + payload, + this._solution.roleSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/iam/v1/token.ts b/rest/iam/v1/token.ts new file mode 100644 index 000000000..bdc4e8404 --- /dev/null +++ b/rest/iam/v1/token.ts @@ -0,0 +1,270 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Iam + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a TokenInstance + */ +export interface TokenListInstanceCreateOptions { + /** Grant type is a credential representing resource owner\\\'s authorization which can be used by client to obtain access token. */ + "grantType": string; + /** A 34 character string that uniquely identifies this OAuth App. */ + "clientId": string; + /** The credential for confidential OAuth App. */ + "clientSecret"?: string; + /** JWT token related to the authorization code grant type. */ + "code"?: string; + /** The redirect uri */ + "redirectUri"?: string; + /** The targeted audience uri */ + "audience"?: string; + /** JWT token related to refresh access token. */ + "refreshToken"?: string; + /** The scope of token */ + "scope"?: string; +} + + +export interface TokenSolution { +} + +export interface TokenListInstance { + _version: V1; + _solution: TokenSolution; + _uri: string; + + + + /** + * Create a TokenInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance + */ + create(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, item?: TokenInstance) => any): Promise; + + /** + * Create a TokenInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance with HTTP metadata + */ + createWithHttpInfo(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TokenListInstance(version: V1): TokenListInstance { + const instance = {} as TokenListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/token`; + + instance.create = function create(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, items: TokenInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["grantType"] === null || params["grantType"] === undefined) { + throw new Error('Required parameter "params[\'grantType\']" missing.'); + } + + if (params["clientId"] === null || params["clientId"] === undefined) { + throw new Error('Required parameter "params[\'clientId\']" missing.'); + } + + let data: any = {}; + + + + data["grant_type"] = params["grantType"]; + + data["client_id"] = params["clientId"]; + if (params["clientSecret"] !== undefined) + data["client_secret"] = params["clientSecret"]; + if (params["code"] !== undefined) + data["code"] = params["code"]; + if (params["redirectUri"] !== undefined) + data["redirect_uri"] = params["redirectUri"]; + if (params["audience"] !== undefined) + data["audience"] = params["audience"]; + if (params["refreshToken"] !== undefined) + data["refresh_token"] = params["refreshToken"]; + if (params["scope"] !== undefined) + data["scope"] = params["scope"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TokenInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["grantType"] === null || params["grantType"] === undefined) { + throw new Error('Required parameter "params[\'grantType\']" missing.'); + } + + if (params["clientId"] === null || params["clientId"] === undefined) { + throw new Error('Required parameter "params[\'clientId\']" missing.'); + } + + let data: any = {}; + + + + data["grant_type"] = params["grantType"]; + + data["client_id"] = params["clientId"]; + if (params["clientSecret"] !== undefined) + data["client_secret"] = params["clientSecret"]; + if (params["code"] !== undefined) + data["code"] = params["code"]; + if (params["redirectUri"] !== undefined) + data["redirect_uri"] = params["redirectUri"]; + if (params["audience"] !== undefined) + data["audience"] = params["audience"]; + if (params["refreshToken"] !== undefined) + data["refresh_token"] = params["refreshToken"]; + if (params["scope"] !== undefined) + data["scope"] = params["scope"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new TokenInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TokenPayload extends TokenResource {} + +interface TokenResource { + access_token: string; + refresh_token: string; + id_token: string; + token_type: string; + expires_in: number; +} + +export class TokenInstance { + + constructor(protected _version: V1, payload: TokenResource) { + + this.accessToken = (payload.access_token); + this.refreshToken = (payload.refresh_token); + this.idToken = (payload.id_token); + this.tokenType = (payload.token_type); + this.expiresIn = (payload.expires_in); + + } + + /** + * Token which carries the necessary information to access a Twilio resource directly. + */ + accessToken: string; + /** + * Token which carries the information necessary to get a new access token. + */ + refreshToken: string; + /** + * Token which carries the information necessary of user profile. + */ + idToken: string; + /** + * Token type + */ + tokenType: string; + expiresIn: number; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accessToken: this.accessToken, + refreshToken: this.refreshToken, + idToken: this.idToken, + tokenType: this.tokenType, + expiresIn: this.expiresIn, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/insights/V1.ts b/rest/insights/V1.ts new file mode 100644 index 000000000..710429441 --- /dev/null +++ b/rest/insights/V1.ts @@ -0,0 +1,74 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import InsightsBase from "../InsightsBase"; +import Version from "../../base/Version"; +import { CallListInstance } from "./v1/call"; +import { CallSummariesListInstance } from "./v1/callSummaries"; +import { ConferenceListInstance } from "./v1/conference"; +import { RoomListInstance } from "./v1/room"; +import { SettingListInstance } from "./v1/setting"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Insights + * + * @param domain - The Twilio (Twilio.Insights) domain + */ + constructor(domain: InsightsBase) { + super(domain, "v1"); + } + + /** calls - { Twilio.Insights.V1.CallListInstance } resource */ + protected _calls?: CallListInstance; + /** callSummaries - { Twilio.Insights.V1.CallSummariesListInstance } resource */ + protected _callSummaries?: CallSummariesListInstance; + /** conferences - { Twilio.Insights.V1.ConferenceListInstance } resource */ + protected _conferences?: ConferenceListInstance; + /** rooms - { Twilio.Insights.V1.RoomListInstance } resource */ + protected _rooms?: RoomListInstance; + /** settings - { Twilio.Insights.V1.SettingListInstance } resource */ + protected _settings?: SettingListInstance; + + /** Getter for calls resource */ + get calls(): CallListInstance { + this._calls = this._calls || CallListInstance(this); + return this._calls; + } + + /** Getter for callSummaries resource */ + get callSummaries(): CallSummariesListInstance { + this._callSummaries = this._callSummaries || CallSummariesListInstance(this); + return this._callSummaries; + } + + /** Getter for conferences resource */ + get conferences(): ConferenceListInstance { + this._conferences = this._conferences || ConferenceListInstance(this); + return this._conferences; + } + + /** Getter for rooms resource */ + get rooms(): RoomListInstance { + this._rooms = this._rooms || RoomListInstance(this); + return this._rooms; + } + + /** Getter for settings resource */ + get settings(): SettingListInstance { + this._settings = this._settings || SettingListInstance(this); + return this._settings; + } + +} diff --git a/rest/insights/V2.ts b/rest/insights/V2.ts new file mode 100644 index 000000000..e6f92cf25 --- /dev/null +++ b/rest/insights/V2.ts @@ -0,0 +1,50 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Sample/reference Twilio API. + * This is the reference API for the rest-proxy server. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import InsightsBase from "../InsightsBase"; +import Version from "../../base/Version"; +import { InboundListInstance } from "./v2/inbound"; +import { OutboundListInstance } from "./v2/outbound"; +import { ReportListInstance } from "./v2/report"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Insights + * + * @param domain - The Twilio (Twilio.Insights) domain + */ + constructor(domain: InsightsBase) { + super(domain, "v2"); + } + + /** reports - { Twilio.Insights.V2.ReportListInstance } resource */ + protected _reports?: ReportListInstance; + + /** Accessor for inbound resource */ + inbound(reportId: string): InboundListInstance { + return InboundListInstance(this, reportId); + } + + /** Accessor for outbound resource */ + outbound(reportId: string): OutboundListInstance { + return OutboundListInstance(this, reportId); + } + + /** Getter for reports resource */ + get reports(): ReportListInstance { + this._reports = this._reports || ReportListInstance(this); + return this._reports; + } + +} diff --git a/rest/insights/V3.ts b/rest/insights/V3.ts new file mode 100644 index 000000000..3b722655a --- /dev/null +++ b/rest/insights/V3.ts @@ -0,0 +1,56 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * Insights Domain V3 API. Includes synchronous Query, Metadata, and Async Query (long-running operation) endpoints. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import InsightsBase from "../InsightsBase"; +import Version from "../../base/Version"; +import { MetadataListInstance } from "./v3/metadata"; +import { QueryListInstance } from "./v3/query"; +import { QueryJobListInstance } from "./v3/queryJob"; + +export default class V3 extends Version { + /** + * Initialize the V3 version of Insights + * + * @param domain - The Twilio (Twilio.Insights) domain + */ + constructor(domain: InsightsBase) { + super(domain, "v3"); + } + + /** metadata - { Twilio.Insights.V3.MetadataListInstance } resource */ + protected _metadata?: MetadataListInstance; + /** query - { Twilio.Insights.V3.QueryListInstance } resource */ + protected _query?: QueryListInstance; + /** queryJobs - { Twilio.Insights.V3.QueryJobListInstance } resource */ + protected _queryJobs?: QueryJobListInstance; + + /** Getter for metadata resource */ + get metadata(): MetadataListInstance { + this._metadata = this._metadata || MetadataListInstance(this); + return this._metadata; + } + + /** Getter for query resource */ + get query(): QueryListInstance { + this._query = this._query || QueryListInstance(this); + return this._query; + } + + /** Getter for queryJobs resource */ + get queryJobs(): QueryJobListInstance { + this._queryJobs = this._queryJobs || QueryJobListInstance(this); + return this._queryJobs; + } + +} diff --git a/rest/insights/v1/call.ts b/rest/insights/v1/call.ts new file mode 100644 index 000000000..a1c6a7767 --- /dev/null +++ b/rest/insights/v1/call.ts @@ -0,0 +1,299 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { AnnotationListInstance } from "./call/annotation"; +import { CallSummaryListInstance } from "./call/callSummary"; +import { EventListInstance } from "./call/event"; +import { MetricListInstance } from "./call/metric"; + + + + +export interface CallContext { + annotation: AnnotationListInstance; + summary: CallSummaryListInstance; + events: EventListInstance; + metrics: MetricListInstance; + + /** + * Fetch a CallInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance + */ + fetch(callback?: (error: Error | null, item?: CallInstance) => any): Promise + + /** + * Fetch a CallInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CallContextSolution { + "sid": string; +} + +export class CallContextImpl implements CallContext { + protected _solution: CallContextSolution; + protected _uri: string; + + protected _annotation?: AnnotationListInstance; + protected _summary?: CallSummaryListInstance; + protected _events?: EventListInstance; + protected _metrics?: MetricListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Voice/${sid}`; + } + + get annotation(): AnnotationListInstance { + this._annotation = this._annotation || AnnotationListInstance(this._version, this._solution.sid); + return this._annotation; + } + + get summary(): CallSummaryListInstance { + this._summary = this._summary || CallSummaryListInstance(this._version, this._solution.sid); + return this._summary; + } + + get events(): EventListInstance { + this._events = this._events || EventListInstance(this._version, this._solution.sid); + return this._events; + } + + get metrics(): MetricListInstance { + this._metrics = this._metrics || MetricListInstance(this._version, this._solution.sid); + return this._metrics; + } + + fetch(callback?: (error: Error | null, item?: CallInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CallInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CallInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CallPayload extends CallResource {} + +interface CallResource { + sid: string; + url: string; + links: Record; +} + +export class CallInstance { + protected _solution: CallContextSolution; + protected _context?: CallContext; + + constructor(protected _version: V1, payload: CallResource, sid?: string) { + + this.sid = (payload.sid); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + sid: string; + url: string; + links: Record; + + private get _proxy(): CallContext { + this._context = this._context || new CallContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a CallInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance + */ + fetch(callback?: (error: Error | null, item?: CallInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CallInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the annotation. + */ + annotation(): AnnotationListInstance { + return this._proxy.annotation; + } + + /** + * Access the summary. + */ + summary(): CallSummaryListInstance { + return this._proxy.summary; + } + + /** + * Access the events. + */ + events(): EventListInstance { + return this._proxy.events; + } + + /** + * Access the metrics. + */ + metrics(): MetricListInstance { + return this._proxy.metrics; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CallSolution { +} + +export interface CallListInstance { + _version: V1; + _solution: CallSolution; + _uri: string; + + (sid: string, ): CallContext; + get(sid: string, ): CallContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CallListInstance(version: V1): CallListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CallListInstance; + + instance.get = function get(sid, ): CallContext { + return new CallContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/insights/v1/call/annotation.ts b/rest/insights/v1/call/annotation.ts new file mode 100644 index 000000000..a29bd3659 --- /dev/null +++ b/rest/insights/v1/call/annotation.ts @@ -0,0 +1,494 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export type AnnotationAnsweredBy = 'unknown_answered_by'|'human'|'machine'; + +export type AnnotationConnectivityIssue = 'unknown_connectivity_issue'|'no_connectivity_issue'|'invalid_number'|'caller_id'|'dropped_call'|'number_reachability'; + + + +/** + * Options to pass to update a AnnotationInstance + */ +export interface AnnotationContextUpdateOptions { + /** */ + "answeredBy"?: AnnotationAnsweredBy; + /** */ + "connectivityIssue"?: AnnotationConnectivityIssue; + /** Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. */ + "qualityIssues"?: string; + /** A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. */ + "spam"?: boolean; + /** Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. */ + "callScore"?: number; + /** Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. */ + "comment"?: string; + /** Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. */ + "incident"?: string; +} + +export interface AnnotationContext { + + /** + * Fetch a AnnotationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance + */ + fetch(callback?: (error: Error | null, item?: AnnotationInstance) => any): Promise + + /** + * Fetch a AnnotationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a AnnotationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance + */ + update(callback?: (error: Error | null, item?: AnnotationInstance) => any): Promise; + /** + * Update a AnnotationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance + */ + update(params: AnnotationContextUpdateOptions, callback?: (error: Error | null, item?: AnnotationInstance) => any): Promise; + + /** + * Update a AnnotationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AnnotationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance with HTTP metadata + */ + updateWithHttpInfo(params: AnnotationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AnnotationContextSolution { + "callSid": string; +} + +export class AnnotationContextImpl implements AnnotationContext { + protected _solution: AnnotationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, callSid: string) { + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + this._solution = { callSid, }; + this._uri = `/Voice/${callSid}/Annotation`; + } + + fetch(callback?: (error: Error | null, item?: AnnotationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AnnotationInstance(operationVersion, payload, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new AnnotationInstance(operationVersion, response.body, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: AnnotationContextUpdateOptions | ((error: Error | null, item?: AnnotationInstance) => any),callback?: (error: Error | null, item?: AnnotationInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["answeredBy"] !== undefined) + data["AnsweredBy"] = params["answeredBy"]; + if (params["connectivityIssue"] !== undefined) + data["ConnectivityIssue"] = params["connectivityIssue"]; + if (params["qualityIssues"] !== undefined) + data["QualityIssues"] = params["qualityIssues"]; + if (params["spam"] !== undefined) + data["Spam"] = serialize.bool(params["spam"]); + if (params["callScore"] !== undefined) + data["CallScore"] = params["callScore"]; + if (params["comment"] !== undefined) + data["Comment"] = params["comment"]; + if (params["incident"] !== undefined) + data["Incident"] = params["incident"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AnnotationInstance(operationVersion, payload, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: AnnotationContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["answeredBy"] !== undefined) + data["AnsweredBy"] = params["answeredBy"]; + if (params["connectivityIssue"] !== undefined) + data["ConnectivityIssue"] = params["connectivityIssue"]; + if (params["qualityIssues"] !== undefined) + data["QualityIssues"] = params["qualityIssues"]; + if (params["spam"] !== undefined) + data["Spam"] = serialize.bool(params["spam"]); + if (params["callScore"] !== undefined) + data["CallScore"] = params["callScore"]; + if (params["comment"] !== undefined) + data["Comment"] = params["comment"]; + if (params["incident"] !== undefined) + data["Incident"] = params["incident"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new AnnotationInstance(operationVersion, response.body, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AnnotationPayload extends AnnotationResource {} + +interface AnnotationResource { + call_sid: string; + account_sid: string; + answered_by: AnnotationAnsweredBy; + connectivity_issue: AnnotationConnectivityIssue; + quality_issues: Array; + spam: boolean; + call_score: number; + comment: string; + incident: string; + url: string; +} + +export class AnnotationInstance { + protected _solution: AnnotationContextSolution; + protected _context?: AnnotationContext; + + constructor(protected _version: V1, payload: AnnotationResource, callSid: string) { + + this.callSid = (payload.call_sid); + this.accountSid = (payload.account_sid); + this.answeredBy = payload.answered_by; + this.connectivityIssue = payload.connectivity_issue; + this.qualityIssues = (payload.quality_issues); + this.spam = (payload.spam); + this.callScore = deserialize.integer(payload.call_score); + this.comment = (payload.comment); + this.incident = (payload.incident); + this.url = (payload.url); + + this._solution = { callSid, }; + } + + /** + * The unique SID identifier of the Call. + */ + callSid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + answeredBy: AnnotationAnsweredBy; + connectivityIssue: AnnotationConnectivityIssue; + /** + * Specifies if the call had any subjective quality issues. Possible values are one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, or `static_noise`. + */ + qualityIssues: Array; + /** + * Specifies if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Is of type Boolean: true, false. Use true if the call was a spam call. + */ + spam: boolean; + /** + * Specifies the Call Score, if available. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + */ + callScore: number; + /** + * Specifies any comments pertaining to the call. Twilio does not treat this field as PII, so no PII should be included in comments. + */ + comment: string; + /** + * Incident or support ticket associated with this call. The `incident` property is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + */ + incident: string; + url: string; + + private get _proxy(): AnnotationContext { + this._context = this._context || new AnnotationContextImpl(this._version, this._solution.callSid); + return this._context; + } + + /** + * Fetch a AnnotationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance + */ + fetch(callback?: (error: Error | null, item?: AnnotationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AnnotationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a AnnotationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance + */ + update(callback?: (error: Error | null, item?: AnnotationInstance) => any): Promise; + /** + * Update a AnnotationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance + */ + update(params: AnnotationContextUpdateOptions, callback?: (error: Error | null, item?: AnnotationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: AnnotationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a AnnotationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a AnnotationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnnotationInstance with HTTP metadata + */ + updateWithHttpInfo(params: AnnotationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + callSid: this.callSid, + accountSid: this.accountSid, + answeredBy: this.answeredBy, + connectivityIssue: this.connectivityIssue, + qualityIssues: this.qualityIssues, + spam: this.spam, + callScore: this.callScore, + comment: this.comment, + incident: this.incident, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AnnotationSolution { + callSid: string; +} + +export interface AnnotationListInstance { + _version: V1; + _solution: AnnotationSolution; + _uri: string; + + (): AnnotationContext; + get(): AnnotationContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AnnotationListInstance(version: V1, callSid: string): AnnotationListInstance { + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = (() => instance.get()) as AnnotationListInstance; + + instance.get = function get(): AnnotationContext { + return new AnnotationContextImpl(version, callSid); + } + + instance._version = version; + instance._solution = { callSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/insights/v1/call/callSummary.ts b/rest/insights/v1/call/callSummary.ts new file mode 100644 index 000000000..eb711e466 --- /dev/null +++ b/rest/insights/v1/call/callSummary.ts @@ -0,0 +1,552 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class CallSummaryAgentSessionSummary { + "sessionId"?: string; + "ttsLatencyMs"?: CallSummaryCrelayRateStats; + "sttLatencyMs"?: CallSummaryCrelayRateStats; + "networkLatencyMs"?: CallSummaryCrelayRateStats; + "timeToFirstAudioMs"?: CallSummaryCrelayRateStats; + "applicationLatencyMs"?: CallSummaryCrelayRateStats; + "tokens"?: CallSummaryCrelayTokenStats; + "words"?: CallSummaryCrelayWordStats; + "turns"?: number; + "interruptions"?: CallSummaryCrelayInterruptions; + "sessionState"?: CallSummaryCrelaySessionState; + + constructor(payload) { + this.sessionId = payload["session_id"]; + this.ttsLatencyMs = payload["tts_latency_ms"]; + this.sttLatencyMs = payload["stt_latency_ms"]; + this.networkLatencyMs = payload["network_latency_ms"]; + this.timeToFirstAudioMs = payload["time_to_first_audio_ms"]; + this.applicationLatencyMs = payload["application_latency_ms"]; + this.tokens = payload["tokens"]; + this.words = payload["words"]; + this.turns = payload["turns"]; + this.interruptions = payload["interruptions"]; + this.sessionState = payload["session_state"]; + } +} + + +export class CallSummaryCrelayInterruptions { + "customerToAgent"?: number; + "agentToCustomer"?: number; + + constructor(payload) { + this.customerToAgent = payload["customer_to_agent"]; + this.agentToCustomer = payload["agent_to_customer"]; + } +} + + +export class CallSummaryCrelayRateStats { + "min"?: number; + "max"?: number; + "avg"?: number; + + constructor(payload) { + this.min = payload["min"]; + this.max = payload["max"]; + this.avg = payload["avg"]; + } +} + + +export type CallSummaryCrelaySessionState = 'unknown'|'failure'|'ended'|'hung_up'; + +export class CallSummaryCrelayTokenStats { + "total"?: number; + "tokensPerSecond"?: CallSummaryCrelayRateStats; + + constructor(payload) { + this.total = payload["total"]; + this.tokensPerSecond = payload["tokens_per_second"]; + } +} + + +export class CallSummaryCrelayWordStats { + "total"?: number; + "wordsPerMinute"?: CallSummaryCrelayRateStats; + + constructor(payload) { + this.total = payload["total"]; + this.wordsPerMinute = payload["words_per_minute"]; + } +} + + +export type CallSummaryAnsweredBy = 'unknown'|'machine_start'|'machine_end_beep'|'machine_end_silence'|'machine_end_other'|'human'|'fax'; + +export type CallSummaryCallState = 'ringing'|'completed'|'busy'|'fail'|'noanswer'|'canceled'|'answered'|'undialed'; + +export type CallSummaryCallType = 'carrier'|'sip'|'trunking'|'client'|'whatsapp'; + +export type CallSummaryProcessingState = 'complete'|'partial'; + + +/** + * Options to pass to fetch a CallSummaryInstance + */ +export interface CallSummaryContextFetchOptions { + /** The Processing State of this Call Summary. One of `complete`, `partial` or `all`. */ + "processingState"?: CallSummaryProcessingState; +} + +export interface CallSummaryContext { + + /** + * Fetch a CallSummaryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallSummaryInstance + */ + fetch(callback?: (error: Error | null, item?: CallSummaryInstance) => any): Promise; + /** + * Fetch a CallSummaryInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallSummaryInstance + */ + fetch(params: CallSummaryContextFetchOptions, callback?: (error: Error | null, item?: CallSummaryInstance) => any): Promise; + + /** + * Fetch a CallSummaryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallSummaryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a CallSummaryInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallSummaryInstance with HTTP metadata + */ + fetchWithHttpInfo(params: CallSummaryContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CallSummaryContextSolution { + "callSid": string; +} + +export class CallSummaryContextImpl implements CallSummaryContext { + protected _solution: CallSummaryContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, callSid: string) { + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + this._solution = { callSid, }; + this._uri = `/Voice/${callSid}/Summary`; + } + + fetch(params?: CallSummaryContextFetchOptions | ((error: Error | null, item?: CallSummaryInstance) => any),callback?: (error: Error | null, item?: CallSummaryInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["processingState"] !== undefined) + data["ProcessingState"] = params["processingState"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new CallSummaryInstance(operationVersion, payload, instance._solution.callSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: CallSummaryContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["processingState"] !== undefined) + data["ProcessingState"] = params["processingState"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CallSummaryInstance(operationVersion, response.body, instance._solution.callSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CallSummaryPayload extends CallSummaryResource {} + +interface CallSummaryResource { + account_sid: string; + call_sid: string; + call_type: CallSummaryCallType; + call_state: CallSummaryCallState; + answered_by: CallSummaryAnsweredBy; + processing_state: CallSummaryProcessingState; + created_time: Date; + start_time: Date; + end_time: Date; + duration: number; + connect_duration: number; + from: any; + to: any; + carrier_edge: any; + client_edge: any; + sdk_edge: any; + sip_edge: any; + tags: Array; + url: string; + attributes: any; + properties: any; + trust: any; + annotation: any; + agent_session_summaries: Array; +} + +export class CallSummaryInstance { + protected _solution: CallSummaryContextSolution; + protected _context?: CallSummaryContext; + + constructor(protected _version: V1, payload: CallSummaryResource, callSid: string) { + + this.accountSid = (payload.account_sid); + this.callSid = (payload.call_sid); + this.callType = payload.call_type; + this.callState = payload.call_state; + this.answeredBy = payload.answered_by; + this.processingState = payload.processing_state; + this.createdTime = deserialize.iso8601DateTime(payload.created_time); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.duration = deserialize.integer(payload.duration); + this.connectDuration = deserialize.integer(payload.connect_duration); + this.from = (payload.from); + this.to = (payload.to); + this.carrierEdge = (payload.carrier_edge); + this.clientEdge = (payload.client_edge); + this.sdkEdge = (payload.sdk_edge); + this.sipEdge = (payload.sip_edge); + this.tags = (payload.tags); + this.url = (payload.url); + this.attributes = (payload.attributes); + this.properties = (payload.properties); + this.trust = (payload.trust); + this.annotation = (payload.annotation); + this.agentSessionSummaries = payload.agent_session_summaries !== null && payload.agent_session_summaries !== undefined ? payload.agent_session_summaries.map( + (payload: any) => new CallSummaryAgentSessionSummary(payload) + ) : null; + + this._solution = { callSid, }; + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Call. + */ + callSid: string; + callType: CallSummaryCallType; + callState: CallSummaryCallState; + answeredBy: CallSummaryAnsweredBy; + processingState: CallSummaryProcessingState; + /** + * The time at which the Call was created, given in ISO 8601 format. Can be different from `start_time` in the event of queueing due to CPS + */ + createdTime: Date; + /** + * The time at which the Call was started, given in ISO 8601 format. + */ + startTime: Date; + /** + * The time at which the Call was ended, given in ISO 8601 format. + */ + endTime: Date; + /** + * Duration between when the call was initiated and the call was ended + */ + duration: number; + /** + * Duration between when the call was answered and when it ended + */ + connectDuration: number; + /** + * `object` The calling party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + */ + from: any; + /** + * `object` The called party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + */ + to: any; + /** + * `object` Contains metrics and properties for the Twilio media gateway of a PSTN call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + carrierEdge: any; + /** + * `object` Contains metrics and properties for the Twilio media gateway of a Client call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + clientEdge: any; + /** + * `object` Contains metrics and properties for the SDK sensor library for Client calls. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + sdkEdge: any; + /** + * `object` Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + sipEdge: any; + /** + * Tags applied to calls by Voice Insights analysis indicating a condition that could result in subjective degradation of the call quality. + */ + tags: Array; + /** + * The URL of this resource. + */ + url: string; + /** + * `object` Attributes capturing call-flow-specific details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#attributes-object) for the object properties. + */ + attributes: any; + /** + * `object` Contains edge-agnostic call-level details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#properties-object) for the object properties. + */ + properties: any; + /** + * `object` Contains trusted communications details including Branded Call and verified caller ID. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#trust-object) for the object properties. + */ + trust: any; + /** + * `object` Programmatically labeled annotations for the Call. Developers can update the Call Summary records with Annotation during or after a Call. Annotations can be updated as long as the Call Summary record is addressable via the API. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#annotation-object) for the object properties. + */ + annotation: any; + /** + * `object` List of session summaries for conversation relay. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#conversation-relay-object) for the object properties. + */ + agentSessionSummaries: Array; + + private get _proxy(): CallSummaryContext { + this._context = this._context || new CallSummaryContextImpl(this._version, this._solution.callSid); + return this._context; + } + + /** + * Fetch a CallSummaryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallSummaryInstance + */ + fetch(callback?: (error: Error | null, item?: CallSummaryInstance) => any): Promise; + /** + * Fetch a CallSummaryInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallSummaryInstance + */ + fetch(params: CallSummaryContextFetchOptions, callback?: (error: Error | null, item?: CallSummaryInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: CallSummaryInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a CallSummaryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallSummaryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a CallSummaryInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CallSummaryInstance with HTTP metadata + */ + fetchWithHttpInfo(params: CallSummaryContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + callSid: this.callSid, + callType: this.callType, + callState: this.callState, + answeredBy: this.answeredBy, + processingState: this.processingState, + createdTime: this.createdTime, + startTime: this.startTime, + endTime: this.endTime, + duration: this.duration, + connectDuration: this.connectDuration, + from: this.from, + to: this.to, + carrierEdge: this.carrierEdge, + clientEdge: this.clientEdge, + sdkEdge: this.sdkEdge, + sipEdge: this.sipEdge, + tags: this.tags, + url: this.url, + attributes: this.attributes, + properties: this.properties, + trust: this.trust, + annotation: this.annotation, + agentSessionSummaries: this.agentSessionSummaries, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CallSummarySolution { + callSid: string; +} + +export interface CallSummaryListInstance { + _version: V1; + _solution: CallSummarySolution; + _uri: string; + + (): CallSummaryContext; + get(): CallSummaryContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CallSummaryListInstance(version: V1, callSid: string): CallSummaryListInstance { + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = (() => instance.get()) as CallSummaryListInstance; + + instance.get = function get(): CallSummaryContext { + return new CallSummaryContextImpl(version, callSid); + } + + instance._version = version; + instance._solution = { callSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/insights/v1/call/event.ts b/rest/insights/v1/call/event.ts new file mode 100644 index 000000000..368512232 --- /dev/null +++ b/rest/insights/v1/call/event.ts @@ -0,0 +1,620 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class CallWrapUpEvent { + /** + * Duration in seconds. + */ + "durationInSeconds"?: number; + /** + * End status of the call wrap up event. + */ + "endStatus"?: string; + + constructor(payload) { + this.durationInSeconds = payload["duration_in_seconds"]; + this.endStatus = payload["end_status"]; + } +} + + +export class ConfigurationEvent { + /** + * Key-value pairs for configuration settings. + */ + "configurations"?: { [key: string]: string; }; + /** + * Key-value pairs for language configurations. + */ + "languages"?: { [key: string]: ConfigurationEventLanguagesValue; }; + + constructor(payload) { + this.configurations = payload["configurations"]; + this.languages = payload["languages"]; + } +} + + +export class ConfigurationEventLanguagesValue { + "ttsProvider"?: string; + "voice"?: string; + "transcriptionProvider"?: string; + "speechModel"?: string; + + constructor(payload) { + this.ttsProvider = payload["tts_provider"]; + this.voice = payload["voice"]; + this.transcriptionProvider = payload["transcription_provider"]; + this.speechModel = payload["speech_model"]; + } +} + + +export class ErrorEvent { + /** + * Error code. + */ + "errorCode"?: number; + /** + * Error message. + */ + "message"?: string; + + constructor(payload) { + this.errorCode = payload["error_code"]; + this.message = payload["message"]; + } +} + + +export type EventLevel = 'UNKNOWN'|'DEBUG'|'INFO'|'WARNING'|'ERROR'; + +export type EventTwilioEdge = 'unknown_edge'|'carrier_edge'|'sip_edge'|'sdk_edge'|'client_edge'; + +/** + * Contains information about the Conversation Relay (CRelay) connection used in calls. + */ +export class InsightsV1CallEventConversationRelayData { + /** + * Session id of the conversation relay. + */ + "sessionId": string; + /** + * Sequence number of the event. + */ + "sequenceNumber": number; + "ttsLatency": LatencyEvent; + "sttLatency": LatencyEvent; + "interrupt": InterruptEvent; + "lastTokenReceived": LastTokenReceivedEvent; + "configurations": ConfigurationEvent; + "languageChanged": LanguageChangedEvent; + "callWrapUp": CallWrapUpEvent; + "error": ErrorEvent; + + constructor(payload) { + this.sessionId = payload["session_id"]; + this.sequenceNumber = payload["sequence_number"]; + this.ttsLatency = payload["tts_latency"]; + this.sttLatency = payload["stt_latency"]; + this.interrupt = payload["interrupt"]; + this.lastTokenReceived = payload["last_token_received"]; + this.configurations = payload["configurations"]; + this.languageChanged = payload["language_changed"]; + this.callWrapUp = payload["call_wrap_up"]; + this.error = payload["error"]; + } +} + + +export class InterruptEvent { + /** + * Type of interruption event. + */ + "type"?: string; + + constructor(payload) { + this.type = payload["type"]; + } +} + + +export class LanguageChangedEvent { + "ttsLanguageCode"?: string; + "transcriptionLanguageCode"?: string; + + constructor(payload) { + this.ttsLanguageCode = payload["tts_language_code"]; + this.transcriptionLanguageCode = payload["transcription_language_code"]; + } +} + + +export class LastTokenReceivedEvent { + /** + * Total number of tokens received. + */ + "totalTokens"?: number; + /** + * Total number of words received. + */ + "totalWords"?: number; + + constructor(payload) { + this.totalTokens = payload["total_tokens"]; + this.totalWords = payload["total_words"]; + } +} + + +export class LatencyEvent { + /** + * Latency in milliseconds. + */ + "latencyMs"?: number; + + constructor(payload) { + this.latencyMs = payload["latency_ms"]; + } +} + + + +/** + * Options to pass to each + */ +export interface EventListInstanceEachOptions { + /** The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. */ + "edge"?: EventTwilioEdge; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EventInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EventListInstanceOptions { + /** The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. */ + "edge"?: EventTwilioEdge; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EventListInstancePageOptions { + /** The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. */ + "edge"?: EventTwilioEdge; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface EventSolution { + callSid: string; +} + +export interface EventListInstance { + _version: V1; + _solution: EventSolution; + _uri: string; + + + + + /** + * Streams EventInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + each(params: EventListInstanceEachOptions, callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EventInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EventListInstanceEachOptions, callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EventInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EventPage) => any): Promise; + /** + * Retrieve a single target page of EventInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists EventInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EventInstance[]) => any): Promise; + list(params: EventListInstanceOptions, callback?: (error: Error | null, items: EventInstance[]) => any): Promise; + /** + * Lists EventInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: EventListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of EventInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EventPage) => any): Promise; + page(params: EventListInstancePageOptions, callback?: (error: Error | null, items: EventPage) => any): Promise; + /** + * Retrieve a single page of EventInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: EventListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EventListInstance(version: V1, callSid: string): EventListInstance { + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = {} as EventListInstance; + + instance._version = version; + instance._solution = { callSid, }; + instance._uri = `/Voice/${callSid}/Events`; + + instance.page = function page(params?: EventListInstancePageOptions | ((error: Error | null, items: EventPage) => any), callback?: (error: Error | null, items: EventPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["edge"] !== undefined) + data["Edge"] = params["edge"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EventPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EventPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EventPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EventListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["edge"] !== undefined) + data["Edge"] = params["edge"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EventPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EventPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface EventPayload extends TwilioResponsePayload { + events: EventResource[]; +} + +interface EventResource { + timestamp: string; + call_sid: string; + account_sid: string; + edge: EventTwilioEdge; + group: string; + level: EventLevel; + name: string; + carrier_edge: any; + sip_edge: any; + sdk_edge: any; + client_edge: any; + conversation_relay_data: InsightsV1CallEventConversationRelayData; +} + +export class EventInstance { + + constructor(protected _version: V1, payload: EventResource, callSid: string) { + + this.timestamp = (payload.timestamp); + this.callSid = (payload.call_sid); + this.accountSid = (payload.account_sid); + this.edge = payload.edge; + this.group = (payload.group); + this.level = payload.level; + this.name = (payload.name); + this.carrierEdge = (payload.carrier_edge); + this.sipEdge = (payload.sip_edge); + this.sdkEdge = (payload.sdk_edge); + this.clientEdge = (payload.client_edge); + this.conversationRelayData = payload.conversation_relay_data !== null && payload.conversation_relay_data !== undefined ? new InsightsV1CallEventConversationRelayData(payload.conversation_relay_data) : null; + + } + + /** + * Event time. + */ + timestamp: string; + /** + * The unique SID identifier of the Call. + */ + callSid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + edge: EventTwilioEdge; + /** + * Event group. + */ + group: string; + level: EventLevel; + /** + * Event name. + */ + name: string; + /** + * `object` Represents the connection between Twilio and our immediate carrier partners. The events here describe the call lifecycle as reported by Twilio\'s carrier media gateways. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + carrierEdge: any; + /** + * `object` Represents the Twilio media gateway for SIP interface and SIP trunking calls. The events here describe the call lifecycle as reported by Twilio\'s public media gateways. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + sipEdge: any; + /** + * `object` Represents the Voice SDK running locally in the browser or in the Android/iOS application. The events here are emitted by the Voice SDK in response to certain call progress events, network changes, or call quality conditions. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + sdkEdge: any; + /** + * `object` Represents the Twilio media gateway for Client calls. The events here describe the call lifecycle as reported by Twilio\'s Voice SDK media gateways. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + clientEdge: any; + conversationRelayData: InsightsV1CallEventConversationRelayData; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + timestamp: this.timestamp, + callSid: this.callSid, + accountSid: this.accountSid, + edge: this.edge, + group: this.group, + level: this.level, + name: this.name, + carrierEdge: this.carrierEdge, + sipEdge: this.sipEdge, + sdkEdge: this.sdkEdge, + clientEdge: this.clientEdge, + conversationRelayData: this.conversationRelayData, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class EventPage extends Page { +/** +* Initialize the EventPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: EventSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EventInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EventResource): EventInstance { + + return new EventInstance( + this._version, + payload, + this._solution.callSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/insights/v1/call/metric.ts b/rest/insights/v1/call/metric.ts new file mode 100644 index 000000000..21ab7ae1b --- /dev/null +++ b/rest/insights/v1/call/metric.ts @@ -0,0 +1,458 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export type MetricStreamDirection = 'unknown'|'inbound'|'outbound'|'both'; + +export type MetricTwilioEdge = 'unknown_edge'|'carrier_edge'|'sip_edge'|'sdk_edge'|'client_edge'; + + +/** + * Options to pass to each + */ +export interface MetricListInstanceEachOptions { + /** The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. */ + "edge"?: MetricTwilioEdge; + /** The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. */ + "direction"?: MetricStreamDirection; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MetricInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MetricListInstanceOptions { + /** The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. */ + "edge"?: MetricTwilioEdge; + /** The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. */ + "direction"?: MetricStreamDirection; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MetricListInstancePageOptions { + /** The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. */ + "edge"?: MetricTwilioEdge; + /** The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. */ + "direction"?: MetricStreamDirection; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface MetricSolution { + callSid: string; +} + +export interface MetricListInstance { + _version: V1; + _solution: MetricSolution; + _uri: string; + + + + + /** + * Streams MetricInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MetricListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MetricInstance, done: (err?: Error) => void) => void): void; + each(params: MetricListInstanceEachOptions, callback?: (item: MetricInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MetricInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MetricListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MetricInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MetricListInstanceEachOptions, callback?: (item: MetricInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MetricInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MetricPage) => any): Promise; + /** + * Retrieve a single target page of MetricInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MetricInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MetricListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MetricInstance[]) => any): Promise; + list(params: MetricListInstanceOptions, callback?: (error: Error | null, items: MetricInstance[]) => any): Promise; + /** + * Lists MetricInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MetricListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MetricListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MetricInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MetricListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MetricPage) => any): Promise; + page(params: MetricListInstancePageOptions, callback?: (error: Error | null, items: MetricPage) => any): Promise; + /** + * Retrieve a single page of MetricInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MetricListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MetricListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MetricListInstance(version: V1, callSid: string): MetricListInstance { + if (!isValidPathParam(callSid)) { + throw new Error('Parameter \'callSid\' is not valid.'); + } + + const instance = {} as MetricListInstance; + + instance._version = version; + instance._solution = { callSid, }; + instance._uri = `/Voice/${callSid}/Metrics`; + + instance.page = function page(params?: MetricListInstancePageOptions | ((error: Error | null, items: MetricPage) => any), callback?: (error: Error | null, items: MetricPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["edge"] !== undefined) + data["Edge"] = params["edge"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MetricPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MetricPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MetricPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MetricListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["edge"] !== undefined) + data["Edge"] = params["edge"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MetricPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MetricPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface MetricPayload extends TwilioResponsePayload { + metrics: MetricResource[]; +} + +interface MetricResource { + timestamp: string; + call_sid: string; + account_sid: string; + edge: MetricTwilioEdge; + direction: MetricStreamDirection; + carrier_edge: any; + sip_edge: any; + sdk_edge: any; + client_edge: any; +} + +export class MetricInstance { + + constructor(protected _version: V1, payload: MetricResource, callSid: string) { + + this.timestamp = (payload.timestamp); + this.callSid = (payload.call_sid); + this.accountSid = (payload.account_sid); + this.edge = payload.edge; + this.direction = payload.direction; + this.carrierEdge = (payload.carrier_edge); + this.sipEdge = (payload.sip_edge); + this.sdkEdge = (payload.sdk_edge); + this.clientEdge = (payload.client_edge); + + } + + /** + * Timestamp of metric sample. Samples are taken every 10 seconds and contain the metrics for the previous 10 seconds. + */ + timestamp: string; + /** + * The unique SID identifier of the Call. + */ + callSid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + edge: MetricTwilioEdge; + direction: MetricStreamDirection; + /** + * Contains metrics and properties for the Twilio media gateway of a PSTN call. + */ + carrierEdge: any; + /** + * Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + */ + sipEdge: any; + /** + * Contains metrics and properties for the SDK sensor library for Client calls. + */ + sdkEdge: any; + /** + * Contains metrics and properties for the Twilio media gateway of a Client call. + */ + clientEdge: any; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + timestamp: this.timestamp, + callSid: this.callSid, + accountSid: this.accountSid, + edge: this.edge, + direction: this.direction, + carrierEdge: this.carrierEdge, + sipEdge: this.sipEdge, + sdkEdge: this.sdkEdge, + clientEdge: this.clientEdge, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class MetricPage extends Page { +/** +* Initialize the MetricPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: MetricSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MetricInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MetricResource): MetricInstance { + + return new MetricInstance( + this._version, + payload, + this._solution.callSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/insights/v1/callSummaries.ts b/rest/insights/v1/callSummaries.ts new file mode 100644 index 000000000..846e5312f --- /dev/null +++ b/rest/insights/v1/callSummaries.ts @@ -0,0 +1,978 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export type CallSummariesAnsweredBy = 'unknown'|'machine_start'|'machine_end_beep'|'machine_end_silence'|'machine_end_other'|'human'|'fax'; + +export type CallSummariesCallState = 'ringing'|'completed'|'busy'|'fail'|'noanswer'|'canceled'|'answered'|'undialed'; + +export type CallSummariesCallType = 'carrier'|'sip'|'trunking'|'client'|'whatsapp'; + +export type CallSummariesProcessingState = 'complete'|'partial'; + +export type CallSummariesProcessingStateRequest = 'completed'|'started'|'partial'|'all'; + +export type CallSummariesSortBy = 'start_time'|'end_time'; + +export class CallSummaryAgentSessionSummary { + "sessionId"?: string; + "ttsLatencyMs"?: CallSummaryCrelayRateStats; + "sttLatencyMs"?: CallSummaryCrelayRateStats; + "networkLatencyMs"?: CallSummaryCrelayRateStats; + "timeToFirstAudioMs"?: CallSummaryCrelayRateStats; + "applicationLatencyMs"?: CallSummaryCrelayRateStats; + "tokens"?: CallSummaryCrelayTokenStats; + "words"?: CallSummaryCrelayWordStats; + "turns"?: number; + "interruptions"?: CallSummaryCrelayInterruptions; + "sessionState"?: CallSummaryCrelaySessionState; + + constructor(payload) { + this.sessionId = payload["session_id"]; + this.ttsLatencyMs = payload["tts_latency_ms"]; + this.sttLatencyMs = payload["stt_latency_ms"]; + this.networkLatencyMs = payload["network_latency_ms"]; + this.timeToFirstAudioMs = payload["time_to_first_audio_ms"]; + this.applicationLatencyMs = payload["application_latency_ms"]; + this.tokens = payload["tokens"]; + this.words = payload["words"]; + this.turns = payload["turns"]; + this.interruptions = payload["interruptions"]; + this.sessionState = payload["session_state"]; + } +} + + +export class CallSummaryCrelayInterruptions { + "customerToAgent"?: number; + "agentToCustomer"?: number; + + constructor(payload) { + this.customerToAgent = payload["customer_to_agent"]; + this.agentToCustomer = payload["agent_to_customer"]; + } +} + + +export class CallSummaryCrelayRateStats { + "min"?: number; + "max"?: number; + "avg"?: number; + + constructor(payload) { + this.min = payload["min"]; + this.max = payload["max"]; + this.avg = payload["avg"]; + } +} + + +export type CallSummaryCrelaySessionState = 'unknown'|'failure'|'ended'|'hung_up'; + +export class CallSummaryCrelayTokenStats { + "total"?: number; + "tokensPerSecond"?: CallSummaryCrelayRateStats; + + constructor(payload) { + this.total = payload["total"]; + this.tokensPerSecond = payload["tokens_per_second"]; + } +} + + +export class CallSummaryCrelayWordStats { + "total"?: number; + "wordsPerMinute"?: CallSummaryCrelayRateStats; + + constructor(payload) { + this.total = payload["total"]; + this.wordsPerMinute = payload["words_per_minute"]; + } +} + + + +/** + * Options to pass to each + */ +export interface CallSummariesListInstanceEachOptions { + /** A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. */ + "from"?: string; + /** A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. */ + "to"?: string; + /** An origination carrier. */ + "fromCarrier"?: string; + /** A destination carrier. */ + "toCarrier"?: string; + /** A source country code based on phone number in From. */ + "fromCountryCode"?: string; + /** A destination country code. Based on phone number in To. */ + "toCountryCode"?: string; + /** A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of \'true\' or \'false\'. */ + "verifiedCaller"?: boolean; + /** A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). */ + "hasTag"?: boolean; + /** A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. */ + "startTime"?: string; + /** An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. */ + "endTime"?: string; + /** A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. */ + "callType"?: string; + /** A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. */ + "callState"?: string; + /** A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. */ + "direction"?: string; + /** A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. */ + "processingState"?: CallSummariesProcessingStateRequest; + /** A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. */ + "sortBy"?: CallSummariesSortBy; + /** A unique SID identifier of a Subaccount. */ + "subaccount"?: string; + /** A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. */ + "abnormalSession"?: boolean; + /** An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. */ + "answeredBy"?: CallSummariesAnsweredBy; + /** Either machine or human. */ + "answeredByAnnotation"?: string; + /** A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. */ + "connectivityIssueAnnotation"?: string; + /** A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. */ + "qualityIssueAnnotation"?: string; + /** A boolean flag indicating spam calls. */ + "spamAnnotation"?: boolean; + /** A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. */ + "callScoreAnnotation"?: string; + /** A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of \'true\' or \'false\' */ + "brandedEnabled"?: boolean; + /** A boolean flag indicating whether or not the phone number had voice integrity enabled.One of \'true\' or \'false\' */ + "voiceIntegrityEnabled"?: boolean; + /** A unique SID identifier of the Branded Call. */ + "brandedBundleSid"?: string; + /** Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). */ + "brandedLogo"?: boolean; + /** Indicates whether the Branded Call is in_band vs out_of_band. */ + "brandedType"?: string; + /** Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. */ + "brandedUseCase"?: string; + /** Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. */ + "brandedCallReason"?: string; + /** A unique SID identifier of the Voice Integrity Profile. */ + "voiceIntegrityBundleSid"?: string; + /** A Voice Integrity Use Case . Is of type enum. One of \'abandoned_cart\', \'appointment_reminders\', \'appointment_scheduling\', \'asset_management\', \'automated_support\', \'call_tracking\', \'click_to_call\', \'contact_tracing\', \'contactless_delivery\', \'customer_support\', \'dating/social\', \'delivery_notifications\', \'distance_learning\', \'emergency_notifications\', \'employee_notifications\', \'exam_proctoring\', \'field_notifications\', \'first_responder\', \'fraud_alerts\', \'group_messaging\', \'identify_&_verification\', \'intelligent_routing\', \'lead_alerts\', \'lead_distribution\', \'lead_generation\', \'lead_management\', \'lead_nurturing\', \'marketing_events\', \'mass_alerts\', \'meetings/collaboration\', \'order_notifications\', \'outbound_dialer\', \'pharmacy\', \'phone_system\', \'purchase_confirmation\', \'remote_appointments\', \'rewards_program\', \'self-service\', \'service_alerts\', \'shift_management\', \'survey/research\', \'telehealth\', \'telemarketing\', \'therapy_(individual+group)\'. */ + "voiceIntegrityUseCase"?: string; + /** A Business Identity of the calls. Is of type enum. One of \'direct_customer\', \'isv_reseller_or_partner\'. */ + "businessProfileIdentity"?: string; + /** A Business Industry of the calls. Is of type enum. One of \'automotive\', \'agriculture\', \'banking\', \'consumer\', \'construction\', \'education\', \'engineering\', \'energy\', \'oil_and_gas\', \'fast_moving_consumer_goods\', \'financial\', \'fintech\', \'food_and_beverage\', \'government\', \'healthcare\', \'hospitality\', \'insurance\', \'legal\', \'manufacturing\', \'media\', \'online\', \'professional_services\', \'raw_materials\', \'real_estate\', \'religion\', \'retail\', \'jewelry\', \'technology\', \'telecommunications\', \'transportation\', \'travel\', \'electronics\', \'not_for_profit\' */ + "businessProfileIndustry"?: string; + /** A unique SID identifier of the Business Profile. */ + "businessProfileBundleSid"?: string; + /** A Business Profile Type of the calls. Is of type enum. One of \'primary\', \'secondary\'. */ + "businessProfileType"?: string; + /** How many resources to return in each list page. The default is 25, and the maximum is 25. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CallSummariesInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CallSummariesListInstanceOptions { + /** A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. */ + "from"?: string; + /** A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. */ + "to"?: string; + /** An origination carrier. */ + "fromCarrier"?: string; + /** A destination carrier. */ + "toCarrier"?: string; + /** A source country code based on phone number in From. */ + "fromCountryCode"?: string; + /** A destination country code. Based on phone number in To. */ + "toCountryCode"?: string; + /** A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of \'true\' or \'false\'. */ + "verifiedCaller"?: boolean; + /** A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). */ + "hasTag"?: boolean; + /** A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. */ + "startTime"?: string; + /** An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. */ + "endTime"?: string; + /** A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. */ + "callType"?: string; + /** A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. */ + "callState"?: string; + /** A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. */ + "direction"?: string; + /** A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. */ + "processingState"?: CallSummariesProcessingStateRequest; + /** A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. */ + "sortBy"?: CallSummariesSortBy; + /** A unique SID identifier of a Subaccount. */ + "subaccount"?: string; + /** A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. */ + "abnormalSession"?: boolean; + /** An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. */ + "answeredBy"?: CallSummariesAnsweredBy; + /** Either machine or human. */ + "answeredByAnnotation"?: string; + /** A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. */ + "connectivityIssueAnnotation"?: string; + /** A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. */ + "qualityIssueAnnotation"?: string; + /** A boolean flag indicating spam calls. */ + "spamAnnotation"?: boolean; + /** A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. */ + "callScoreAnnotation"?: string; + /** A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of \'true\' or \'false\' */ + "brandedEnabled"?: boolean; + /** A boolean flag indicating whether or not the phone number had voice integrity enabled.One of \'true\' or \'false\' */ + "voiceIntegrityEnabled"?: boolean; + /** A unique SID identifier of the Branded Call. */ + "brandedBundleSid"?: string; + /** Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). */ + "brandedLogo"?: boolean; + /** Indicates whether the Branded Call is in_band vs out_of_band. */ + "brandedType"?: string; + /** Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. */ + "brandedUseCase"?: string; + /** Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. */ + "brandedCallReason"?: string; + /** A unique SID identifier of the Voice Integrity Profile. */ + "voiceIntegrityBundleSid"?: string; + /** A Voice Integrity Use Case . Is of type enum. One of \'abandoned_cart\', \'appointment_reminders\', \'appointment_scheduling\', \'asset_management\', \'automated_support\', \'call_tracking\', \'click_to_call\', \'contact_tracing\', \'contactless_delivery\', \'customer_support\', \'dating/social\', \'delivery_notifications\', \'distance_learning\', \'emergency_notifications\', \'employee_notifications\', \'exam_proctoring\', \'field_notifications\', \'first_responder\', \'fraud_alerts\', \'group_messaging\', \'identify_&_verification\', \'intelligent_routing\', \'lead_alerts\', \'lead_distribution\', \'lead_generation\', \'lead_management\', \'lead_nurturing\', \'marketing_events\', \'mass_alerts\', \'meetings/collaboration\', \'order_notifications\', \'outbound_dialer\', \'pharmacy\', \'phone_system\', \'purchase_confirmation\', \'remote_appointments\', \'rewards_program\', \'self-service\', \'service_alerts\', \'shift_management\', \'survey/research\', \'telehealth\', \'telemarketing\', \'therapy_(individual+group)\'. */ + "voiceIntegrityUseCase"?: string; + /** A Business Identity of the calls. Is of type enum. One of \'direct_customer\', \'isv_reseller_or_partner\'. */ + "businessProfileIdentity"?: string; + /** A Business Industry of the calls. Is of type enum. One of \'automotive\', \'agriculture\', \'banking\', \'consumer\', \'construction\', \'education\', \'engineering\', \'energy\', \'oil_and_gas\', \'fast_moving_consumer_goods\', \'financial\', \'fintech\', \'food_and_beverage\', \'government\', \'healthcare\', \'hospitality\', \'insurance\', \'legal\', \'manufacturing\', \'media\', \'online\', \'professional_services\', \'raw_materials\', \'real_estate\', \'religion\', \'retail\', \'jewelry\', \'technology\', \'telecommunications\', \'transportation\', \'travel\', \'electronics\', \'not_for_profit\' */ + "businessProfileIndustry"?: string; + /** A unique SID identifier of the Business Profile. */ + "businessProfileBundleSid"?: string; + /** A Business Profile Type of the calls. Is of type enum. One of \'primary\', \'secondary\'. */ + "businessProfileType"?: string; + /** How many resources to return in each list page. The default is 25, and the maximum is 25. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CallSummariesListInstancePageOptions { + /** A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. */ + "from"?: string; + /** A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. */ + "to"?: string; + /** An origination carrier. */ + "fromCarrier"?: string; + /** A destination carrier. */ + "toCarrier"?: string; + /** A source country code based on phone number in From. */ + "fromCountryCode"?: string; + /** A destination country code. Based on phone number in To. */ + "toCountryCode"?: string; + /** A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of \'true\' or \'false\'. */ + "verifiedCaller"?: boolean; + /** A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). */ + "hasTag"?: boolean; + /** A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. */ + "startTime"?: string; + /** An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. */ + "endTime"?: string; + /** A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. */ + "callType"?: string; + /** A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. */ + "callState"?: string; + /** A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. */ + "direction"?: string; + /** A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. */ + "processingState"?: CallSummariesProcessingStateRequest; + /** A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. */ + "sortBy"?: CallSummariesSortBy; + /** A unique SID identifier of a Subaccount. */ + "subaccount"?: string; + /** A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. */ + "abnormalSession"?: boolean; + /** An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. */ + "answeredBy"?: CallSummariesAnsweredBy; + /** Either machine or human. */ + "answeredByAnnotation"?: string; + /** A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. */ + "connectivityIssueAnnotation"?: string; + /** A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. */ + "qualityIssueAnnotation"?: string; + /** A boolean flag indicating spam calls. */ + "spamAnnotation"?: boolean; + /** A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. */ + "callScoreAnnotation"?: string; + /** A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of \'true\' or \'false\' */ + "brandedEnabled"?: boolean; + /** A boolean flag indicating whether or not the phone number had voice integrity enabled.One of \'true\' or \'false\' */ + "voiceIntegrityEnabled"?: boolean; + /** A unique SID identifier of the Branded Call. */ + "brandedBundleSid"?: string; + /** Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). */ + "brandedLogo"?: boolean; + /** Indicates whether the Branded Call is in_band vs out_of_band. */ + "brandedType"?: string; + /** Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. */ + "brandedUseCase"?: string; + /** Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. */ + "brandedCallReason"?: string; + /** A unique SID identifier of the Voice Integrity Profile. */ + "voiceIntegrityBundleSid"?: string; + /** A Voice Integrity Use Case . Is of type enum. One of \'abandoned_cart\', \'appointment_reminders\', \'appointment_scheduling\', \'asset_management\', \'automated_support\', \'call_tracking\', \'click_to_call\', \'contact_tracing\', \'contactless_delivery\', \'customer_support\', \'dating/social\', \'delivery_notifications\', \'distance_learning\', \'emergency_notifications\', \'employee_notifications\', \'exam_proctoring\', \'field_notifications\', \'first_responder\', \'fraud_alerts\', \'group_messaging\', \'identify_&_verification\', \'intelligent_routing\', \'lead_alerts\', \'lead_distribution\', \'lead_generation\', \'lead_management\', \'lead_nurturing\', \'marketing_events\', \'mass_alerts\', \'meetings/collaboration\', \'order_notifications\', \'outbound_dialer\', \'pharmacy\', \'phone_system\', \'purchase_confirmation\', \'remote_appointments\', \'rewards_program\', \'self-service\', \'service_alerts\', \'shift_management\', \'survey/research\', \'telehealth\', \'telemarketing\', \'therapy_(individual+group)\'. */ + "voiceIntegrityUseCase"?: string; + /** A Business Identity of the calls. Is of type enum. One of \'direct_customer\', \'isv_reseller_or_partner\'. */ + "businessProfileIdentity"?: string; + /** A Business Industry of the calls. Is of type enum. One of \'automotive\', \'agriculture\', \'banking\', \'consumer\', \'construction\', \'education\', \'engineering\', \'energy\', \'oil_and_gas\', \'fast_moving_consumer_goods\', \'financial\', \'fintech\', \'food_and_beverage\', \'government\', \'healthcare\', \'hospitality\', \'insurance\', \'legal\', \'manufacturing\', \'media\', \'online\', \'professional_services\', \'raw_materials\', \'real_estate\', \'religion\', \'retail\', \'jewelry\', \'technology\', \'telecommunications\', \'transportation\', \'travel\', \'electronics\', \'not_for_profit\' */ + "businessProfileIndustry"?: string; + /** A unique SID identifier of the Business Profile. */ + "businessProfileBundleSid"?: string; + /** A Business Profile Type of the calls. Is of type enum. One of \'primary\', \'secondary\'. */ + "businessProfileType"?: string; + /** How many resources to return in each list page. The default is 25, and the maximum is 25. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface CallSummariesSolution { +} + +export interface CallSummariesListInstance { + _version: V1; + _solution: CallSummariesSolution; + _uri: string; + + + + + /** + * Streams CallSummariesInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallSummariesListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CallSummariesInstance, done: (err?: Error) => void) => void): void; + each(params: CallSummariesListInstanceEachOptions, callback?: (item: CallSummariesInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CallSummariesInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallSummariesListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CallSummariesInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CallSummariesListInstanceEachOptions, callback?: (item: CallSummariesInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CallSummariesInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CallSummariesPage) => any): Promise; + /** + * Retrieve a single target page of CallSummariesInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CallSummariesInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallSummariesListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CallSummariesInstance[]) => any): Promise; + list(params: CallSummariesListInstanceOptions, callback?: (error: Error | null, items: CallSummariesInstance[]) => any): Promise; + /** + * Lists CallSummariesInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallSummariesListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CallSummariesListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CallSummariesInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallSummariesListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CallSummariesPage) => any): Promise; + page(params: CallSummariesListInstancePageOptions, callback?: (error: Error | null, items: CallSummariesPage) => any): Promise; + /** + * Retrieve a single page of CallSummariesInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CallSummariesListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CallSummariesListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CallSummariesListInstance(version: V1): CallSummariesListInstance { + const instance = {} as CallSummariesListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Voice/Summaries`; + + instance.page = function page(params?: CallSummariesListInstancePageOptions | ((error: Error | null, items: CallSummariesPage) => any), callback?: (error: Error | null, items: CallSummariesPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["fromCarrier"] !== undefined) + data["FromCarrier"] = params["fromCarrier"]; + if (params["toCarrier"] !== undefined) + data["ToCarrier"] = params["toCarrier"]; + if (params["fromCountryCode"] !== undefined) + data["FromCountryCode"] = params["fromCountryCode"]; + if (params["toCountryCode"] !== undefined) + data["ToCountryCode"] = params["toCountryCode"]; + if (params["verifiedCaller"] !== undefined) + data["VerifiedCaller"] = serialize.bool(params["verifiedCaller"]); + if (params["hasTag"] !== undefined) + data["HasTag"] = serialize.bool(params["hasTag"]); + if (params["startTime"] !== undefined) + data["StartTime"] = params["startTime"]; + if (params["endTime"] !== undefined) + data["EndTime"] = params["endTime"]; + if (params["callType"] !== undefined) + data["CallType"] = params["callType"]; + if (params["callState"] !== undefined) + data["CallState"] = params["callState"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["processingState"] !== undefined) + data["ProcessingState"] = params["processingState"]; + if (params["sortBy"] !== undefined) + data["SortBy"] = params["sortBy"]; + if (params["subaccount"] !== undefined) + data["Subaccount"] = params["subaccount"]; + if (params["abnormalSession"] !== undefined) + data["AbnormalSession"] = serialize.bool(params["abnormalSession"]); + if (params["answeredBy"] !== undefined) + data["AnsweredBy"] = params["answeredBy"]; + if (params["answeredByAnnotation"] !== undefined) + data["AnsweredByAnnotation"] = params["answeredByAnnotation"]; + if (params["connectivityIssueAnnotation"] !== undefined) + data["ConnectivityIssueAnnotation"] = params["connectivityIssueAnnotation"]; + if (params["qualityIssueAnnotation"] !== undefined) + data["QualityIssueAnnotation"] = params["qualityIssueAnnotation"]; + if (params["spamAnnotation"] !== undefined) + data["SpamAnnotation"] = serialize.bool(params["spamAnnotation"]); + if (params["callScoreAnnotation"] !== undefined) + data["CallScoreAnnotation"] = params["callScoreAnnotation"]; + if (params["brandedEnabled"] !== undefined) + data["BrandedEnabled"] = serialize.bool(params["brandedEnabled"]); + if (params["voiceIntegrityEnabled"] !== undefined) + data["VoiceIntegrityEnabled"] = serialize.bool(params["voiceIntegrityEnabled"]); + if (params["brandedBundleSid"] !== undefined) + data["BrandedBundleSid"] = params["brandedBundleSid"]; + if (params["brandedLogo"] !== undefined) + data["BrandedLogo"] = serialize.bool(params["brandedLogo"]); + if (params["brandedType"] !== undefined) + data["BrandedType"] = params["brandedType"]; + if (params["brandedUseCase"] !== undefined) + data["BrandedUseCase"] = params["brandedUseCase"]; + if (params["brandedCallReason"] !== undefined) + data["BrandedCallReason"] = params["brandedCallReason"]; + if (params["voiceIntegrityBundleSid"] !== undefined) + data["VoiceIntegrityBundleSid"] = params["voiceIntegrityBundleSid"]; + if (params["voiceIntegrityUseCase"] !== undefined) + data["VoiceIntegrityUseCase"] = params["voiceIntegrityUseCase"]; + if (params["businessProfileIdentity"] !== undefined) + data["BusinessProfileIdentity"] = params["businessProfileIdentity"]; + if (params["businessProfileIndustry"] !== undefined) + data["BusinessProfileIndustry"] = params["businessProfileIndustry"]; + if (params["businessProfileBundleSid"] !== undefined) + data["BusinessProfileBundleSid"] = params["businessProfileBundleSid"]; + if (params["businessProfileType"] !== undefined) + data["BusinessProfileType"] = params["businessProfileType"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CallSummariesPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CallSummariesPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CallSummariesPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CallSummariesListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["fromCarrier"] !== undefined) + data["FromCarrier"] = params["fromCarrier"]; + if (params["toCarrier"] !== undefined) + data["ToCarrier"] = params["toCarrier"]; + if (params["fromCountryCode"] !== undefined) + data["FromCountryCode"] = params["fromCountryCode"]; + if (params["toCountryCode"] !== undefined) + data["ToCountryCode"] = params["toCountryCode"]; + if (params["verifiedCaller"] !== undefined) + data["VerifiedCaller"] = serialize.bool(params["verifiedCaller"]); + if (params["hasTag"] !== undefined) + data["HasTag"] = serialize.bool(params["hasTag"]); + if (params["startTime"] !== undefined) + data["StartTime"] = params["startTime"]; + if (params["endTime"] !== undefined) + data["EndTime"] = params["endTime"]; + if (params["callType"] !== undefined) + data["CallType"] = params["callType"]; + if (params["callState"] !== undefined) + data["CallState"] = params["callState"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["processingState"] !== undefined) + data["ProcessingState"] = params["processingState"]; + if (params["sortBy"] !== undefined) + data["SortBy"] = params["sortBy"]; + if (params["subaccount"] !== undefined) + data["Subaccount"] = params["subaccount"]; + if (params["abnormalSession"] !== undefined) + data["AbnormalSession"] = serialize.bool(params["abnormalSession"]); + if (params["answeredBy"] !== undefined) + data["AnsweredBy"] = params["answeredBy"]; + if (params["answeredByAnnotation"] !== undefined) + data["AnsweredByAnnotation"] = params["answeredByAnnotation"]; + if (params["connectivityIssueAnnotation"] !== undefined) + data["ConnectivityIssueAnnotation"] = params["connectivityIssueAnnotation"]; + if (params["qualityIssueAnnotation"] !== undefined) + data["QualityIssueAnnotation"] = params["qualityIssueAnnotation"]; + if (params["spamAnnotation"] !== undefined) + data["SpamAnnotation"] = serialize.bool(params["spamAnnotation"]); + if (params["callScoreAnnotation"] !== undefined) + data["CallScoreAnnotation"] = params["callScoreAnnotation"]; + if (params["brandedEnabled"] !== undefined) + data["BrandedEnabled"] = serialize.bool(params["brandedEnabled"]); + if (params["voiceIntegrityEnabled"] !== undefined) + data["VoiceIntegrityEnabled"] = serialize.bool(params["voiceIntegrityEnabled"]); + if (params["brandedBundleSid"] !== undefined) + data["BrandedBundleSid"] = params["brandedBundleSid"]; + if (params["brandedLogo"] !== undefined) + data["BrandedLogo"] = serialize.bool(params["brandedLogo"]); + if (params["brandedType"] !== undefined) + data["BrandedType"] = params["brandedType"]; + if (params["brandedUseCase"] !== undefined) + data["BrandedUseCase"] = params["brandedUseCase"]; + if (params["brandedCallReason"] !== undefined) + data["BrandedCallReason"] = params["brandedCallReason"]; + if (params["voiceIntegrityBundleSid"] !== undefined) + data["VoiceIntegrityBundleSid"] = params["voiceIntegrityBundleSid"]; + if (params["voiceIntegrityUseCase"] !== undefined) + data["VoiceIntegrityUseCase"] = params["voiceIntegrityUseCase"]; + if (params["businessProfileIdentity"] !== undefined) + data["BusinessProfileIdentity"] = params["businessProfileIdentity"]; + if (params["businessProfileIndustry"] !== undefined) + data["BusinessProfileIndustry"] = params["businessProfileIndustry"]; + if (params["businessProfileBundleSid"] !== undefined) + data["BusinessProfileBundleSid"] = params["businessProfileBundleSid"]; + if (params["businessProfileType"] !== undefined) + data["BusinessProfileType"] = params["businessProfileType"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CallSummariesPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CallSummariesPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface CallSummariesPayload extends TwilioResponsePayload { + call_summaries: CallSummariesResource[]; +} + +interface CallSummariesResource { + account_sid: string; + call_sid: string; + answered_by: CallSummariesAnsweredBy; + call_type: CallSummariesCallType; + call_state: CallSummariesCallState; + processing_state: CallSummariesProcessingState; + created_time: Date; + start_time: Date; + end_time: Date; + duration: number; + connect_duration: number; + from: any; + to: any; + carrier_edge: any; + client_edge: any; + sdk_edge: any; + sip_edge: any; + tags: Array; + url: string; + attributes: any; + properties: any; + trust: any; + annotation: any; + agent_session_summaries: Array; +} + +export class CallSummariesInstance { + + constructor(protected _version: V1, payload: CallSummariesResource) { + + this.accountSid = (payload.account_sid); + this.callSid = (payload.call_sid); + this.answeredBy = payload.answered_by; + this.callType = payload.call_type; + this.callState = payload.call_state; + this.processingState = payload.processing_state; + this.createdTime = deserialize.iso8601DateTime(payload.created_time); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.duration = deserialize.integer(payload.duration); + this.connectDuration = deserialize.integer(payload.connect_duration); + this.from = (payload.from); + this.to = (payload.to); + this.carrierEdge = (payload.carrier_edge); + this.clientEdge = (payload.client_edge); + this.sdkEdge = (payload.sdk_edge); + this.sipEdge = (payload.sip_edge); + this.tags = (payload.tags); + this.url = (payload.url); + this.attributes = (payload.attributes); + this.properties = (payload.properties); + this.trust = (payload.trust); + this.annotation = (payload.annotation); + this.agentSessionSummaries = payload.agent_session_summaries !== null && payload.agent_session_summaries !== undefined ? payload.agent_session_summaries.map( + (payload: any) => new CallSummaryAgentSessionSummary(payload) + ) : null; + + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Call. + */ + callSid: string; + answeredBy: CallSummariesAnsweredBy; + callType: CallSummariesCallType; + callState: CallSummariesCallState; + processingState: CallSummariesProcessingState; + /** + * The time at which the Call was created, given in ISO 8601 format. Can be different from `start_time` in the event of queueing due to CPS + */ + createdTime: Date; + /** + * The time at which the Call was started, given in ISO 8601 format. + */ + startTime: Date; + /** + * The time at which the Call was ended, given in ISO 8601 format. + */ + endTime: Date; + /** + * Duration between when the call was initiated and the call was ended + */ + duration: number; + /** + * Duration between when the call was answered and when it ended + */ + connectDuration: number; + /** + * `object` The calling party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + */ + from: any; + /** + * `object` The called party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + */ + to: any; + /** + * `object` Contains metrics and properties for the Twilio media gateway of a PSTN call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + carrierEdge: any; + /** + * `object` Contains metrics and properties for the Twilio media gateway of a Client call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + clientEdge: any; + /** + * `object` Contains metrics and properties for the SDK sensor library for Client calls. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + sdkEdge: any; + /** + * `object` Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + */ + sipEdge: any; + /** + * Tags applied to calls by Voice Insights analysis indicating a condition that could result in subjective degradation of the call quality. + */ + tags: Array; + /** + * The URL of this resource. + */ + url: string; + /** + * `object` Attributes capturing call-flow-specific details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#attributes-object) for the object properties. + */ + attributes: any; + /** + * `object` Contains edge-agnostic call-level details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#properties-object) for the object properties. + */ + properties: any; + /** + * `object` Contains trusted communications details including Branded Call and verified caller ID. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#trust-object) for the object properties. + */ + trust: any; + /** + * `object` Programmatically labeled annotations for the Call. Developers can update the Call Summary records with Annotation during or after a Call. Annotations can be updated as long as the Call Summary record is addressable via the API. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#annotation-object) for the object properties. + */ + annotation: any; + /** + * `array[object]` List of agent session summaries for conversation relay. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#conversation-relay-object) for the object properties. + */ + agentSessionSummaries: Array; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + callSid: this.callSid, + answeredBy: this.answeredBy, + callType: this.callType, + callState: this.callState, + processingState: this.processingState, + createdTime: this.createdTime, + startTime: this.startTime, + endTime: this.endTime, + duration: this.duration, + connectDuration: this.connectDuration, + from: this.from, + to: this.to, + carrierEdge: this.carrierEdge, + clientEdge: this.clientEdge, + sdkEdge: this.sdkEdge, + sipEdge: this.sipEdge, + tags: this.tags, + url: this.url, + attributes: this.attributes, + properties: this.properties, + trust: this.trust, + annotation: this.annotation, + agentSessionSummaries: this.agentSessionSummaries, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class CallSummariesPage extends Page { +/** +* Initialize the CallSummariesPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: CallSummariesSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CallSummariesInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CallSummariesResource): CallSummariesInstance { + + return new CallSummariesInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/insights/v1/conference.ts b/rest/insights/v1/conference.ts new file mode 100644 index 000000000..dfd400987 --- /dev/null +++ b/rest/insights/v1/conference.ts @@ -0,0 +1,780 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ConferenceParticipantListInstance } from "./conference/conferenceParticipant"; + + +export type ConferenceConferenceEndReason = 'last_participant_left'|'conference_ended_via_api'|'participant_with_end_conference_on_exit_left'|'last_participant_kicked'|'participant_with_end_conference_on_exit_kicked'; + +export type ConferenceConferenceStatus = 'in_progress'|'not_started'|'completed'|'summary_timeout'; + +export type ConferenceProcessingState = 'complete'|'in_progress'|'timeout'; + +export type ConferenceRegion = 'us1'|'us2'|'au1'|'br1'|'ie1'|'jp1'|'sg1'|'de1'|'in1'; + +export type ConferenceTag = 'invalid_requested_region'|'duplicate_identity'|'start_failure'|'region_configuration_issues'|'quality_warnings'|'participant_behavior_issues'|'high_packet_loss'|'high_jitter'|'high_latency'|'low_mos'|'detected_silence'|'no_concurrent_participants'; + + + +/** + * Options to pass to each + */ +export interface ConferenceListInstanceEachOptions { + /** The SID of the conference. */ + "conferenceSid"?: string; + /** Custom label for the conference resource, up to 64 characters. */ + "friendlyName"?: string; + /** Conference status. */ + "status"?: string; + /** Conferences created after the provided timestamp specified in ISO 8601 format */ + "createdAfter"?: string; + /** Conferences created before the provided timestamp specified in ISO 8601 format. */ + "createdBefore"?: string; + /** Twilio region where the conference media was mixed. */ + "mixerRegion"?: string; + /** Tags applied by Twilio for common potential configuration, quality, or performance issues. */ + "tags"?: string; + /** Account SID for the subaccount whose resources you wish to retrieve. */ + "subaccount"?: string; + /** Potential configuration, behavior, or performance issues detected during the conference. */ + "detectedIssues"?: string; + /** Conference end reason; e.g. last participant left, modified by API, etc. */ + "endReason"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConferenceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConferenceListInstanceOptions { + /** The SID of the conference. */ + "conferenceSid"?: string; + /** Custom label for the conference resource, up to 64 characters. */ + "friendlyName"?: string; + /** Conference status. */ + "status"?: string; + /** Conferences created after the provided timestamp specified in ISO 8601 format */ + "createdAfter"?: string; + /** Conferences created before the provided timestamp specified in ISO 8601 format. */ + "createdBefore"?: string; + /** Twilio region where the conference media was mixed. */ + "mixerRegion"?: string; + /** Tags applied by Twilio for common potential configuration, quality, or performance issues. */ + "tags"?: string; + /** Account SID for the subaccount whose resources you wish to retrieve. */ + "subaccount"?: string; + /** Potential configuration, behavior, or performance issues detected during the conference. */ + "detectedIssues"?: string; + /** Conference end reason; e.g. last participant left, modified by API, etc. */ + "endReason"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConferenceListInstancePageOptions { + /** The SID of the conference. */ + "conferenceSid"?: string; + /** Custom label for the conference resource, up to 64 characters. */ + "friendlyName"?: string; + /** Conference status. */ + "status"?: string; + /** Conferences created after the provided timestamp specified in ISO 8601 format */ + "createdAfter"?: string; + /** Conferences created before the provided timestamp specified in ISO 8601 format. */ + "createdBefore"?: string; + /** Twilio region where the conference media was mixed. */ + "mixerRegion"?: string; + /** Tags applied by Twilio for common potential configuration, quality, or performance issues. */ + "tags"?: string; + /** Account SID for the subaccount whose resources you wish to retrieve. */ + "subaccount"?: string; + /** Potential configuration, behavior, or performance issues detected during the conference. */ + "detectedIssues"?: string; + /** Conference end reason; e.g. last participant left, modified by API, etc. */ + "endReason"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ConferenceContext { + conferenceParticipants: ConferenceParticipantListInstance; + + /** + * Fetch a ConferenceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance + */ + fetch(callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise + + /** + * Fetch a ConferenceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConferenceContextSolution { + "conferenceSid": string; +} + +export class ConferenceContextImpl implements ConferenceContext { + protected _solution: ConferenceContextSolution; + protected _uri: string; + + protected _conferenceParticipants?: ConferenceParticipantListInstance; + + constructor(protected _version: V1, conferenceSid: string) { + if (!isValidPathParam(conferenceSid)) { + throw new Error('Parameter \'conferenceSid\' is not valid.'); + } + + this._solution = { conferenceSid, }; + this._uri = `/Conferences/${conferenceSid}`; + } + + get conferenceParticipants(): ConferenceParticipantListInstance { + this._conferenceParticipants = this._conferenceParticipants || ConferenceParticipantListInstance(this._version, this._solution.conferenceSid); + return this._conferenceParticipants; + } + + fetch(callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConferenceInstance(operationVersion, payload, instance._solution.conferenceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConferenceInstance(operationVersion, response.body, instance._solution.conferenceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConferencePayload extends TwilioResponsePayload { + conferences: ConferenceResource[]; +} + +interface ConferenceResource { + conference_sid: string; + account_sid: string; + friendly_name: string; + create_time: Date; + start_time: Date; + end_time: Date; + duration_seconds: number; + connect_duration_seconds: number; + status: ConferenceConferenceStatus; + max_participants: number; + max_concurrent_participants: number; + unique_participants: number; + end_reason: ConferenceConferenceEndReason; + ended_by: string; + mixer_region: ConferenceRegion; + mixer_region_requested: ConferenceRegion; + recording_enabled: boolean; + detected_issues: any; + tags: Array; + tag_info: any; + processing_state: ConferenceProcessingState; + url: string; + links: Record; +} + +export class ConferenceInstance { + protected _solution: ConferenceContextSolution; + protected _context?: ConferenceContext; + + constructor(protected _version: V1, payload: ConferenceResource, conferenceSid?: string) { + + this.conferenceSid = (payload.conference_sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.createTime = deserialize.iso8601DateTime(payload.create_time); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.durationSeconds = deserialize.integer(payload.duration_seconds); + this.connectDurationSeconds = deserialize.integer(payload.connect_duration_seconds); + this.status = payload.status; + this.maxParticipants = deserialize.integer(payload.max_participants); + this.maxConcurrentParticipants = deserialize.integer(payload.max_concurrent_participants); + this.uniqueParticipants = deserialize.integer(payload.unique_participants); + this.endReason = payload.end_reason; + this.endedBy = (payload.ended_by); + this.mixerRegion = payload.mixer_region; + this.mixerRegionRequested = payload.mixer_region_requested; + this.recordingEnabled = (payload.recording_enabled); + this.detectedIssues = (payload.detected_issues); + this.tags = (payload.tags); + this.tagInfo = (payload.tag_info); + this.processingState = payload.processing_state; + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { conferenceSid: conferenceSid, }; + } + + /** + * The unique SID identifier of the Conference. + */ + conferenceSid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * Custom label for the conference resource, up to 64 characters. + */ + friendlyName: string; + /** + * Conference creation date and time in ISO 8601 format. + */ + createTime: Date; + /** + * Timestamp in ISO 8601 format when the conference started. Conferences do not start until at least two participants join, at least one of whom has startConferenceOnEnter=true. + */ + startTime: Date; + /** + * Conference end date and time in ISO 8601 format. + */ + endTime: Date; + /** + * Conference duration in seconds. + */ + durationSeconds: number; + /** + * Duration of the between conference start event and conference end event in seconds. + */ + connectDurationSeconds: number; + status: ConferenceConferenceStatus; + /** + * Maximum number of concurrent participants as specified by the configuration. + */ + maxParticipants: number; + /** + * Actual maximum number of concurrent participants in the conference. + */ + maxConcurrentParticipants: number; + /** + * Unique conference participants based on caller ID. + */ + uniqueParticipants: number; + endReason: ConferenceConferenceEndReason; + /** + * Call SID of the participant whose actions ended the conference. + */ + endedBy: string; + mixerRegion: ConferenceRegion; + mixerRegionRequested: ConferenceRegion; + /** + * Boolean. Indicates whether recording was enabled at the conference mixer. + */ + recordingEnabled: boolean; + /** + * Potential issues detected by Twilio during the conference. + */ + detectedIssues: any; + /** + * Tags for detected conference conditions and participant behaviors which may be of interest. + */ + tags: Array; + /** + * Object. Contains details about conference tags including severity. + */ + tagInfo: any; + processingState: ConferenceProcessingState; + /** + * The URL of this resource. + */ + url: string; + /** + * Contains a dictionary of URL links to nested resources of this Conference. + */ + links: Record; + + private get _proxy(): ConferenceContext { + this._context = this._context || new ConferenceContextImpl(this._version, this._solution.conferenceSid); + return this._context; + } + + /** + * Fetch a ConferenceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance + */ + fetch(callback?: (error: Error | null, item?: ConferenceInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConferenceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the conferenceParticipants. + */ + conferenceParticipants(): ConferenceParticipantListInstance { + return this._proxy.conferenceParticipants; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + conferenceSid: this.conferenceSid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + createTime: this.createTime, + startTime: this.startTime, + endTime: this.endTime, + durationSeconds: this.durationSeconds, + connectDurationSeconds: this.connectDurationSeconds, + status: this.status, + maxParticipants: this.maxParticipants, + maxConcurrentParticipants: this.maxConcurrentParticipants, + uniqueParticipants: this.uniqueParticipants, + endReason: this.endReason, + endedBy: this.endedBy, + mixerRegion: this.mixerRegion, + mixerRegionRequested: this.mixerRegionRequested, + recordingEnabled: this.recordingEnabled, + detectedIssues: this.detectedIssues, + tags: this.tags, + tagInfo: this.tagInfo, + processingState: this.processingState, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConferenceSolution { +} + +export interface ConferenceListInstance { + _version: V1; + _solution: ConferenceSolution; + _uri: string; + + (conferenceSid: string, ): ConferenceContext; + get(conferenceSid: string, ): ConferenceContext; + + + + + + /** + * Streams ConferenceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConferenceInstance, done: (err?: Error) => void) => void): void; + each(params: ConferenceListInstanceEachOptions, callback?: (item: ConferenceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConferenceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConferenceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConferenceListInstanceEachOptions, callback?: (item: ConferenceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConferenceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConferencePage) => any): Promise; + /** + * Retrieve a single target page of ConferenceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConferenceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConferenceInstance[]) => any): Promise; + list(params: ConferenceListInstanceOptions, callback?: (error: Error | null, items: ConferenceInstance[]) => any): Promise; + /** + * Lists ConferenceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConferenceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConferenceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConferencePage) => any): Promise; + page(params: ConferenceListInstancePageOptions, callback?: (error: Error | null, items: ConferencePage) => any): Promise; + /** + * Retrieve a single page of ConferenceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConferenceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConferenceListInstance(version: V1): ConferenceListInstance { + const instance = ((conferenceSid, ) => instance.get(conferenceSid, )) as ConferenceListInstance; + + instance.get = function get(conferenceSid, ): ConferenceContext { + return new ConferenceContextImpl(version, conferenceSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Conferences`; + + instance.page = function page(params?: ConferenceListInstancePageOptions | ((error: Error | null, items: ConferencePage) => any), callback?: (error: Error | null, items: ConferencePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["conferenceSid"] !== undefined) + data["ConferenceSid"] = params["conferenceSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["createdAfter"] !== undefined) + data["CreatedAfter"] = params["createdAfter"]; + if (params["createdBefore"] !== undefined) + data["CreatedBefore"] = params["createdBefore"]; + if (params["mixerRegion"] !== undefined) + data["MixerRegion"] = params["mixerRegion"]; + if (params["tags"] !== undefined) + data["Tags"] = params["tags"]; + if (params["subaccount"] !== undefined) + data["Subaccount"] = params["subaccount"]; + if (params["detectedIssues"] !== undefined) + data["DetectedIssues"] = params["detectedIssues"]; + if (params["endReason"] !== undefined) + data["EndReason"] = params["endReason"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConferencePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConferencePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConferencePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConferenceListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["conferenceSid"] !== undefined) + data["ConferenceSid"] = params["conferenceSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["createdAfter"] !== undefined) + data["CreatedAfter"] = params["createdAfter"]; + if (params["createdBefore"] !== undefined) + data["CreatedBefore"] = params["createdBefore"]; + if (params["mixerRegion"] !== undefined) + data["MixerRegion"] = params["mixerRegion"]; + if (params["tags"] !== undefined) + data["Tags"] = params["tags"]; + if (params["subaccount"] !== undefined) + data["Subaccount"] = params["subaccount"]; + if (params["detectedIssues"] !== undefined) + data["DetectedIssues"] = params["detectedIssues"]; + if (params["endReason"] !== undefined) + data["EndReason"] = params["endReason"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConferencePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConferencePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConferencePage extends Page { +/** +* Initialize the ConferencePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ConferenceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ConferenceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConferenceResource): ConferenceInstance { + + return new ConferenceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/insights/v1/conference/conferenceParticipant.ts b/rest/insights/v1/conference/conferenceParticipant.ts new file mode 100644 index 000000000..a71b63889 --- /dev/null +++ b/rest/insights/v1/conference/conferenceParticipant.ts @@ -0,0 +1,813 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export type ConferenceParticipantCallDirection = 'inbound'|'outbound'; + +export type ConferenceParticipantCallStatus = 'answered'|'completed'|'busy'|'fail'|'noanswer'|'ringing'|'canceled'; + +export type ConferenceParticipantCallType = 'carrier'|'client'|'sip'; + +export type ConferenceParticipantJitterBufferSize = 'large'|'small'|'medium'|'off'; + +export type ConferenceParticipantProcessingState = 'complete'|'in_progress'|'timeout'; + +export type ConferenceParticipantRegion = 'us1'|'us2'|'au1'|'br1'|'ie1'|'jp1'|'sg1'|'de1'|'in1'; + + +/** + * Options to pass to fetch a ConferenceParticipantInstance + */ +export interface ConferenceParticipantContextFetchOptions { + /** Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. */ + "events"?: string; + /** Object. Contains participant call quality metrics. */ + "metrics"?: string; +} + +/** + * Options to pass to each + */ +export interface ConferenceParticipantListInstanceEachOptions { + /** The unique SID identifier of the Participant. */ + "participantSid"?: string; + /** User-specified label for a participant. */ + "label"?: string; + /** Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. */ + "events"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConferenceParticipantInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConferenceParticipantListInstanceOptions { + /** The unique SID identifier of the Participant. */ + "participantSid"?: string; + /** User-specified label for a participant. */ + "label"?: string; + /** Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. */ + "events"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConferenceParticipantListInstancePageOptions { + /** The unique SID identifier of the Participant. */ + "participantSid"?: string; + /** User-specified label for a participant. */ + "label"?: string; + /** Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. */ + "events"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ConferenceParticipantContext { + + /** + * Fetch a ConferenceParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ConferenceParticipantInstance) => any): Promise; + /** + * Fetch a ConferenceParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceParticipantInstance + */ + fetch(params: ConferenceParticipantContextFetchOptions, callback?: (error: Error | null, item?: ConferenceParticipantInstance) => any): Promise; + + /** + * Fetch a ConferenceParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a ConferenceParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(params: ConferenceParticipantContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConferenceParticipantContextSolution { + "conferenceSid": string; + "participantSid": string; +} + +export class ConferenceParticipantContextImpl implements ConferenceParticipantContext { + protected _solution: ConferenceParticipantContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, conferenceSid: string, participantSid: string) { + if (!isValidPathParam(conferenceSid)) { + throw new Error('Parameter \'conferenceSid\' is not valid.'); + } + + if (!isValidPathParam(participantSid)) { + throw new Error('Parameter \'participantSid\' is not valid.'); + } + + this._solution = { conferenceSid, participantSid, }; + this._uri = `/Conferences/${conferenceSid}/Participants/${participantSid}`; + } + + fetch(params?: ConferenceParticipantContextFetchOptions | ((error: Error | null, item?: ConferenceParticipantInstance) => any),callback?: (error: Error | null, item?: ConferenceParticipantInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["events"] !== undefined) + data["Events"] = params["events"]; + if (params["metrics"] !== undefined) + data["Metrics"] = params["metrics"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new ConferenceParticipantInstance(operationVersion, payload, instance._solution.conferenceSid, instance._solution.participantSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: ConferenceParticipantContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["events"] !== undefined) + data["Events"] = params["events"]; + if (params["metrics"] !== undefined) + data["Metrics"] = params["metrics"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConferenceParticipantInstance(operationVersion, response.body, instance._solution.conferenceSid, instance._solution.participantSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConferenceParticipantPayload extends TwilioResponsePayload { + participants: ConferenceParticipantResource[]; +} + +interface ConferenceParticipantResource { + participant_sid: string; + label: string; + conference_sid: string; + call_sid: string; + account_sid: string; + call_direction: ConferenceParticipantCallDirection; + from: string; + to: string; + call_status: ConferenceParticipantCallStatus; + country_code: string; + is_moderator: boolean; + join_time: Date; + leave_time: Date; + duration_seconds: number; + outbound_queue_length: number; + outbound_time_in_queue: number; + jitter_buffer_size: ConferenceParticipantJitterBufferSize; + is_coach: boolean; + coached_participants: Array; + participant_region: ConferenceParticipantRegion; + conference_region: ConferenceParticipantRegion; + call_type: ConferenceParticipantCallType; + processing_state: ConferenceParticipantProcessingState; + properties: any; + events: any; + metrics: any; + url: string; +} + +export class ConferenceParticipantInstance { + protected _solution: ConferenceParticipantContextSolution; + protected _context?: ConferenceParticipantContext; + + constructor(protected _version: V1, payload: ConferenceParticipantResource, conferenceSid: string, participantSid?: string) { + + this.participantSid = (payload.participant_sid); + this.label = (payload.label); + this.conferenceSid = (payload.conference_sid); + this.callSid = (payload.call_sid); + this.accountSid = (payload.account_sid); + this.callDirection = payload.call_direction; + this.from = (payload.from); + this.to = (payload.to); + this.callStatus = payload.call_status; + this.countryCode = (payload.country_code); + this.isModerator = (payload.is_moderator); + this.joinTime = deserialize.iso8601DateTime(payload.join_time); + this.leaveTime = deserialize.iso8601DateTime(payload.leave_time); + this.durationSeconds = deserialize.integer(payload.duration_seconds); + this.outboundQueueLength = deserialize.integer(payload.outbound_queue_length); + this.outboundTimeInQueue = deserialize.integer(payload.outbound_time_in_queue); + this.jitterBufferSize = payload.jitter_buffer_size; + this.isCoach = (payload.is_coach); + this.coachedParticipants = (payload.coached_participants); + this.participantRegion = payload.participant_region; + this.conferenceRegion = payload.conference_region; + this.callType = payload.call_type; + this.processingState = payload.processing_state; + this.properties = (payload.properties); + this.events = (payload.events); + this.metrics = (payload.metrics); + this.url = (payload.url); + + this._solution = { conferenceSid, participantSid: participantSid, }; + } + + /** + * SID for this participant. + */ + participantSid: string; + /** + * The user-specified label of this participant. + */ + label: string; + /** + * The unique SID identifier of the Conference. + */ + conferenceSid: string; + /** + * Unique SID identifier of the call that generated the Participant resource. + */ + callSid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + callDirection: ConferenceParticipantCallDirection; + /** + * Caller ID of the calling party. + */ + from: string; + /** + * Called party. + */ + to: string; + callStatus: ConferenceParticipantCallStatus; + /** + * ISO alpha-2 country code of the participant based on caller ID or called number. + */ + countryCode: string; + /** + * Boolean. Indicates whether participant had startConferenceOnEnter=true or endConferenceOnExit=true. + */ + isModerator: boolean; + /** + * ISO 8601 timestamp of participant join event. + */ + joinTime: Date; + /** + * ISO 8601 timestamp of participant leave event. + */ + leaveTime: Date; + /** + * Participant durations in seconds. + */ + durationSeconds: number; + /** + * Add Participant API only. Estimated time in queue at call creation. + */ + outboundQueueLength: number; + /** + * Add Participant API only. Actual time in queue in seconds. + */ + outboundTimeInQueue: number; + jitterBufferSize: ConferenceParticipantJitterBufferSize; + /** + * Boolean. Indicated whether participant was a coach. + */ + isCoach: boolean; + /** + * Call SIDs coached by this participant. + */ + coachedParticipants: Array; + participantRegion: ConferenceParticipantRegion; + conferenceRegion: ConferenceParticipantRegion; + callType: ConferenceParticipantCallType; + processingState: ConferenceParticipantProcessingState; + /** + * Participant properties and metadata. + */ + properties: any; + /** + * Object containing information of actions taken by participants. Contains a dictionary of URL links to nested resources of this Conference Participant. + */ + events: any; + /** + * Object. Contains participant call quality metrics. + */ + metrics: any; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): ConferenceParticipantContext { + this._context = this._context || new ConferenceParticipantContextImpl(this._version, this._solution.conferenceSid, this._solution.participantSid); + return this._context; + } + + /** + * Fetch a ConferenceParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ConferenceParticipantInstance) => any): Promise; + /** + * Fetch a ConferenceParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceParticipantInstance + */ + fetch(params: ConferenceParticipantContextFetchOptions, callback?: (error: Error | null, item?: ConferenceParticipantInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: ConferenceParticipantInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a ConferenceParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a ConferenceParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConferenceParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(params: ConferenceParticipantContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + participantSid: this.participantSid, + label: this.label, + conferenceSid: this.conferenceSid, + callSid: this.callSid, + accountSid: this.accountSid, + callDirection: this.callDirection, + from: this.from, + to: this.to, + callStatus: this.callStatus, + countryCode: this.countryCode, + isModerator: this.isModerator, + joinTime: this.joinTime, + leaveTime: this.leaveTime, + durationSeconds: this.durationSeconds, + outboundQueueLength: this.outboundQueueLength, + outboundTimeInQueue: this.outboundTimeInQueue, + jitterBufferSize: this.jitterBufferSize, + isCoach: this.isCoach, + coachedParticipants: this.coachedParticipants, + participantRegion: this.participantRegion, + conferenceRegion: this.conferenceRegion, + callType: this.callType, + processingState: this.processingState, + properties: this.properties, + events: this.events, + metrics: this.metrics, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConferenceParticipantSolution { + conferenceSid: string; +} + +export interface ConferenceParticipantListInstance { + _version: V1; + _solution: ConferenceParticipantSolution; + _uri: string; + + (participantSid: string, ): ConferenceParticipantContext; + get(participantSid: string, ): ConferenceParticipantContext; + + + + + + /** + * Streams ConferenceParticipantInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConferenceParticipantInstance, done: (err?: Error) => void) => void): void; + each(params: ConferenceParticipantListInstanceEachOptions, callback?: (item: ConferenceParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConferenceParticipantInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConferenceParticipantInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConferenceParticipantListInstanceEachOptions, callback?: (item: ConferenceParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConferenceParticipantInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConferenceParticipantPage) => any): Promise; + /** + * Retrieve a single target page of ConferenceParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConferenceParticipantInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConferenceParticipantInstance[]) => any): Promise; + list(params: ConferenceParticipantListInstanceOptions, callback?: (error: Error | null, items: ConferenceParticipantInstance[]) => any): Promise; + /** + * Lists ConferenceParticipantInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConferenceParticipantListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConferenceParticipantInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConferenceParticipantPage) => any): Promise; + page(params: ConferenceParticipantListInstancePageOptions, callback?: (error: Error | null, items: ConferenceParticipantPage) => any): Promise; + /** + * Retrieve a single page of ConferenceParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConferenceParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConferenceParticipantListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConferenceParticipantListInstance(version: V1, conferenceSid: string): ConferenceParticipantListInstance { + if (!isValidPathParam(conferenceSid)) { + throw new Error('Parameter \'conferenceSid\' is not valid.'); + } + + const instance = ((participantSid, ) => instance.get(participantSid, )) as ConferenceParticipantListInstance; + + instance.get = function get(participantSid, ): ConferenceParticipantContext { + return new ConferenceParticipantContextImpl(version, conferenceSid, participantSid); + } + + instance._version = version; + instance._solution = { conferenceSid, }; + instance._uri = `/Conferences/${conferenceSid}/Participants`; + + instance.page = function page(params?: ConferenceParticipantListInstancePageOptions | ((error: Error | null, items: ConferenceParticipantPage) => any), callback?: (error: Error | null, items: ConferenceParticipantPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["participantSid"] !== undefined) + data["ParticipantSid"] = params["participantSid"]; + if (params["label"] !== undefined) + data["Label"] = params["label"]; + if (params["events"] !== undefined) + data["Events"] = params["events"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConferenceParticipantPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConferenceParticipantPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConferenceParticipantPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConferenceParticipantListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["participantSid"] !== undefined) + data["ParticipantSid"] = params["participantSid"]; + if (params["label"] !== undefined) + data["Label"] = params["label"]; + if (params["events"] !== undefined) + data["Events"] = params["events"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConferenceParticipantPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConferenceParticipantPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConferenceParticipantPage extends Page { +/** +* Initialize the ConferenceParticipantPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ConferenceParticipantSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ConferenceParticipantInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConferenceParticipantResource): ConferenceParticipantInstance { + + return new ConferenceParticipantInstance( + this._version, + payload, + this._solution.conferenceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/insights/v1/room.ts b/rest/insights/v1/room.ts new file mode 100644 index 000000000..0a55b93e0 --- /dev/null +++ b/rest/insights/v1/room.ts @@ -0,0 +1,751 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ParticipantListInstance } from "./room/participant"; + + +export type RoomCodec = 'VP8'|'H264'|'VP9'|'opus'; + +export type RoomCreatedMethod = 'sdk'|'ad_hoc'|'api'; + +export type RoomEdgeLocation = 'ashburn'|'dublin'|'frankfurt'|'singapore'|'sydney'|'sao_paulo'|'roaming'|'umatilla'|'tokyo'; + +export type RoomEndReason = 'room_ended_via_api'|'timeout'; + +export type RoomProcessingState = 'complete'|'in_progress'|'timeout'|'not_started'; + +export type RoomRoomStatus = 'in_progress'|'completed'; + +export type RoomRoomType = 'go'|'peer_to_peer'|'group'|'group_small'; + +export type RoomTwilioRealm = 'us1'|'us2'|'au1'|'br1'|'ie1'|'jp1'|'sg1'|'in1'|'de1'|'gll'; + + + +/** + * Options to pass to each + */ +export interface RoomListInstanceEachOptions { + /** Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. */ + "roomType"?: Array; + /** Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. */ + "codec"?: Array; + /** Room friendly name. */ + "roomName"?: string; + /** Only read rooms that started on or after this ISO 8601 timestamp. */ + "createdAfter"?: Date; + /** Only read rooms that started before this ISO 8601 timestamp. */ + "createdBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoomInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoomListInstanceOptions { + /** Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. */ + "roomType"?: Array; + /** Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. */ + "codec"?: Array; + /** Room friendly name. */ + "roomName"?: string; + /** Only read rooms that started on or after this ISO 8601 timestamp. */ + "createdAfter"?: Date; + /** Only read rooms that started before this ISO 8601 timestamp. */ + "createdBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoomListInstancePageOptions { + /** Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. */ + "roomType"?: Array; + /** Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. */ + "codec"?: Array; + /** Room friendly name. */ + "roomName"?: string; + /** Only read rooms that started on or after this ISO 8601 timestamp. */ + "createdAfter"?: Date; + /** Only read rooms that started before this ISO 8601 timestamp. */ + "createdBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoomContext { + participants: ParticipantListInstance; + + /** + * Fetch a RoomInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance + */ + fetch(callback?: (error: Error | null, item?: RoomInstance) => any): Promise + + /** + * Fetch a RoomInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoomContextSolution { + "roomSid": string; +} + +export class RoomContextImpl implements RoomContext { + protected _solution: RoomContextSolution; + protected _uri: string; + + protected _participants?: ParticipantListInstance; + + constructor(protected _version: V1, roomSid: string) { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + this._solution = { roomSid, }; + this._uri = `/Video/Rooms/${roomSid}`; + } + + get participants(): ParticipantListInstance { + this._participants = this._participants || ParticipantListInstance(this._version, this._solution.roomSid); + return this._participants; + } + + fetch(callback?: (error: Error | null, item?: RoomInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RoomInstance(operationVersion, payload, instance._solution.roomSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoomInstance(operationVersion, response.body, instance._solution.roomSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RoomPayload extends TwilioResponsePayload { + rooms: RoomResource[]; +} + +interface RoomResource { + account_sid: string; + room_sid: string; + room_name: string; + create_time: Date; + end_time: Date; + room_type: RoomRoomType; + room_status: RoomRoomStatus; + status_callback: string; + status_callback_method: string; + created_method: RoomCreatedMethod; + end_reason: RoomEndReason; + max_participants: number; + unique_participants: number; + unique_participant_identities: number; + concurrent_participants: number; + max_concurrent_participants: number; + codecs: Array; + media_region: RoomTwilioRealm; + duration_sec: number; + total_participant_duration_sec: number; + total_recording_duration_sec: number; + processing_state: RoomProcessingState; + recording_enabled: boolean; + edge_location: RoomEdgeLocation; + url: string; + links: Record; +} + +export class RoomInstance { + protected _solution: RoomContextSolution; + protected _context?: RoomContext; + + constructor(protected _version: V1, payload: RoomResource, roomSid?: string) { + + this.accountSid = (payload.account_sid); + this.roomSid = (payload.room_sid); + this.roomName = (payload.room_name); + this.createTime = deserialize.iso8601DateTime(payload.create_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.roomType = payload.room_type; + this.roomStatus = payload.room_status; + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.createdMethod = payload.created_method; + this.endReason = payload.end_reason; + this.maxParticipants = deserialize.integer(payload.max_participants); + this.uniqueParticipants = deserialize.integer(payload.unique_participants); + this.uniqueParticipantIdentities = deserialize.integer(payload.unique_participant_identities); + this.concurrentParticipants = deserialize.integer(payload.concurrent_participants); + this.maxConcurrentParticipants = deserialize.integer(payload.max_concurrent_participants); + this.codecs = (payload.codecs); + this.mediaRegion = payload.media_region; + this.durationSec = (payload.duration_sec); + this.totalParticipantDurationSec = (payload.total_participant_duration_sec); + this.totalRecordingDurationSec = (payload.total_recording_duration_sec); + this.processingState = payload.processing_state; + this.recordingEnabled = (payload.recording_enabled); + this.edgeLocation = payload.edge_location; + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { roomSid: roomSid, }; + } + + /** + * Account SID associated with this room. + */ + accountSid: string; + /** + * Unique identifier for the room. + */ + roomSid: string; + /** + * Room friendly name. + */ + roomName: string; + /** + * Creation time of the room. + */ + createTime: Date; + /** + * End time for the room. + */ + endTime: Date; + roomType: RoomRoomType; + roomStatus: RoomRoomStatus; + /** + * Webhook provided for status callbacks. + */ + statusCallback: string; + /** + * HTTP method provided for status callback URL. + */ + statusCallbackMethod: string; + createdMethod: RoomCreatedMethod; + endReason: RoomEndReason; + /** + * Max number of total participants allowed by the application settings. + */ + maxParticipants: number; + /** + * Number of participants. May include duplicate identities for participants who left and rejoined. + */ + uniqueParticipants: number; + /** + * Unique number of participant identities. + */ + uniqueParticipantIdentities: number; + /** + * Actual number of concurrent participants. + */ + concurrentParticipants: number; + /** + * Maximum number of participants allowed in the room at the same time allowed by the application settings. + */ + maxConcurrentParticipants: number; + /** + * Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + */ + codecs: Array; + mediaRegion: RoomTwilioRealm; + /** + * Total room duration from create time to end time. + */ + durationSec: number; + /** + * Combined amount of participant time in the room. + */ + totalParticipantDurationSec: number; + /** + * Combined amount of recorded seconds for participants in the room. + */ + totalRecordingDurationSec: number; + processingState: RoomProcessingState; + /** + * Boolean indicating if recording is enabled for the room. + */ + recordingEnabled: boolean; + edgeLocation: RoomEdgeLocation; + /** + * URL for the room resource. + */ + url: string; + /** + * Room subresources. + */ + links: Record; + + private get _proxy(): RoomContext { + this._context = this._context || new RoomContextImpl(this._version, this._solution.roomSid); + return this._context; + } + + /** + * Fetch a RoomInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance + */ + fetch(callback?: (error: Error | null, item?: RoomInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RoomInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the participants. + */ + participants(): ParticipantListInstance { + return this._proxy.participants; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + roomSid: this.roomSid, + roomName: this.roomName, + createTime: this.createTime, + endTime: this.endTime, + roomType: this.roomType, + roomStatus: this.roomStatus, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + createdMethod: this.createdMethod, + endReason: this.endReason, + maxParticipants: this.maxParticipants, + uniqueParticipants: this.uniqueParticipants, + uniqueParticipantIdentities: this.uniqueParticipantIdentities, + concurrentParticipants: this.concurrentParticipants, + maxConcurrentParticipants: this.maxConcurrentParticipants, + codecs: this.codecs, + mediaRegion: this.mediaRegion, + durationSec: this.durationSec, + totalParticipantDurationSec: this.totalParticipantDurationSec, + totalRecordingDurationSec: this.totalRecordingDurationSec, + processingState: this.processingState, + recordingEnabled: this.recordingEnabled, + edgeLocation: this.edgeLocation, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoomSolution { +} + +export interface RoomListInstance { + _version: V1; + _solution: RoomSolution; + _uri: string; + + (roomSid: string, ): RoomContext; + get(roomSid: string, ): RoomContext; + + + + + + /** + * Streams RoomInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoomInstance, done: (err?: Error) => void) => void): void; + each(params: RoomListInstanceEachOptions, callback?: (item: RoomInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoomInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoomInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoomListInstanceEachOptions, callback?: (item: RoomInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoomInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RoomPage) => any): Promise; + /** + * Retrieve a single target page of RoomInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RoomInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoomInstance[]) => any): Promise; + list(params: RoomListInstanceOptions, callback?: (error: Error | null, items: RoomInstance[]) => any): Promise; + /** + * Lists RoomInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RoomListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RoomInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RoomPage) => any): Promise; + page(params: RoomListInstancePageOptions, callback?: (error: Error | null, items: RoomPage) => any): Promise; + /** + * Retrieve a single page of RoomInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RoomListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoomListInstance(version: V1): RoomListInstance { + const instance = ((roomSid, ) => instance.get(roomSid, )) as RoomListInstance; + + instance.get = function get(roomSid, ): RoomContext { + return new RoomContextImpl(version, roomSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Video/Rooms`; + + instance.page = function page(params?: RoomListInstancePageOptions | ((error: Error | null, items: RoomPage) => any), callback?: (error: Error | null, items: RoomPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["roomType"] !== undefined) + data["RoomType"] = serialize.map(params["roomType"], (e: RoomRoomType) => (e)); + if (params["codec"] !== undefined) + data["Codec"] = serialize.map(params["codec"], (e: RoomCodec) => (e)); + if (params["roomName"] !== undefined) + data["RoomName"] = params["roomName"]; + if (params["createdAfter"] !== undefined) + data["CreatedAfter"] = serialize.iso8601DateTime(params["createdAfter"]); + if (params["createdBefore"] !== undefined) + data["CreatedBefore"] = serialize.iso8601DateTime(params["createdBefore"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RoomPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RoomPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RoomPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoomListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["roomType"] !== undefined) + data["RoomType"] = serialize.map(params["roomType"], (e: RoomRoomType) => (e)); + if (params["codec"] !== undefined) + data["Codec"] = serialize.map(params["codec"], (e: RoomCodec) => (e)); + if (params["roomName"] !== undefined) + data["RoomName"] = params["roomName"]; + if (params["createdAfter"] !== undefined) + data["CreatedAfter"] = serialize.iso8601DateTime(params["createdAfter"]); + if (params["createdBefore"] !== undefined) + data["CreatedBefore"] = serialize.iso8601DateTime(params["createdBefore"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RoomPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RoomPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RoomPage extends Page { +/** +* Initialize the RoomPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: RoomSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoomInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoomResource): RoomInstance { + + return new RoomInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/insights/v1/room/participant.ts b/rest/insights/v1/room/participant.ts new file mode 100644 index 000000000..e1cd925a7 --- /dev/null +++ b/rest/insights/v1/room/participant.ts @@ -0,0 +1,638 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export type ParticipantCodec = 'VP8'|'H264'|'VP9'|'opus'; + +export type ParticipantEdgeLocation = 'ashburn'|'dublin'|'frankfurt'|'singapore'|'sydney'|'sao_paulo'|'roaming'|'umatilla'|'tokyo'; + +export type ParticipantRoomStatus = 'in_progress'|'connected'|'completed'|'disconnected'; + +export type ParticipantTwilioRealm = 'us1'|'us2'|'au1'|'br1'|'ie1'|'jp1'|'sg1'|'in1'|'de1'|'gll'; + + + +/** + * Options to pass to each + */ +export interface ParticipantListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ParticipantListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ParticipantListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ParticipantContext { + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ParticipantContextSolution { + "roomSid": string; + "participantSid": string; +} + +export class ParticipantContextImpl implements ParticipantContext { + protected _solution: ParticipantContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, roomSid: string, participantSid: string) { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(participantSid)) { + throw new Error('Parameter \'participantSid\' is not valid.'); + } + + this._solution = { roomSid, participantSid, }; + this._uri = `/Video/Rooms/${roomSid}/Participants/${participantSid}`; + } + + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.participantSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.participantSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ParticipantPayload extends TwilioResponsePayload { + participants: ParticipantResource[]; +} + +interface ParticipantResource { + participant_sid: string; + participant_identity: string; + join_time: Date; + leave_time: Date; + duration_sec: number; + account_sid: string; + room_sid: string; + status: ParticipantRoomStatus; + codecs: Array; + end_reason: string; + error_code: number; + error_code_url: string; + media_region: ParticipantTwilioRealm; + properties: any; + edge_location: ParticipantEdgeLocation; + publisher_info: any; + url: string; +} + +export class ParticipantInstance { + protected _solution: ParticipantContextSolution; + protected _context?: ParticipantContext; + + constructor(protected _version: V1, payload: ParticipantResource, roomSid: string, participantSid?: string) { + + this.participantSid = (payload.participant_sid); + this.participantIdentity = (payload.participant_identity); + this.joinTime = deserialize.iso8601DateTime(payload.join_time); + this.leaveTime = deserialize.iso8601DateTime(payload.leave_time); + this.durationSec = (payload.duration_sec); + this.accountSid = (payload.account_sid); + this.roomSid = (payload.room_sid); + this.status = payload.status; + this.codecs = (payload.codecs); + this.endReason = (payload.end_reason); + this.errorCode = deserialize.integer(payload.error_code); + this.errorCodeUrl = (payload.error_code_url); + this.mediaRegion = payload.media_region; + this.properties = (payload.properties); + this.edgeLocation = payload.edge_location; + this.publisherInfo = (payload.publisher_info); + this.url = (payload.url); + + this._solution = { roomSid, participantSid: participantSid, }; + } + + /** + * Unique identifier for the participant. + */ + participantSid: string; + /** + * The application-defined string that uniquely identifies the participant within a Room. + */ + participantIdentity: string; + /** + * When the participant joined the room. + */ + joinTime: Date; + /** + * When the participant left the room. + */ + leaveTime: Date; + /** + * Amount of time in seconds the participant was in the room. + */ + durationSec: number; + /** + * Account SID associated with the room. + */ + accountSid: string; + /** + * Unique identifier for the room. + */ + roomSid: string; + status: ParticipantRoomStatus; + /** + * Codecs detected from the participant. Can be `VP8`, `H264`, or `VP9`. + */ + codecs: Array; + /** + * Reason the participant left the room. See [the list of possible values here](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#end_reason). + */ + endReason: string; + /** + * Errors encountered by the participant. + */ + errorCode: number; + /** + * Twilio error code dictionary link. + */ + errorCodeUrl: string; + mediaRegion: ParticipantTwilioRealm; + /** + * Object containing information about the participant\'s data from the room. See [below](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#properties) for more information. + */ + properties: any; + edgeLocation: ParticipantEdgeLocation; + /** + * Object containing information about the SDK name and version. See [below](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#publisher_info) for more information. + */ + publisherInfo: any; + /** + * URL of the participant resource. + */ + url: string; + + private get _proxy(): ParticipantContext { + this._context = this._context || new ParticipantContextImpl(this._version, this._solution.roomSid, this._solution.participantSid); + return this._context; + } + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + participantSid: this.participantSid, + participantIdentity: this.participantIdentity, + joinTime: this.joinTime, + leaveTime: this.leaveTime, + durationSec: this.durationSec, + accountSid: this.accountSid, + roomSid: this.roomSid, + status: this.status, + codecs: this.codecs, + endReason: this.endReason, + errorCode: this.errorCode, + errorCodeUrl: this.errorCodeUrl, + mediaRegion: this.mediaRegion, + properties: this.properties, + edgeLocation: this.edgeLocation, + publisherInfo: this.publisherInfo, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ParticipantSolution { + roomSid: string; +} + +export interface ParticipantListInstance { + _version: V1; + _solution: ParticipantSolution; + _uri: string; + + (participantSid: string, ): ParticipantContext; + get(participantSid: string, ): ParticipantContext; + + + + + + /** + * Streams ParticipantInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + each(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ParticipantInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + /** + * Retrieve a single target page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ParticipantInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise; + list(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise; + /** + * Lists ParticipantInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + page(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ParticipantPage) => any): Promise; + /** + * Retrieve a single page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ParticipantListInstance(version: V1, roomSid: string): ParticipantListInstance { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + const instance = ((participantSid, ) => instance.get(participantSid, )) as ParticipantListInstance; + + instance.get = function get(participantSid, ): ParticipantContext { + return new ParticipantContextImpl(version, roomSid, participantSid); + } + + instance._version = version; + instance._solution = { roomSid, }; + instance._uri = `/Video/Rooms/${roomSid}/Participants`; + + instance.page = function page(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ParticipantPage) => any), callback?: (error: Error | null, items: ParticipantPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ParticipantPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ParticipantPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ParticipantPage extends Page { +/** +* Initialize the ParticipantPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ParticipantSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ParticipantInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ParticipantResource): ParticipantInstance { + + return new ParticipantInstance( + this._version, + payload, + this._solution.roomSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/insights/v1/setting.ts b/rest/insights/v1/setting.ts new file mode 100644 index 000000000..e2c34cf0f --- /dev/null +++ b/rest/insights/v1/setting.ts @@ -0,0 +1,500 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a SettingInstance + */ +export interface SettingContextFetchOptions { + /** The unique SID identifier of the Subaccount. */ + "subaccountSid"?: string; +} + +/** + * Options to pass to update a SettingInstance + */ +export interface SettingContextUpdateOptions { + /** A boolean flag to enable Advanced Features for Voice Insights. */ + "advancedFeatures"?: boolean; + /** A boolean flag to enable Voice Trace. */ + "voiceTrace"?: boolean; + /** The unique SID identifier of the Subaccount. */ + "subaccountSid"?: string; +} + +export interface SettingContext { + + /** + * Fetch a SettingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance + */ + fetch(callback?: (error: Error | null, item?: SettingInstance) => any): Promise; + /** + * Fetch a SettingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance + */ + fetch(params: SettingContextFetchOptions, callback?: (error: Error | null, item?: SettingInstance) => any): Promise; + + /** + * Fetch a SettingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a SettingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance with HTTP metadata + */ + fetchWithHttpInfo(params: SettingContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Update a SettingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance + */ + update(callback?: (error: Error | null, item?: SettingInstance) => any): Promise; + /** + * Update a SettingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance + */ + update(params: SettingContextUpdateOptions, callback?: (error: Error | null, item?: SettingInstance) => any): Promise; + + /** + * Update a SettingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a SettingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance with HTTP metadata + */ + updateWithHttpInfo(params: SettingContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SettingContextSolution { +} + +export class SettingContextImpl implements SettingContext { + protected _solution: SettingContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/Voice/Settings`; + } + + fetch(params?: SettingContextFetchOptions | ((error: Error | null, item?: SettingInstance) => any),callback?: (error: Error | null, item?: SettingInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["subaccountSid"] !== undefined) + data["SubaccountSid"] = params["subaccountSid"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new SettingInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: SettingContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["subaccountSid"] !== undefined) + data["SubaccountSid"] = params["subaccountSid"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SettingInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SettingContextUpdateOptions | ((error: Error | null, item?: SettingInstance) => any),callback?: (error: Error | null, item?: SettingInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["advancedFeatures"] !== undefined) + data["AdvancedFeatures"] = serialize.bool(params["advancedFeatures"]); + if (params["voiceTrace"] !== undefined) + data["VoiceTrace"] = serialize.bool(params["voiceTrace"]); + if (params["subaccountSid"] !== undefined) + data["SubaccountSid"] = params["subaccountSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SettingInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SettingContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["advancedFeatures"] !== undefined) + data["AdvancedFeatures"] = serialize.bool(params["advancedFeatures"]); + if (params["voiceTrace"] !== undefined) + data["VoiceTrace"] = serialize.bool(params["voiceTrace"]); + if (params["subaccountSid"] !== undefined) + data["SubaccountSid"] = params["subaccountSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new SettingInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SettingPayload extends SettingResource {} + +interface SettingResource { + account_sid: string; + advanced_features: boolean; + voice_trace: boolean; + url: string; +} + +export class SettingInstance { + protected _solution: SettingContextSolution; + protected _context?: SettingContext; + + constructor(protected _version: V1, payload: SettingResource) { + + this.accountSid = (payload.account_sid); + this.advancedFeatures = (payload.advanced_features); + this.voiceTrace = (payload.voice_trace); + this.url = (payload.url); + + this._solution = { }; + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * A boolean flag indicating whether Advanced Features for Voice Insights are enabled. + */ + advancedFeatures: boolean; + /** + * A boolean flag indicating whether Voice Trace is enabled. + */ + voiceTrace: boolean; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): SettingContext { + this._context = this._context || new SettingContextImpl(this._version); + return this._context; + } + + /** + * Fetch a SettingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance + */ + fetch(callback?: (error: Error | null, item?: SettingInstance) => any): Promise; + /** + * Fetch a SettingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance + */ + fetch(params: SettingContextFetchOptions, callback?: (error: Error | null, item?: SettingInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: SettingInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a SettingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a SettingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance with HTTP metadata + */ + fetchWithHttpInfo(params: SettingContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Update a SettingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance + */ + update(callback?: (error: Error | null, item?: SettingInstance) => any): Promise; + /** + * Update a SettingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance + */ + update(params: SettingContextUpdateOptions, callback?: (error: Error | null, item?: SettingInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: SettingInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a SettingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a SettingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingInstance with HTTP metadata + */ + updateWithHttpInfo(params: SettingContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + advancedFeatures: this.advancedFeatures, + voiceTrace: this.voiceTrace, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SettingSolution { +} + +export interface SettingListInstance { + _version: V1; + _solution: SettingSolution; + _uri: string; + + (): SettingContext; + get(): SettingContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SettingListInstance(version: V1): SettingListInstance { + const instance = (() => instance.get()) as SettingListInstance; + + instance.get = function get(): SettingContext { + return new SettingContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/insights/v2/inbound.ts b/rest/insights/v2/inbound.ts new file mode 100644 index 000000000..8210225eb --- /dev/null +++ b/rest/insights/v2/inbound.ts @@ -0,0 +1,788 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Sample/reference Twilio API. + * This is the reference API for the rest-proxy server. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class InsightsV2CreatePhoneNumbersReportRequest { + "timeRange"?: InsightsV2CreatePhoneNumbersReportRequestTimeRange; + "filters"?: Array; + /** + * The number of max available top Phone Numbers to generate. + */ + "size"?: number; + + constructor(payload) { + this.timeRange = payload["time_range"]; + this.filters = payload["filters"]; + this.size = payload["size"]; + } +} + + +export class InsightsV2CreatePhoneNumbersReportRequestTimeRange { + /** + * Start date time of the report + */ + "startDatetime"?: Date; + /** + * End date time of the report + */ + "endDatetime"?: Date; + + constructor(payload) { + this.startDatetime = payload["start_datetime"]; + this.endDatetime = payload["end_datetime"]; + } +} + + +/** + * Percentage of calls made in each state. + */ +export class InsightsV2InboundPhoneNumberReportCallStatePercentage { + /** + * Percentage of completed inbound calls. + */ + "completed"?: number; + /** + * Percentage of failed inbound calls. + */ + "fail"?: number; + /** + * Percentage of busy inbound calls. + */ + "busy"?: number; + /** + * Percentage of no-answer inbound calls. + */ + "noanswer"?: number; + /** + * Percentage of canceled inbound calls. + */ + "canceled"?: number; + + constructor(payload) { + this.completed = payload["completed"]; + this.fail = payload["fail"]; + this.busy = payload["busy"]; + this.noanswer = payload["noanswer"]; + this.canceled = payload["canceled"]; + } +} + + +export class PhoneNumberReportFilter { + /** + * The name of the filter + */ + "key"?: string; + /** + * List of supported filter values for the field name + */ + "values"?: Array; + + constructor(payload) { + this.key = payload["key"]; + this.values = payload["values"]; + } +} + + +export class ReportFilter { + /** + * The name of the filter \'call_state\', \'call_direction\', \'call_type\', \'twilio_regions\', \'caller_country_code\', \'callee_country_code\', \'silent\' + */ + "key"?: string; + /** + * List of supported filter values for the field name + */ + "values"?: Array; + + constructor(payload) { + this.key = payload["key"]; + this.values = payload["values"]; + } +} + + +export class ReportMetadata { + /** + * Start date time of the report + */ + "startDatetime"?: Date; + /** + * End date time of the report + */ + "endDatetime"?: Date; + /** + * Filter values applied to the report + */ + "filters"?: Array; + + constructor(payload) { + this.startDatetime = payload["start_datetime"]; + this.endDatetime = payload["end_datetime"]; + this.filters = payload["filters"]; + } +} + + +/** + * The status of the report. + */ +export type ReportStatus = 'created'|'running'|'completed'; + + +/** + * Options to pass to create a InboundInstance + */ +export interface InboundContextCreateOptions { + /** */ + "insightsV2CreatePhoneNumbersReportRequest"?: InsightsV2CreatePhoneNumbersReportRequest; +} + +/** + * Options to pass to each + */ +export interface InboundListInstanceEachOptions { + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InboundInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InboundListInstanceOptions { + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InboundListInstancePageOptions { + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InboundContext { + + /** + * Create a InboundInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InboundInstance + */ + create(callback?: (error: Error | null, item?: InboundInstance) => any): Promise; + /** + * Create a InboundInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InboundInstance + */ + create(params: InsightsV2CreatePhoneNumbersReportRequest, headers?: any, callback?: (error: Error | null, item?: InboundInstance) => any): Promise; + + /** + * Create a InboundInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InboundInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a InboundInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InboundInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsV2CreatePhoneNumbersReportRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InboundContextSolution { + "reportId": string; +} + +export class InboundContextImpl implements InboundContext { + protected _solution: InboundContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, reportId: string) { + if (!isValidPathParam(reportId)) { + throw new Error('Parameter \'reportId\' is not valid.'); + } + + this._solution = { reportId, }; + this._uri = `/Voice/Reports/PhoneNumbers/Inbound`; + } + + create(params?: InsightsV2CreatePhoneNumbersReportRequest | ((error: Error | null, item?: InboundInstance) => any), headers?: any,callback?: (error: Error | null, item?: InboundInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as InsightsV2CreatePhoneNumbersReportRequest; + } else { + params = params || {} as Partial as InsightsV2CreatePhoneNumbersReportRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InboundInstance(operationVersion, payload, instance._solution.reportId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params?: InsightsV2CreatePhoneNumbersReportRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as InsightsV2CreatePhoneNumbersReportRequest; + } else { + params = params || {} as Partial as InsightsV2CreatePhoneNumbersReportRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InboundInstance(operationVersion, response.body, instance._solution.reportId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InboundPayload extends TwilioResponsePayload { + reports: InboundResource[]; +} + +interface InboundResource { + account_sid: string; + report_id: string; + status: ReportStatus; + request_meta: ReportMetadata; + url: string; + handle: string; + total_calls: number; + call_answer_score: number; + call_state_percentage: InsightsV2InboundPhoneNumberReportCallStatePercentage; + silent_calls_percentage: number; +} + +export class InboundInstance { + protected _solution: InboundContextSolution; + protected _context?: InboundContext; + + constructor(protected _version: V2, payload: InboundResource, reportId?: string) { + + this.accountSid = (payload.account_sid); + this.reportId = (payload.report_id); + this.status = payload.status; + this.requestMeta = payload.request_meta !== null && payload.request_meta !== undefined ? new ReportMetadata(payload.request_meta) : null; + this.url = (payload.url); + this.handle = (payload.handle); + this.totalCalls = deserialize.integer(payload.total_calls); + this.callAnswerScore = (payload.call_answer_score); + this.callStatePercentage = payload.call_state_percentage !== null && payload.call_state_percentage !== undefined ? new InsightsV2InboundPhoneNumberReportCallStatePercentage(payload.call_state_percentage) : null; + this.silentCallsPercentage = (payload.silent_calls_percentage); + + this._solution = { reportId: reportId, }; + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The report identifier as Voice Insights Report TTID. + */ + reportId: string; + status: ReportStatus; + requestMeta: ReportMetadata; + /** + * The URL of this resource. + */ + url: string; + /** + * Inbound phone number handle represented in the report. + */ + handle: string; + /** + * Total number of calls made with the given handle during the report period. + */ + totalCalls: number; + /** + * The call answer score measures customers behavior to the delivered calls. The score is a value between 0 and 100, where 100 indicates that all calls were successfully answered. + */ + callAnswerScore: number; + callStatePercentage: InsightsV2InboundPhoneNumberReportCallStatePercentage; + /** + * Percentage of inbound calls with silence tags over total outbound calls. A silent tag is indicative of a connectivity issue or muted audio. + */ + silentCallsPercentage: number; + + private get _proxy(): InboundContext { + this._context = this._context || new InboundContextImpl(this._version, this._solution.reportId); + return this._context; + } + + /** + * Create a InboundInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InboundInstance + */ + create(callback?: (error: Error | null, item?: InboundInstance) => any): Promise; + /** + * Create a InboundInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InboundInstance + */ + create(params: InsightsV2CreatePhoneNumbersReportRequest, headers?: any, callback?: (error: Error | null, item?: InboundInstance) => any): Promise; + + create(params?: any, callback?: (error: Error | null, item?: InboundInstance) => any): Promise + { + return this._proxy.create(params, callback); + } + + /** + * Create a InboundInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InboundInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a InboundInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InboundInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsV2CreatePhoneNumbersReportRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + reportId: this.reportId, + status: this.status, + requestMeta: this.requestMeta, + url: this.url, + handle: this.handle, + totalCalls: this.totalCalls, + callAnswerScore: this.callAnswerScore, + callStatePercentage: this.callStatePercentage, + silentCallsPercentage: this.silentCallsPercentage, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InboundSolution { + reportId: string; +} + +export interface InboundListInstance { + _version: V2; + _solution: InboundSolution; + _uri: string; + + (reportId: string, ): InboundContext; + get(reportId: string, ): InboundContext; + + + + + + /** + * Streams InboundInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InboundListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InboundInstance, done: (err?: Error) => void) => void): void; + each(params: InboundListInstanceEachOptions, callback?: (item: InboundInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InboundInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InboundListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InboundInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InboundListInstanceEachOptions, callback?: (item: InboundInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InboundInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InboundPage) => any): Promise; + /** + * Retrieve a single target page of InboundInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InboundInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InboundListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InboundInstance[]) => any): Promise; + list(params: InboundListInstanceOptions, callback?: (error: Error | null, items: InboundInstance[]) => any): Promise; + /** + * Lists InboundInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InboundListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InboundListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InboundInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InboundListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InboundPage) => any): Promise; + page(params: InboundListInstancePageOptions, callback?: (error: Error | null, items: InboundPage) => any): Promise; + /** + * Retrieve a single page of InboundInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InboundListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InboundListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InboundListInstance(version: V2, reportId: string): InboundListInstance { + if (!isValidPathParam(reportId)) { + throw new Error('Parameter \'reportId\' is not valid.'); + } + + const instance = ((reportId, ) => instance.get(reportId, )) as InboundListInstance; + + instance.get = function get(reportId, ): InboundContext { + return new InboundContextImpl(version, reportId); + } + + instance._version = version; + instance._solution = { reportId, }; + instance._uri = `/Voice/Reports/PhoneNumbers/Inbound/${reportId}`; + + instance.page = function page(params?: InboundListInstancePageOptions | ((error: Error | null, items: InboundPage) => any), callback?: (error: Error | null, items: InboundPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InboundPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InboundPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InboundPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InboundListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InboundPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InboundPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InboundPage extends Page { +/** +* Initialize the InboundPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: InboundSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InboundInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InboundResource): InboundInstance { + + return new InboundInstance( + this._version, + payload, + this._solution.reportId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/insights/v2/outbound.ts b/rest/insights/v2/outbound.ts new file mode 100644 index 000000000..0a948f9e0 --- /dev/null +++ b/rest/insights/v2/outbound.ts @@ -0,0 +1,899 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Sample/reference Twilio API. + * This is the reference API for the rest-proxy server. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class CountyCarrierValue { + "country"?: string; + "carriers"?: Array; + + constructor(payload) { + this.country = payload["country"]; + this.carriers = payload["carriers"]; + } +} + + +export class CountyCarrierValueCarriers { + /** + * The name of the carrier. + */ + "carrier"?: string; + /** + * Total number of outbound calls for the carrier in the country. + */ + "totalCalls"?: number; + /** + * Total number of blocked outbound calls for the carrier in the country. + */ + "blockedCalls"?: number; + /** + * Percentage of blocked outbound calls for the carrier in the country. + */ + "blockedCallsPercentage"?: number; + + constructor(payload) { + this.carrier = payload["carrier"]; + this.totalCalls = payload["total_calls"]; + this.blockedCalls = payload["blocked_calls"]; + this.blockedCallsPercentage = payload["blocked_calls_percentage"]; + } +} + + +export class InsightsV2CreatePhoneNumbersReportRequest { + "timeRange"?: InsightsV2CreatePhoneNumbersReportRequestTimeRange; + "filters"?: Array; + /** + * The number of max available top Phone Numbers to generate. + */ + "size"?: number; + + constructor(payload) { + this.timeRange = payload["time_range"]; + this.filters = payload["filters"]; + this.size = payload["size"]; + } +} + + +export class InsightsV2CreatePhoneNumbersReportRequestTimeRange { + /** + * Start date time of the report + */ + "startDatetime"?: Date; + /** + * End date time of the report + */ + "endDatetime"?: Date; + + constructor(payload) { + this.startDatetime = payload["start_datetime"]; + this.endDatetime = payload["end_datetime"]; + } +} + + +/** + * Percentage of calls made in each state. + */ +export class InsightsV2InboundPhoneNumberReportCallStatePercentage { + /** + * Percentage of completed inbound calls. + */ + "completed"?: number; + /** + * Percentage of failed inbound calls. + */ + "fail"?: number; + /** + * Percentage of busy inbound calls. + */ + "busy"?: number; + /** + * Percentage of no-answer inbound calls. + */ + "noanswer"?: number; + /** + * Percentage of canceled inbound calls. + */ + "canceled"?: number; + + constructor(payload) { + this.completed = payload["completed"]; + this.fail = payload["fail"]; + this.busy = payload["busy"]; + this.noanswer = payload["noanswer"]; + this.canceled = payload["canceled"]; + } +} + + +/** + * Number of calls made in answering machine detection (AMD) enabled. + */ +export class InsightsV2OutboundPhoneNumberReportAnsweringMachineDetection { + /** + * Total number of calls with answering machine detection (AMD) enabled. + */ + "totalCalls"?: number; + /** + * Percentage of calls marked as answered by human. + */ + "answeredByHumanPercentage"?: number; + /** + * Percentage of calls marked as answered by machined related like the following: `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `fax` + */ + "answeredByMachinePercentage"?: number; + + constructor(payload) { + this.totalCalls = payload["total_calls"]; + this.answeredByHumanPercentage = payload["answered_by_human_percentage"]; + this.answeredByMachinePercentage = payload["answered_by_machine_percentage"]; + } +} + + +export class PhoneNumberReportFilter { + /** + * The name of the filter + */ + "key"?: string; + /** + * List of supported filter values for the field name + */ + "values"?: Array; + + constructor(payload) { + this.key = payload["key"]; + this.values = payload["values"]; + } +} + + +export class ReportFilter { + /** + * The name of the filter \'call_state\', \'call_direction\', \'call_type\', \'twilio_regions\', \'caller_country_code\', \'callee_country_code\', \'silent\' + */ + "key"?: string; + /** + * List of supported filter values for the field name + */ + "values"?: Array; + + constructor(payload) { + this.key = payload["key"]; + this.values = payload["values"]; + } +} + + +export class ReportMetadata { + /** + * Start date time of the report + */ + "startDatetime"?: Date; + /** + * End date time of the report + */ + "endDatetime"?: Date; + /** + * Filter values applied to the report + */ + "filters"?: Array; + + constructor(payload) { + this.startDatetime = payload["start_datetime"]; + this.endDatetime = payload["end_datetime"]; + this.filters = payload["filters"]; + } +} + + +/** + * The status of the report. + */ +export type ReportStatus = 'created'|'running'|'completed'; + + +/** + * Options to pass to create a OutboundInstance + */ +export interface OutboundContextCreateOptions { + /** */ + "insightsV2CreatePhoneNumbersReportRequest"?: InsightsV2CreatePhoneNumbersReportRequest; +} + +/** + * Options to pass to each + */ +export interface OutboundListInstanceEachOptions { + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: OutboundInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface OutboundListInstanceOptions { + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface OutboundListInstancePageOptions { + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface OutboundContext { + + /** + * Create a OutboundInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutboundInstance + */ + create(callback?: (error: Error | null, item?: OutboundInstance) => any): Promise; + /** + * Create a OutboundInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutboundInstance + */ + create(params: InsightsV2CreatePhoneNumbersReportRequest, headers?: any, callback?: (error: Error | null, item?: OutboundInstance) => any): Promise; + + /** + * Create a OutboundInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutboundInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a OutboundInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutboundInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsV2CreatePhoneNumbersReportRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OutboundContextSolution { + "reportId": string; +} + +export class OutboundContextImpl implements OutboundContext { + protected _solution: OutboundContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, reportId: string) { + if (!isValidPathParam(reportId)) { + throw new Error('Parameter \'reportId\' is not valid.'); + } + + this._solution = { reportId, }; + this._uri = `/Voice/Reports/PhoneNumbers/Outbound`; + } + + create(params?: InsightsV2CreatePhoneNumbersReportRequest | ((error: Error | null, item?: OutboundInstance) => any), headers?: any,callback?: (error: Error | null, item?: OutboundInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as InsightsV2CreatePhoneNumbersReportRequest; + } else { + params = params || {} as Partial as InsightsV2CreatePhoneNumbersReportRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new OutboundInstance(operationVersion, payload, instance._solution.reportId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params?: InsightsV2CreatePhoneNumbersReportRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as InsightsV2CreatePhoneNumbersReportRequest; + } else { + params = params || {} as Partial as InsightsV2CreatePhoneNumbersReportRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new OutboundInstance(operationVersion, response.body, instance._solution.reportId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface OutboundPayload extends TwilioResponsePayload { + reports: OutboundResource[]; +} + +interface OutboundResource { + account_sid: string; + report_id: string; + status: ReportStatus; + request_meta: ReportMetadata; + url: string; + handle: string; + total_calls: number; + call_answer_score: number; + call_state_percentage: InsightsV2InboundPhoneNumberReportCallStatePercentage; + silent_calls_percentage: number; + calls_by_device_type: { [key: string]: number; }; + answer_rate_device_type: { [key: string]: number; }; + blocked_calls_by_carrier: Array; + short_duration_calls_percentage: number; + long_duration_calls_percentage: number; + potential_robocalls_percentage: number; + answering_machine_detection: InsightsV2OutboundPhoneNumberReportAnsweringMachineDetection; +} + +export class OutboundInstance { + protected _solution: OutboundContextSolution; + protected _context?: OutboundContext; + + constructor(protected _version: V2, payload: OutboundResource, reportId?: string) { + + this.accountSid = (payload.account_sid); + this.reportId = (payload.report_id); + this.status = payload.status; + this.requestMeta = payload.request_meta !== null && payload.request_meta !== undefined ? new ReportMetadata(payload.request_meta) : null; + this.url = (payload.url); + this.handle = (payload.handle); + this.totalCalls = deserialize.integer(payload.total_calls); + this.callAnswerScore = (payload.call_answer_score); + this.callStatePercentage = payload.call_state_percentage !== null && payload.call_state_percentage !== undefined ? new InsightsV2InboundPhoneNumberReportCallStatePercentage(payload.call_state_percentage) : null; + this.silentCallsPercentage = (payload.silent_calls_percentage); + this.callsByDeviceType = (payload.calls_by_device_type); + this.answerRateDeviceType = (payload.answer_rate_device_type); + this.blockedCallsByCarrier = payload.blocked_calls_by_carrier !== null && payload.blocked_calls_by_carrier !== undefined ? payload.blocked_calls_by_carrier.map( + (payload: any) => new CountyCarrierValue(payload) + ) : null; + this.shortDurationCallsPercentage = (payload.short_duration_calls_percentage); + this.longDurationCallsPercentage = (payload.long_duration_calls_percentage); + this.potentialRobocallsPercentage = (payload.potential_robocalls_percentage); + this.answeringMachineDetection = payload.answering_machine_detection !== null && payload.answering_machine_detection !== undefined ? new InsightsV2OutboundPhoneNumberReportAnsweringMachineDetection(payload.answering_machine_detection) : null; + + this._solution = { reportId: reportId, }; + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The report identifier as Voice Insights Report TTID. + */ + reportId: string; + status: ReportStatus; + requestMeta: ReportMetadata; + /** + * The URL of this resource. + */ + url: string; + /** + * Inbound phone number handle represented in the report. + */ + handle: string; + /** + * Total number of calls made with the given handle during the report period. + */ + totalCalls: number; + /** + * The call answer score measures customers behavior to the delivered calls. The score is a value between 0 and 100, where 100 indicates that all calls were successfully answered. + */ + callAnswerScore: number; + callStatePercentage: InsightsV2InboundPhoneNumberReportCallStatePercentage; + /** + * Percentage of inbound calls with silence tags over total outbound calls. A silent tag is indicative of a connectivity issue or muted audio. + */ + silentCallsPercentage: number; + /** + * Number of calls made with each device type. `voip`, `mobile`, `landline`, `unknown` + */ + callsByDeviceType: { [key: string]: number; }; + /** + * Answer rate for each device type. `voip`, `mobile`, `landline`, `unknown` + */ + answerRateDeviceType: { [key: string]: number; }; + /** + * Percentage of blocked calls by carrier per country. + */ + blockedCallsByCarrier: Array; + /** + * Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + */ + shortDurationCallsPercentage: number; + /** + * Percentage of long duration calls ( >= 60 seconds) + */ + longDurationCallsPercentage: number; + /** + * Percentage of completed outbound calls to unassigned or unallocated phone numbers. + */ + potentialRobocallsPercentage: number; + answeringMachineDetection: InsightsV2OutboundPhoneNumberReportAnsweringMachineDetection; + + private get _proxy(): OutboundContext { + this._context = this._context || new OutboundContextImpl(this._version, this._solution.reportId); + return this._context; + } + + /** + * Create a OutboundInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutboundInstance + */ + create(callback?: (error: Error | null, item?: OutboundInstance) => any): Promise; + /** + * Create a OutboundInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutboundInstance + */ + create(params: InsightsV2CreatePhoneNumbersReportRequest, headers?: any, callback?: (error: Error | null, item?: OutboundInstance) => any): Promise; + + create(params?: any, callback?: (error: Error | null, item?: OutboundInstance) => any): Promise + { + return this._proxy.create(params, callback); + } + + /** + * Create a OutboundInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutboundInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a OutboundInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OutboundInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsV2CreatePhoneNumbersReportRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + reportId: this.reportId, + status: this.status, + requestMeta: this.requestMeta, + url: this.url, + handle: this.handle, + totalCalls: this.totalCalls, + callAnswerScore: this.callAnswerScore, + callStatePercentage: this.callStatePercentage, + silentCallsPercentage: this.silentCallsPercentage, + callsByDeviceType: this.callsByDeviceType, + answerRateDeviceType: this.answerRateDeviceType, + blockedCallsByCarrier: this.blockedCallsByCarrier, + shortDurationCallsPercentage: this.shortDurationCallsPercentage, + longDurationCallsPercentage: this.longDurationCallsPercentage, + potentialRobocallsPercentage: this.potentialRobocallsPercentage, + answeringMachineDetection: this.answeringMachineDetection, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OutboundSolution { + reportId: string; +} + +export interface OutboundListInstance { + _version: V2; + _solution: OutboundSolution; + _uri: string; + + (reportId: string, ): OutboundContext; + get(reportId: string, ): OutboundContext; + + + + + + /** + * Streams OutboundInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutboundListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: OutboundInstance, done: (err?: Error) => void) => void): void; + each(params: OutboundListInstanceEachOptions, callback?: (item: OutboundInstance, done: (err?: Error) => void) => void): void; + /** + * Streams OutboundInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutboundListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: OutboundInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: OutboundListInstanceEachOptions, callback?: (item: OutboundInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of OutboundInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: OutboundPage) => any): Promise; + /** + * Retrieve a single target page of OutboundInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists OutboundInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutboundListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: OutboundInstance[]) => any): Promise; + list(params: OutboundListInstanceOptions, callback?: (error: Error | null, items: OutboundInstance[]) => any): Promise; + /** + * Lists OutboundInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutboundListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: OutboundListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of OutboundInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutboundListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: OutboundPage) => any): Promise; + page(params: OutboundListInstancePageOptions, callback?: (error: Error | null, items: OutboundPage) => any): Promise; + /** + * Retrieve a single page of OutboundInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OutboundListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: OutboundListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OutboundListInstance(version: V2, reportId: string): OutboundListInstance { + if (!isValidPathParam(reportId)) { + throw new Error('Parameter \'reportId\' is not valid.'); + } + + const instance = ((reportId, ) => instance.get(reportId, )) as OutboundListInstance; + + instance.get = function get(reportId, ): OutboundContext { + return new OutboundContextImpl(version, reportId); + } + + instance._version = version; + instance._solution = { reportId, }; + instance._uri = `/Voice/Reports/PhoneNumbers/Outbound/${reportId}`; + + instance.page = function page(params?: OutboundListInstancePageOptions | ((error: Error | null, items: OutboundPage) => any), callback?: (error: Error | null, items: OutboundPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new OutboundPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: OutboundPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new OutboundPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: OutboundListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OutboundPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OutboundPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class OutboundPage extends Page { +/** +* Initialize the OutboundPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: OutboundSolution) { + super(version, response, solution); + } + + /** + * Build an instance of OutboundInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: OutboundResource): OutboundInstance { + + return new OutboundInstance( + this._version, + payload, + this._solution.reportId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/insights/v2/report.ts b/rest/insights/v2/report.ts new file mode 100644 index 000000000..8d347f834 --- /dev/null +++ b/rest/insights/v2/report.ts @@ -0,0 +1,1212 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Sample/reference Twilio API. + * This is the reference API for the rest-proxy server. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class AccountReport { + /** + * The call deliverability score measures the network effectiveness in delivering calls by scoring calls reach the intended recipient. The score is a value between 0 and 100, where 100 indicates that all calls were successfully delivered. + */ + "callDeliverabilityScore"?: number; + /** + * The call answer score measures customers behavior to the delivered calls. The score is a value between 0 and 100, where 100 indicates that all calls were successfully answered. + */ + "callAnswerScore"?: number; + /** + * Total number of calls made during the report period. + */ + "totalCalls"?: number; + "callDirection"?: AccountReportCallDirection; + "callState"?: AccountReportCallState; + "callType"?: AccountReportCallType; + /** + * Average length of call in seconds. + */ + "aloc"?: number; + /** + * Number of calls made in each Twilio Edge location. Refer to [Public Edge Locations](https://www.twilio.com/docs/global-infrastructure/edge-locations#public-edge-locations) for more detail. + */ + "twilioEdgeLocation"?: { [key: string]: number; }; + /** + * Number of calls originating from each country (ISO alpha-2). + */ + "callerCountryCode"?: { [key: string]: number; }; + /** + * Number of calls terminating in each country (ISO alpha-2). + */ + "calleeCountryCode"?: { [key: string]: number; }; + /** + * Average queue time in milliseconds. + */ + "averageQueueTimeMs"?: number; + /** + * Percentage of silent calls. + */ + "silentCallsPercentage"?: number; + "networkIssues"?: AccountReportNetworkIssues; + "kYT"?: AccountReportKYT; + "answeringMachineDetection"?: AccountReportAnsweringMachineDetection; + + constructor(payload) { + this.callDeliverabilityScore = payload["call_deliverability_score"]; + this.callAnswerScore = payload["call_answer_score"]; + this.totalCalls = payload["total_calls"]; + this.callDirection = payload["call_direction"]; + this.callState = payload["call_state"]; + this.callType = payload["call_type"]; + this.aloc = payload["aloc"]; + this.twilioEdgeLocation = payload["twilio_edge_location"]; + this.callerCountryCode = payload["caller_country_code"]; + this.calleeCountryCode = payload["callee_country_code"]; + this.averageQueueTimeMs = payload["average_queue_time_ms"]; + this.silentCallsPercentage = payload["silent_calls_percentage"]; + this.networkIssues = payload["network_issues"]; + this.kYT = payload["KYT"]; + this.answeringMachineDetection = payload["answering_machine_detection"]; + } +} + + +/** + * Number of calls made in each answering machine detection. + */ +export class AccountReportAnsweringMachineDetection { + /** + * Total number of calls with answering machine detection enabled (AMD). + */ + "totalCalls"?: number; + /** + * Percentage of calls marked as answered by human. + */ + "answeredByHumanPercentage"?: number; + /** + * Percentage of calls marked as answered by machined related like the following: `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `fax` + */ + "answeredByMachinePercentage"?: number; + + constructor(payload) { + this.totalCalls = payload["total_calls"]; + this.answeredByHumanPercentage = payload["answered_by_human_percentage"]; + this.answeredByMachinePercentage = payload["answered_by_machine_percentage"]; + } +} + + +/** + * Number of calls made in each direction. + */ +export class AccountReportCallDirection { + /** + * Number of outbound calls + */ + "outbound"?: number; + /** + * Number of inbound calls + */ + "inbound"?: number; + + constructor(payload) { + this.outbound = payload["outbound"]; + this.inbound = payload["inbound"]; + } +} + + +/** + * Number of calls made in each state. + */ +export class AccountReportCallState { + /** + * Number of completed calls + */ + "completed"?: number; + /** + * Number of failed calls + */ + "fail"?: number; + /** + * Number of busy calls + */ + "busy"?: number; + /** + * Number of no-answer calls + */ + "noanswer"?: number; + /** + * Number of canceled calls + */ + "canceled"?: number; + + constructor(payload) { + this.completed = payload["completed"]; + this.fail = payload["fail"]; + this.busy = payload["busy"]; + this.noanswer = payload["noanswer"]; + this.canceled = payload["canceled"]; + } +} + + +/** + * Number of calls made in each type. `carrier`, `sip`, `trunking`, `client`, `whatsapp` + */ +export class AccountReportCallType { + /** + * Number of carrier calls + */ + "carrier"?: number; + /** + * Number of SIP calls + */ + "sip"?: number; + /** + * Number of trunking calls + */ + "trunking"?: number; + /** + * Number of client calls + */ + "client"?: number; + /** + * Number of WhatsApp Business calls + */ + "whatsapp"?: number; + + constructor(payload) { + this.carrier = payload["carrier"]; + this.sip = payload["sip"]; + this.trunking = payload["trunking"]; + this.client = payload["client"]; + this.whatsapp = payload["whatsapp"]; + } +} + + +/** + * Know Your Traffic (KYT) metrics focused on outbound carrier performance and trust signals for the report period. + */ +export class AccountReportKYT { + "outboundCarrierCalling"?: AccountReportKYTOutboundCarrierCalling; + + constructor(payload) { + this.outboundCarrierCalling = payload["outbound_carrier_calling"]; + } +} + + +/** + * KYT metrics for outbound carrier calling. + */ +export class AccountReportKYTOutboundCarrierCalling { + /** + * Number of unique PSTN calling numbers to non-Twilio numbers during the report period. + */ + "uniqueCallingNumbers"?: number; + /** + * Number of unique non-Twilio PSTN called numbers during the report period. + */ + "uniqueCalledNumbers"?: number; + /** + * Percentage of blocked calls by carrier per country. + */ + "blockedCallsByCarrier"?: Array; + /** + * Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + */ + "shortDurationCallsPercentage"?: number; + /** + * Percentage of long duration calls ( >= 60 seconds) + */ + "longDurationCallsPercentage"?: number; + /** + * Percentage of completed outbound calls to unassigned or unallocated phone numbers. + */ + "potentialRobocallsPercentage"?: number; + "brandedCalling"?: BrandedCalling; + "voiceIntegrity"?: VoiceIntegrity; + "stirShaken"?: StirShaken; + + constructor(payload) { + this.uniqueCallingNumbers = payload["unique_calling_numbers"]; + this.uniqueCalledNumbers = payload["unique_called_numbers"]; + this.blockedCallsByCarrier = payload["blocked_calls_by_carrier"]; + this.shortDurationCallsPercentage = payload["short_duration_calls_percentage"]; + this.longDurationCallsPercentage = payload["long_duration_calls_percentage"]; + this.potentialRobocallsPercentage = payload["potential_robocalls_percentage"]; + this.brandedCalling = payload["branded_calling"]; + this.voiceIntegrity = payload["voice_integrity"]; + this.stirShaken = payload["stir_shaken"]; + } +} + + +/** + * Network-quality indicators for SDK and Twilio Gateway traffic during the report period. + */ +export class AccountReportNetworkIssues { + "sdk"?: AccountReportNetworkIssuesSdk; + "twilioGateway"?: AccountReportNetworkIssuesTwilioGateway; + + constructor(payload) { + this.sdk = payload["sdk"]; + this.twilioGateway = payload["twilio_gateway"]; + } +} + + +/** + * Network issues of calls for client type. This is indicative of local network issues. + */ +export class AccountReportNetworkIssuesSdk { + /** + * Percentage of ICE connection failure tag that ICE candidates have failed to find compatible connection. + */ + "iceFailuresPercentage"?: number; + /** + * Percentage of calls with high latency. + */ + "highLatencyPercentage"?: number; + /** + * Percentage of calls with high packet loss. + */ + "highPacketLossPercentage"?: number; + /** + * Percentage of calls with high jitter. + */ + "highJitterPercentage"?: number; + + constructor(payload) { + this.iceFailuresPercentage = payload["ice_failures_percentage"]; + this.highLatencyPercentage = payload["high_latency_percentage"]; + this.highPacketLossPercentage = payload["high_packet_loss_percentage"]; + this.highJitterPercentage = payload["high_jitter_percentage"]; + } +} + + +/** + * Network related metrics for Twilio Gateway calls only. + */ +export class AccountReportNetworkIssuesTwilioGateway { + /** + * Percentage of calls with high latency. + */ + "highLatencyPercentage"?: number; + /** + * Percentage of calls with high packet loss. + */ + "highPacketLossPercentage"?: number; + /** + * Percentage of calls with high jitter. + */ + "highJitterPercentage"?: number; + + constructor(payload) { + this.highLatencyPercentage = payload["high_latency_percentage"]; + this.highPacketLossPercentage = payload["high_packet_loss_percentage"]; + this.highJitterPercentage = payload["high_jitter_percentage"]; + } +} + + +/** + * Metrics related to Branded Calling bundled calls including CTIA for the report period. + */ +export class BrandedCalling { + /** + * Total number of Branded bundled calls. + */ + "totalBrandedCalls"?: number; + /** + * Percentage of Branded bundled calls over total outbound calls. + */ + "percentBrandedCalls"?: number; + /** + * Answer rate for Branded bundled calls. + */ + "answerRate"?: number; + /** + * Rate of Branded bundled calls that were answered by Human. + */ + "humanAnswerRate"?: number; + /** + * Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds. + */ + "engagementRate"?: number; + /** + * Details of branded calls by use case. + */ + "byUseCase"?: Array; + + constructor(payload) { + this.totalBrandedCalls = payload["total_branded_calls"]; + this.percentBrandedCalls = payload["percent_branded_calls"]; + this.answerRate = payload["answer_rate"]; + this.humanAnswerRate = payload["human_answer_rate"]; + this.engagementRate = payload["engagement_rate"]; + this.byUseCase = payload["by_use_case"]; + } +} + + +/** + * Associated metrics for Branded calls grouped by each use case. + */ +export class BrandedUseCaseDetail { + /** + * The name of supported use case for Branded calls. + */ + "useCase"?: string; + /** + * The number of phone numbers enabled Branded calls. + */ + "enabledPhonenumbers"?: number; + /** + * The number of total outbound calls for the use case. + */ + "totalCalls"?: number; + /** + * Answer rate per each use case for Branded bundled calls. + */ + "answerRate"?: number; + /** + * Rate of Branded bundled calls that were answered by Human per each use case for Branded bundled calls. + */ + "humanAnswerRate"?: number; + /** + * Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds per each use case for Branded bundled calls. + */ + "engagementRate"?: number; + + constructor(payload) { + this.useCase = payload["use_case"]; + this.enabledPhonenumbers = payload["enabled_phonenumbers"]; + this.totalCalls = payload["total_calls"]; + this.answerRate = payload["answer_rate"]; + this.humanAnswerRate = payload["human_answer_rate"]; + this.engagementRate = payload["engagement_rate"]; + } +} + + +export class CountyCarrierValue { + "country"?: string; + "carriers"?: Array; + + constructor(payload) { + this.country = payload["country"]; + this.carriers = payload["carriers"]; + } +} + + +export class CountyCarrierValueCarriers { + /** + * The name of the carrier. + */ + "carrier"?: string; + /** + * Total number of outbound calls for the carrier in the country. + */ + "totalCalls"?: number; + /** + * Total number of blocked outbound calls for the carrier in the country. + */ + "blockedCalls"?: number; + /** + * Percentage of blocked outbound calls for the carrier in the country. + */ + "blockedCallsPercentage"?: number; + + constructor(payload) { + this.carrier = payload["carrier"]; + this.totalCalls = payload["total_calls"]; + this.blockedCalls = payload["blocked_calls"]; + this.blockedCallsPercentage = payload["blocked_calls_percentage"]; + } +} + + +export class InsightsV2CreateAccountReportRequest { + "timeRange"?: InsightsV2CreateAccountReportRequestTimeRange; + "filters"?: Array; + + constructor(payload) { + this.timeRange = payload["time_range"]; + this.filters = payload["filters"]; + } +} + + +/** + * Optional start and end date time for the report window. Defaults to the most recent 7 days when omitted. + */ +export class InsightsV2CreateAccountReportRequestTimeRange { + /** + * Start date time of the report + */ + "startDatetime"?: Date; + /** + * End date time of the report + */ + "endDatetime"?: Date; + + constructor(payload) { + this.startDatetime = payload["start_datetime"]; + this.endDatetime = payload["end_datetime"]; + } +} + + +/** + * Percentage of calls made in each state. + */ +export class InsightsV2InboundPhoneNumberReportCallStatePercentage { + /** + * Percentage of completed inbound calls. + */ + "completed"?: number; + /** + * Percentage of failed inbound calls. + */ + "fail"?: number; + /** + * Percentage of busy inbound calls. + */ + "busy"?: number; + /** + * Percentage of no-answer inbound calls. + */ + "noanswer"?: number; + /** + * Percentage of canceled inbound calls. + */ + "canceled"?: number; + + constructor(payload) { + this.completed = payload["completed"]; + this.fail = payload["fail"]; + this.busy = payload["busy"]; + this.noanswer = payload["noanswer"]; + this.canceled = payload["canceled"]; + } +} + + +/** + * Number of calls made in answering machine detection (AMD) enabled. + */ +export class InsightsV2OutboundPhoneNumberReportAnsweringMachineDetection { + /** + * Total number of calls with answering machine detection (AMD) enabled. + */ + "totalCalls"?: number; + /** + * Percentage of calls marked as answered by human. + */ + "answeredByHumanPercentage"?: number; + /** + * Percentage of calls marked as answered by machined related like the following: `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `fax` + */ + "answeredByMachinePercentage"?: number; + + constructor(payload) { + this.totalCalls = payload["total_calls"]; + this.answeredByHumanPercentage = payload["answered_by_human_percentage"]; + this.answeredByMachinePercentage = payload["answered_by_machine_percentage"]; + } +} + + +export class ReportFilter { + /** + * The name of the filter \'call_state\', \'call_direction\', \'call_type\', \'twilio_regions\', \'caller_country_code\', \'callee_country_code\', \'silent\' + */ + "key"?: string; + /** + * List of supported filter values for the field name + */ + "values"?: Array; + + constructor(payload) { + this.key = payload["key"]; + this.values = payload["values"]; + } +} + + +export class ReportMetadata { + /** + * Start date time of the report + */ + "startDatetime"?: Date; + /** + * End date time of the report + */ + "endDatetime"?: Date; + /** + * Filter values applied to the report + */ + "filters"?: Array; + + constructor(payload) { + this.startDatetime = payload["start_datetime"]; + this.endDatetime = payload["end_datetime"]; + this.filters = payload["filters"]; + } +} + + +/** + * The status of the report. + */ +export type ReportStatus = 'created'|'running'|'completed'; + +/** + * Metrics related to STIR/SHAKEN attestation A, B, and C for the report period. + */ +export class StirShaken { + "callCount"?: StirShakenCallCount; + "percentage"?: StirShakenPercentage; + "answerRate"?: StirShakenAnswerRate; + + constructor(payload) { + this.callCount = payload["call_count"]; + this.percentage = payload["percentage"]; + this.answerRate = payload["answer_rate"]; + } +} + + +/** + * Answer rate for each STIR/SHAKEN attestation category. + */ +export class StirShakenAnswerRate { + /** + * Answer rate for Stir Shaken category A. + */ + "stshA"?: number; + /** + * Answer rate for Stir Shaken category B. + */ + "stshB"?: number; + /** + * Answer rate for Stir Shaken category C. + */ + "stshC"?: number; + + constructor(payload) { + this.stshA = payload["stsh_a"]; + this.stshB = payload["stsh_b"]; + this.stshC = payload["stsh_c"]; + } +} + + +/** + * Total number of calls for each STIR/SHAKEN attestation category. + */ +export class StirShakenCallCount { + /** + * Total number of calls for Stir Shaken category A. + */ + "stshA"?: number; + /** + * Total number of calls for Stir Shaken category B. + */ + "stshB"?: number; + /** + * Total number of calls for Stir Shaken category C. + */ + "stshC"?: number; + + constructor(payload) { + this.stshA = payload["stsh_a"]; + this.stshB = payload["stsh_b"]; + this.stshC = payload["stsh_c"]; + } +} + + +/** + * Percentage of calls for each STIR/SHAKEN attestation category. + */ +export class StirShakenPercentage { + /** + * Percentage of calls for Stir Shaken category A. + */ + "stshA"?: number; + /** + * Percentage of calls for Stir Shaken category B. + */ + "stshB"?: number; + /** + * Percentage of calls for Stir Shaken category C. + */ + "stshC"?: number; + + constructor(payload) { + this.stshA = payload["stsh_a"]; + this.stshB = payload["stsh_b"]; + this.stshC = payload["stsh_c"]; + } +} + + +/** + * Metrics related to Voice Integrity enabled calls for the report period. + */ +export class VoiceIntegrity { + /** + * Total number of calls with Voice Integrity enabled. + */ + "enabledCalls"?: number; + /** + * Percentage of calls with Voice Integrity enabled. + */ + "enabledPercentage"?: number; + /** + * Number of calls per Voice Integrity enabled Bundle Sid. + */ + "callsPerBundle"?: Array; + + constructor(payload) { + this.enabledCalls = payload["enabled_calls"]; + this.enabledPercentage = payload["enabled_percentage"]; + this.callsPerBundle = payload["calls_per_bundle"]; + } +} + + +export class VoiceIntegrityCallsPerBundle { + /** + * Voice Integrity Approved Profile Sid. + */ + "bundleSid"?: string; + /** + * The number of Voice Integrity enabled and registered phone numbers per Bundle Sid. + */ + "enabledPhonenumbers"?: number; + /** + * The number of outbound calls on Voice Integrity enabled and registered number per Bundle Sid. + */ + "totalCalls"?: number; + /** + * Answer rate for calls on Voice Integrity enabled and registered number per Bundle Sid. + */ + "answerRate"?: number; + /** + * Rate for calls on Voice Integrity enabled and registered number per Bundle Sid that were answered by Human per each use case for Branded bundled calls. + */ + "humanAnswerRate"?: number; + + constructor(payload) { + this.bundleSid = payload["bundle_sid"]; + this.enabledPhonenumbers = payload["enabled_phonenumbers"]; + this.totalCalls = payload["total_calls"]; + this.answerRate = payload["answer_rate"]; + this.humanAnswerRate = payload["human_answer_rate"]; + } +} + + + +/** + * Options to pass to create a ReportInstance + */ +export interface ReportContextCreateOptions { + /** */ + "insightsV2CreateAccountReportRequest"?: InsightsV2CreateAccountReportRequest; +} + + +export interface ReportContext { + + /** + * Create a ReportInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance + */ + create(callback?: (error: Error | null, item?: ReportInstance) => any): Promise; + /** + * Create a ReportInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance + */ + create(params: InsightsV2CreateAccountReportRequest, headers?: any, callback?: (error: Error | null, item?: ReportInstance) => any): Promise; + + /** + * Create a ReportInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ReportInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsV2CreateAccountReportRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a ReportInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance + */ + fetch(callback?: (error: Error | null, item?: ReportInstance) => any): Promise + + /** + * Fetch a ReportInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ReportContextSolution { + "reportId": string; +} + +export class ReportContextImpl implements ReportContext { + protected _solution: ReportContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, reportId: string) { + if (!isValidPathParam(reportId)) { + throw new Error('Parameter \'reportId\' is not valid.'); + } + + this._solution = { reportId, }; + this._uri = `/Voice/Reports/${reportId}`; + } + + create(params?: InsightsV2CreateAccountReportRequest | ((error: Error | null, item?: ReportInstance) => any), headers?: any,callback?: (error: Error | null, item?: ReportInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as InsightsV2CreateAccountReportRequest; + } else { + params = params || {} as Partial as InsightsV2CreateAccountReportRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ReportInstance(operationVersion, payload, instance._solution.reportId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params?: InsightsV2CreateAccountReportRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as InsightsV2CreateAccountReportRequest; + } else { + params = params || {} as Partial as InsightsV2CreateAccountReportRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ReportInstance(operationVersion, response.body, instance._solution.reportId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ReportInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ReportInstance(operationVersion, payload, instance._solution.reportId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ReportInstance(operationVersion, response.body, instance._solution.reportId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ReportPayload extends ReportResource {} + +interface ReportResource { + account_sid: string; + report_id: string; + status: ReportStatus; + request_meta: ReportMetadata; + url: string; + handle: string; + total_calls: number; + call_answer_score: number; + call_state_percentage: InsightsV2InboundPhoneNumberReportCallStatePercentage; + silent_calls_percentage: number; + calls_by_device_type: { [key: string]: number; }; + answer_rate_device_type: { [key: string]: number; }; + blocked_calls_by_carrier: Array; + short_duration_calls_percentage: number; + long_duration_calls_percentage: number; + potential_robocalls_percentage: number; + answering_machine_detection: InsightsV2OutboundPhoneNumberReportAnsweringMachineDetection; + report: AccountReport; +} + +export class ReportInstance { + protected _solution: ReportContextSolution; + protected _context?: ReportContext; + + constructor(protected _version: V2, payload: ReportResource, reportId?: string) { + + this.accountSid = (payload.account_sid); + this.reportId = (payload.report_id); + this.status = payload.status; + this.requestMeta = payload.request_meta !== null && payload.request_meta !== undefined ? new ReportMetadata(payload.request_meta) : null; + this.url = (payload.url); + this.handle = (payload.handle); + this.totalCalls = deserialize.integer(payload.total_calls); + this.callAnswerScore = (payload.call_answer_score); + this.callStatePercentage = payload.call_state_percentage !== null && payload.call_state_percentage !== undefined ? new InsightsV2InboundPhoneNumberReportCallStatePercentage(payload.call_state_percentage) : null; + this.silentCallsPercentage = (payload.silent_calls_percentage); + this.callsByDeviceType = (payload.calls_by_device_type); + this.answerRateDeviceType = (payload.answer_rate_device_type); + this.blockedCallsByCarrier = payload.blocked_calls_by_carrier !== null && payload.blocked_calls_by_carrier !== undefined ? payload.blocked_calls_by_carrier.map( + (payload: any) => new CountyCarrierValue(payload) + ) : null; + this.shortDurationCallsPercentage = (payload.short_duration_calls_percentage); + this.longDurationCallsPercentage = (payload.long_duration_calls_percentage); + this.potentialRobocallsPercentage = (payload.potential_robocalls_percentage); + this.answeringMachineDetection = payload.answering_machine_detection !== null && payload.answering_machine_detection !== undefined ? new InsightsV2OutboundPhoneNumberReportAnsweringMachineDetection(payload.answering_machine_detection) : null; + this.report = payload.report !== null && payload.report !== undefined ? new AccountReport(payload.report) : null; + + this._solution = { reportId: reportId, }; + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The report identifier as Voice Insights Report TTID. + */ + reportId: string; + status: ReportStatus; + requestMeta: ReportMetadata; + /** + * The URL of this resource. + */ + url: string; + /** + * Inbound phone number handle represented in the report. + */ + handle: string; + /** + * Total number of calls made with the given handle during the report period. + */ + totalCalls: number; + /** + * The call answer score measures customers behavior to the delivered calls. The score is a value between 0 and 100, where 100 indicates that all calls were successfully answered. + */ + callAnswerScore: number; + callStatePercentage: InsightsV2InboundPhoneNumberReportCallStatePercentage; + /** + * Percentage of inbound calls with silence tags over total outbound calls. A silent tag is indicative of a connectivity issue or muted audio. + */ + silentCallsPercentage: number; + /** + * Number of calls made with each device type. `voip`, `mobile`, `landline`, `unknown` + */ + callsByDeviceType: { [key: string]: number; }; + /** + * Answer rate for each device type. `voip`, `mobile`, `landline`, `unknown` + */ + answerRateDeviceType: { [key: string]: number; }; + /** + * Percentage of blocked calls by carrier per country. + */ + blockedCallsByCarrier: Array; + /** + * Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + */ + shortDurationCallsPercentage: number; + /** + * Percentage of long duration calls ( >= 60 seconds) + */ + longDurationCallsPercentage: number; + /** + * Percentage of completed outbound calls to unassigned or unallocated phone numbers. + */ + potentialRobocallsPercentage: number; + answeringMachineDetection: InsightsV2OutboundPhoneNumberReportAnsweringMachineDetection; + report: AccountReport; + + private get _proxy(): ReportContext { + this._context = this._context || new ReportContextImpl(this._version, this._solution.reportId); + return this._context; + } + + /** + * Create a ReportInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance + */ + create(callback?: (error: Error | null, item?: ReportInstance) => any): Promise; + /** + * Create a ReportInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance + */ + create(params: InsightsV2CreateAccountReportRequest, headers?: any, callback?: (error: Error | null, item?: ReportInstance) => any): Promise; + + create(params?: any, callback?: (error: Error | null, item?: ReportInstance) => any): Promise + { + return this._proxy.create(params, callback); + } + + /** + * Create a ReportInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ReportInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsV2CreateAccountReportRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Fetch a ReportInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance + */ + fetch(callback?: (error: Error | null, item?: ReportInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ReportInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReportInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + reportId: this.reportId, + status: this.status, + requestMeta: this.requestMeta, + url: this.url, + handle: this.handle, + totalCalls: this.totalCalls, + callAnswerScore: this.callAnswerScore, + callStatePercentage: this.callStatePercentage, + silentCallsPercentage: this.silentCallsPercentage, + callsByDeviceType: this.callsByDeviceType, + answerRateDeviceType: this.answerRateDeviceType, + blockedCallsByCarrier: this.blockedCallsByCarrier, + shortDurationCallsPercentage: this.shortDurationCallsPercentage, + longDurationCallsPercentage: this.longDurationCallsPercentage, + potentialRobocallsPercentage: this.potentialRobocallsPercentage, + answeringMachineDetection: this.answeringMachineDetection, + report: this.report, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ReportSolution { +} + +export interface ReportListInstance { + _version: V2; + _solution: ReportSolution; + _uri: string; + + (reportId: string, ): ReportContext; + get(reportId: string, ): ReportContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ReportListInstance(version: V2): ReportListInstance { + const instance = ((reportId, ) => instance.get(reportId, )) as ReportListInstance; + + instance.get = function get(reportId, ): ReportContext { + return new ReportContextImpl(version, reportId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/insights/v3/metadata.ts b/rest/insights/v3/metadata.ts new file mode 100644 index 000000000..f86a83bc1 --- /dev/null +++ b/rest/insights/v3/metadata.ts @@ -0,0 +1,238 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * Insights Domain V3 API. Includes synchronous Query, Metadata, and Async Query (long-running operation) endpoints. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class InsightsMetadataResponseCubes { + /** + * Name of the cube, used as a reference in queries + */ + "name": string; + /** + * Human-readable description of what the cube represents + */ + "description"?: string; + /** + * List of measures available in the cube, representing quantitative values that can be aggregated + */ + "measures": Array; + /** + * List of dimensions available in the cube, representing categorical attributes for grouping data + */ + "dimensions": Array; + + constructor(payload) { + this.name = payload["name"]; + this.description = payload["description"]; + this.measures = payload["measures"]; + this.dimensions = payload["dimensions"]; + } +} + + +export class InsightsMetadataResponseCubesDimensions { + /** + * Identifier used to reference this dimension in queries + */ + "name": string; + /** + * Detailed explanation of what this dimension represents + */ + "description"?: string; + /** + * Data type of the dimension (e.g., string, number, boolean, date) + */ + "type": string; + + constructor(payload) { + this.name = payload["name"]; + this.description = payload["description"]; + this.type = payload["type"]; + } +} + + +export class InsightsMetadataResponseCubesMeasures { + /** + * Identifier used to reference this measure in queries + */ + "name": string; + /** + * Detailed explanation of what this measure represents + */ + "description"?: string; + /** + * Type of the measure + */ + "type": string; + /** + * Aggregation type for the measure (e.g., sum, count, average) + */ + "aggregation"?: string; + + constructor(payload) { + this.name = payload["name"]; + this.description = payload["description"]; + this.type = payload["type"]; + this.aggregation = payload["aggregation"]; + } +} + + + + + +export interface MetadataSolution { +} + +export interface MetadataListInstance { + _version: V3; + _solution: MetadataSolution; + _uri: string; + + + + /** + * Fetch a MetadataInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MetadataInstance + */ + fetch(callback?: (error: Error | null, item?: MetadataInstance) => any): Promise + + /** + * Fetch a MetadataInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MetadataInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MetadataListInstance(version: V3): MetadataListInstance { + const instance = {} as MetadataListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/InsightsDomains/Conversations/Metadata`; + + instance.fetch = function fetch( callback?: (error: Error | null, items: MetadataInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MetadataInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo( callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MetadataInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + + +interface MetadataResource { + domain: string; + cubes: Array; +} + +/** + * Response containing metadata about available cubes, measures, and dimensions for a domain + */ +export class MetadataInstance { + + constructor(protected _version: V3, _payload: MetadataResource) { + const payload = _payload; + this.domain = (payload.domain); + this.cubes = payload.cubes !== null && payload.cubes !== undefined ? payload.cubes.map( + (payload: any) => new InsightsMetadataResponseCubes(payload) + ) : null; + + } + + /** + * The business domain name for which metadata is being provided + */ + domain: string; + /** + * List of data cubes available in the domain, each containing measures and dimensions + */ + cubes: Array; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domain: this.domain, + cubes: this.cubes, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/insights/v3/query.ts b/rest/insights/v3/query.ts new file mode 100644 index 000000000..ec3fb1a42 --- /dev/null +++ b/rest/insights/v3/query.ts @@ -0,0 +1,418 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * Insights Domain V3 API. Includes synchronous Query, Metadata, and Async Query (long-running operation) endpoints. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class InsightsQueryRequest { + /** + * The business domain to execute the query against + */ + "domain"?: string; + "query": QueryDefinition; + + constructor(payload) { + this.domain = payload["domain"]; + this.query = payload["query"]; + } +} + + +/** + * Pagination metadata containing navigation tokens and result information, this schema should according to convention be added to the response payload\'s \'meta\' attribute + */ +export class PaginationMeta { + /** + * The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + */ + "key": string; + /** + * The actual number of items returned in this response. May be less than the requested pageSize for the last page. + */ + "pageSize": number; + /** + * Token to fetch the previous page of results. Only included if there is a previous page, otherwise omitted. + */ + "previousToken"?: string | null; + /** + * Token to fetch the next page of results. Only included if there is a next page, otherwise omitted. + */ + "nextToken"?: string | null; + + constructor(payload) { + this.key = payload["key"]; + this.pageSize = payload["pageSize"]; + this.previousToken = payload["previousToken"]; + this.nextToken = payload["nextToken"]; + } +} + + +/** + * Structured query definition that specifies what data to retrieve and how to filter, group, and order it + */ +export class QueryDefinition { + /** + * Array of measures to retrieve, representing quantitative values or metrics to be calculated + */ + "measures"?: Array; + /** + * Array of dimensions to retrieve, representing categorical attributes for grouping and organizing data + */ + "dimensions"?: Array; + /** + * Nested filter conditions. Always use `op` and `expressions`. + */ + "filters"?: Array; + /** + * Specifications for sorting the query results by specific fields in ascending or descending order + */ + "orderBy"?: Array; + + constructor(payload) { + this.measures = payload["measures"]; + this.dimensions = payload["dimensions"]; + this.filters = payload["filters"]; + this.orderBy = payload["orderBy"]; + } +} + + +export class QueryDefinitionFilters { + "op"?: string; + "expressions": Array; + + constructor(payload) { + this.op = payload["op"]; + this.expressions = payload["expressions"]; + } +} + + +export class QueryDefinitionFiltersExpressions { + "op": string; + "field": string; + "values"?: Array; + + constructor(payload) { + this.op = payload["op"]; + this.field = payload["field"]; + this.values = payload["values"]; + } +} + + +export class QueryDefinitionOrderBy { + /** + * Dimension or measure to order by + */ + "field"?: string; + /** + * Sort order direction, ascending or descending + */ + "direction"?: string; + + constructor(payload) { + this.field = payload["field"]; + this.direction = payload["direction"]; + } +} + + + +/** + * Options to pass to create a QueryInstance + */ +export interface QueryListInstanceCreateOptions { + /** */ + "insightsQueryRequest": InsightsQueryRequest; + /** Number of items per page */ + "pageSize"?: number; +} + +/** + * Options to pass to fetch a QueryInstance + */ +export interface QueryListInstanceFetchOptions { + /** Pagination token */ + "pageToken": string; +} + + +export interface QuerySolution { +} + +export interface QueryListInstance { + _version: V3; + _solution: QuerySolution; + _uri: string; + + + + /** + * Create a QueryInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryInstance + */ + create(params: InsightsQueryRequest, headers?: any, callback?: (error: Error | null, item?: QueryInstance) => any): Promise; + + /** + * Create a QueryInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsQueryRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Fetch a QueryInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryInstance + */ + fetch(params: QueryListInstanceFetchOptions, callback?: (error: Error | null, item?: QueryInstance) => any): Promise; + + /** + * Fetch a QueryInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryInstance with HTTP metadata + */ + fetchWithHttpInfo(params: QueryListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function QueryListInstance(version: V3): QueryListInstance { + const instance = {} as QueryListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/InsightsDomains/Conversations/Query`; + + instance.create = function create(params: InsightsQueryRequest, headers?: any, callback?: (error: Error | null, items: QueryInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new QueryInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InsightsQueryRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new QueryInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetch = function fetch(params: QueryListInstanceFetchOptions, callback?: (error: Error | null, items: QueryInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["pageToken"] === null || params["pageToken"] === undefined) { + throw new Error('Required parameter "params[\'pageToken\']" missing.'); + } + + let data: any = {}; + + + data["pageToken"] = params["pageToken"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new QueryInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params: QueryListInstanceFetchOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["pageToken"] === null || params["pageToken"] === undefined) { + throw new Error('Required parameter "params[\'pageToken\']" missing.'); + } + + let data: any = {}; + + + data["pageToken"] = params["pageToken"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new QueryInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + + +interface QueryResource { + domain: string; + items: Array<{ [key: string]: any; }>; + meta: PaginationMeta; +} + +export class QueryInstance { + + constructor(protected _version: V3, _payload: QueryResource) { + const payload = _payload; + this.domain = (payload.domain); + this.items = (payload.items); + this.meta = payload.meta !== null && payload.meta !== undefined ? new PaginationMeta(payload.meta) : null; + + } + + /** + * Indicates the business domain the query was executed against + */ + domain: string; + /** + * Array of result objects containing the query results. Each object contains properties matching the requested measures and dimensions. + */ + items: Array<{ [key: string]: any; }>; + meta: PaginationMeta; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domain: this.domain, + items: this.items, + meta: this.meta, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/insights/v3/queryJob.ts b/rest/insights/v3/queryJob.ts new file mode 100644 index 000000000..7398ddc93 --- /dev/null +++ b/rest/insights/v3/queryJob.ts @@ -0,0 +1,864 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * Insights Domain V3 API. Includes synchronous Query, Metadata, and Async Query (long-running operation) endpoints. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class InsightsQueryRequest { + /** + * The business domain to execute the query against + */ + "domain"?: string; + "query": QueryDefinition; + + constructor(payload) { + this.domain = payload["domain"]; + this.query = payload["query"]; + } +} + + +/** + * Valid status values for long-running operations. + */ +export type LongRunningOperationStatus = 'PENDING'|'RUNNING'|'CANCELLED'|'COMPLETED'|'FAILED'; + +/** + * Error details for a failed operation, embedded inside a 200 OK operation envelope. + */ +export class OperationError { + /** + * Twilio-specific error code + */ + "code": number; + /** + * A human readable error message + */ + "message": string; + /** + * HTTP status code that would have been returned for a synchronous failure + */ + "httpStatusCode": number; + /** + * Additional context about the failure + */ + "detail"?: string | null; + + constructor(payload) { + this.code = payload["code"]; + this.message = payload["message"]; + this.httpStatusCode = payload["httpStatusCode"]; + this.detail = payload["detail"]; + } +} + + +/** + * Structured query definition that specifies what data to retrieve and how to filter, group, and order it + */ +export class QueryDefinition { + /** + * Array of measures to retrieve, representing quantitative values or metrics to be calculated + */ + "measures"?: Array; + /** + * Array of dimensions to retrieve, representing categorical attributes for grouping and organizing data + */ + "dimensions"?: Array; + /** + * Nested filter conditions. Always use `op` and `expressions`. + */ + "filters"?: Array; + /** + * Specifications for sorting the query results by specific fields in ascending or descending order + */ + "orderBy"?: Array; + + constructor(payload) { + this.measures = payload["measures"]; + this.dimensions = payload["dimensions"]; + this.filters = payload["filters"]; + this.orderBy = payload["orderBy"]; + } +} + + +export class QueryDefinitionFilters { + "op"?: string; + "expressions": Array; + + constructor(payload) { + this.op = payload["op"]; + this.expressions = payload["expressions"]; + } +} + + +export class QueryDefinitionFiltersExpressions { + "op": string; + "field": string; + "values"?: Array; + + constructor(payload) { + this.op = payload["op"]; + this.field = payload["field"]; + this.values = payload["values"]; + } +} + + +export class QueryDefinitionOrderBy { + /** + * Dimension or measure to order by + */ + "field"?: string; + /** + * Sort order direction, ascending or descending + */ + "direction"?: string; + + constructor(payload) { + this.field = payload["field"]; + this.direction = payload["direction"]; + } +} + + + + +/** + * Options to pass to create a QueryJobInstance + */ +export interface QueryJobListInstanceCreateOptions { + /** */ + "insightsQueryRequest": InsightsQueryRequest; + /** Client-generated UUIDv7 key to ensure idempotent behavior. Submitting the same key for identical requests returns the same operation without re-execution. Scoped to Account + Region. Retained for 24 hours. */ + "idempotencyKey"?: string; +} + +/** + * Options to pass to each + */ +export interface QueryJobListInstanceEachOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Filter by operation status. */ + "status"?: LongRunningOperationStatus; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: QueryJobInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface QueryJobListInstanceOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Filter by operation status. */ + "status"?: LongRunningOperationStatus; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface QueryJobListInstancePageOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Filter by operation status. */ + "status"?: LongRunningOperationStatus; +} + + +export interface QueryJobContext { + + /** + * Fetch a QueryJobInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryJobInstance + */ + fetch(callback?: (error: Error | null, item?: QueryJobInstance) => any): Promise + + /** + * Fetch a QueryJobInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryJobInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface QueryJobContextSolution { + "operationId": string; +} + +export class QueryJobContextImpl implements QueryJobContext { + protected _solution: QueryJobContextSolution; + protected _uri: string; + + + constructor(protected _version: V3, operationId: string) { + if (!isValidPathParam(operationId)) { + throw new Error('Parameter \'operationId\' is not valid.'); + } + + this._solution = { operationId, }; + this._uri = `/InsightsDomains/Conversations/QueryJobs/${operationId}`; + } + + fetch(callback?: (error: Error | null, item?: QueryJobInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new QueryJobInstance(operationVersion, payload, instance._solution.operationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new QueryJobInstance(operationVersion, response.body, instance._solution.operationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for InsightsQueryRequest + */ +export interface InsightsQueryRequest { + domain?: string; + query: QueryDefinition; +} + +/** + * Nested model for OperationError + */ +export interface OperationError { + code: number; + message: string; + httpStatusCode: number; + detail?: string; +} + +/** + * Nested model for QueryDefinition + */ +export interface QueryDefinition { + measures?: Array; + dimensions?: Array; + filters?: Array; + orderBy?: Array; +} + +/** + * Nested model for QueryDefinitionFilters + */ +export interface QueryDefinitionFilters { + op?: string; + expressions: Array; +} + +/** + * Nested model for QueryDefinitionFiltersExpressions + */ +export interface QueryDefinitionFiltersExpressions { + op: string; + field: string; + values?: Array; +} + +/** + * Nested model for QueryDefinitionOrderBy + */ +export interface QueryDefinitionOrderBy { + field?: string; + direction?: string; +} + + + + interface QueryJobPayload extends TokenPaginationPayload { + items: QueryJobResource[]; +} + +/** + * Response model for QueryJobSubmitResponse operations + */ +interface QueryJobSubmitResponse_ResponseResource { + operationId: string; + status: LongRunningOperationStatus; + statusUrl: string; + createdAt: Date; +} + +/** + * Response model for QueryJobStatusResponse operations + */ +interface QueryJobStatusResponse_ResponseResource { + operationId: string; + status: LongRunningOperationStatus; + statusUrl?: string; + createdAt: Date; + completedAt?: Date; + error?: OperationError; + resultUrl?: string; + resultRetentionPeriod?: string; +} + +/** + * Union type for all possible response models + */ +type QueryJobResource = QueryJobSubmitResponse_ResponseResource | QueryJobStatusResponse_ResponseResource; + +/** + * Initial 202 response for an async query submission. Conforms to LongRunningOperation202Response from Twilio API Standards. + */ +export class QueryJobInstance { + protected _solution: QueryJobContextSolution; + protected _context?: QueryJobContext; + + constructor(protected _version: V3, _payload: QueryJobResource, operationId?: string) { + const payload: any = _payload; + this.operationId = (payload.operationId); + this.status = payload.status; + this.statusUrl = (payload.statusUrl); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.completedAt = deserialize.iso8601DateTime(payload.completedAt); + this.error = payload.error !== null && payload.error !== undefined ? new OperationError(payload.error) : null; + this.resultUrl = (payload.resultUrl); + this.resultRetentionPeriod = (payload.resultRetentionPeriod); + + this._solution = { operationId: operationId, }; + } + + /** + * Unique identifier for the async query operation. + */ + operationId?: string; + status?: LongRunningOperationStatus; + /** + * URI to poll for operation status. + */ + statusUrl?: string; + /** + * When the operation was accepted (RFC 3339 UTC). + */ + createdAt?: Date; + /** + * When the operation reached a terminal state. + */ + completedAt?: Date; + /** + * Error details. Present only when status is FAILED. + */ + error?: OperationError; + /** + * URL to retrieve query results. Present only when status is COMPLETED. Supports pagination via pageSize and pageToken query parameters. + */ + resultUrl?: string; + /** + * ISO 8601 duration for how long results are retained. + */ + resultRetentionPeriod?: string; + + private get _proxy(): QueryJobContext { + this._context = this._context || new QueryJobContextImpl(this._version, this._solution.operationId); + return this._context; + } + + /** + * Fetch a QueryJobInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryJobInstance + */ + fetch(callback?: (error: Error | null, item?: QueryJobInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a QueryJobInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryJobInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + operationId: this.operationId, + status: this.status, + statusUrl: this.statusUrl, + createdAt: this.createdAt, + completedAt: this.completedAt, + error: this.error, + resultUrl: this.resultUrl, + resultRetentionPeriod: this.resultRetentionPeriod, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface QueryJobSolution { +} + +export interface QueryJobListInstance { + _version: V3; + _solution: QueryJobSolution; + _uri: string; + + (operationId: string, ): QueryJobContext; + get(operationId: string, ): QueryJobContext; + + + + + /** + * Create a QueryJobInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryJobInstance + */ + create(params: InsightsQueryRequest, headers?: any, callback?: (error: Error | null, item?: QueryJobInstance) => any): Promise; + + /** + * Create a QueryJobInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryJobInstance with HTTP metadata + */ + createWithHttpInfo(params: InsightsQueryRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams QueryJobInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueryJobListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: QueryJobInstance, done: (err?: Error) => void) => void): void; + each(params: QueryJobListInstanceEachOptions, callback?: (item: QueryJobInstance, done: (err?: Error) => void) => void): void; + /** + * Streams QueryJobInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueryJobListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: QueryJobInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: QueryJobListInstanceEachOptions, callback?: (item: QueryJobInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of QueryJobInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: QueryJobPage) => any): Promise; + /** + * Retrieve a single target page of QueryJobInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists QueryJobInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueryJobListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: QueryJobInstance[]) => any): Promise; + list(params: QueryJobListInstanceOptions, callback?: (error: Error | null, items: QueryJobInstance[]) => any): Promise; + /** + * Lists QueryJobInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueryJobListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: QueryJobListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of QueryJobInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueryJobListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: QueryJobPage) => any): Promise; + page(params: QueryJobListInstancePageOptions, callback?: (error: Error | null, items: QueryJobPage) => any): Promise; + /** + * Retrieve a single page of QueryJobInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { QueryJobListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: QueryJobListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function QueryJobListInstance(version: V3): QueryJobListInstance { + const instance = ((operationId, ) => instance.get(operationId, )) as QueryJobListInstance; + + instance.get = function get(operationId, ): QueryJobContext { + return new QueryJobContextImpl(version, operationId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/InsightsDomains/Conversations/QueryJobs`; + + instance.create = function create(params: InsightsQueryRequest, headers?: any, callback?: (error: Error | null, items: QueryJobInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new QueryJobInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InsightsQueryRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new QueryJobInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: QueryJobListInstancePageOptions | ((error: Error | null, items: QueryJobPage) => any), callback?: (error: Error | null, items: QueryJobPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["status"] !== undefined) + data["status"] = params["status"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new QueryJobPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: QueryJobPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new QueryJobPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: QueryJobListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["status"] !== undefined) + data["status"] = params["status"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new QueryJobPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new QueryJobPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class QueryJobPage extends TokenPage { +/** +* Initialize the QueryJobPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V3, response: Response, uri: string, params: any, solution: QueryJobSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of QueryJobInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: QueryJobResource): QueryJobInstance { + + return new QueryJobInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/insights/v3/result.ts b/rest/insights/v3/result.ts new file mode 100644 index 000000000..0ec13da38 --- /dev/null +++ b/rest/insights/v3/result.ts @@ -0,0 +1,259 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Insights + * Insights Domain V3 API. Includes synchronous Query, Metadata, and Async Query (long-running operation) endpoints. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Pagination metadata containing navigation tokens and result information, this schema should according to convention be added to the response payload\'s \'meta\' attribute + */ +export class PaginationMeta { + /** + * The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + */ + "key": string; + /** + * The actual number of items returned in this response. May be less than the requested pageSize for the last page. + */ + "pageSize": number; + /** + * Token to fetch the previous page of results. Only included if there is a previous page, otherwise omitted. + */ + "previousToken"?: string | null; + /** + * Token to fetch the next page of results. Only included if there is a next page, otherwise omitted. + */ + "nextToken"?: string | null; + + constructor(payload) { + this.key = payload["key"]; + this.pageSize = payload["pageSize"]; + this.previousToken = payload["previousToken"]; + this.nextToken = payload["nextToken"]; + } +} + + + +/** + * Options to pass to fetch a ResultInstance + */ +export interface ResultListInstanceFetchOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; +} + + +export interface ResultSolution { + operationId: string; +} + +export interface ResultListInstance { + _version: V3; + _solution: ResultSolution; + _uri: string; + + + + /** + * Fetch a ResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ResultInstance + */ + fetch(callback?: (error: Error | null, item?: ResultInstance) => any): Promise; + /** + * Fetch a ResultInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ResultInstance + */ + fetch(params: ResultListInstanceFetchOptions, callback?: (error: Error | null, item?: ResultInstance) => any): Promise; + + /** + * Fetch a ResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ResultInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a ResultInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ResultInstance with HTTP metadata + */ + fetchWithHttpInfo(params: ResultListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ResultListInstance(version: V3, operationId: string): ResultListInstance { + if (!isValidPathParam(operationId)) { + throw new Error('Parameter \'operationId\' is not valid.'); + } + + const instance = {} as ResultListInstance; + + instance._version = version; + instance._solution = { operationId, }; + instance._uri = `/InsightsDomains/Conversations/QueryJobs/${operationId}/Results`; + + instance.fetch = function fetch(params?: ResultListInstanceFetchOptions | ((error: Error | null, items: ResultInstance) => any), callback?: (error: Error | null, items: ResultInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new ResultInstance(operationVersion, payload, instance._solution.operationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params?: ResultListInstanceFetchOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ResultInstance(operationVersion, response.body, instance._solution.operationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + + +interface ResultResource { + domain: string; + items: Array<{ [key: string]: any; }>; + meta: PaginationMeta; +} + +export class ResultInstance { + + constructor(protected _version: V3, _payload: ResultResource, operationId: string) { + const payload = _payload; + this.domain = (payload.domain); + this.items = (payload.items); + this.meta = payload.meta !== null && payload.meta !== undefined ? new PaginationMeta(payload.meta) : null; + + } + + /** + * Indicates the business domain the query was executed against + */ + domain: string; + /** + * Array of result objects containing the query results. Each object contains properties matching the requested measures and dimensions. + */ + items: Array<{ [key: string]: any; }>; + meta: PaginationMeta; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domain: this.domain, + items: this.items, + meta: this.meta, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/intelligence/V2.ts b/rest/intelligence/V2.ts new file mode 100644 index 000000000..22cb5a718 --- /dev/null +++ b/rest/intelligence/V2.ts @@ -0,0 +1,101 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import IntelligenceBase from "../IntelligenceBase"; +import Version from "../../base/Version"; +import { CustomOperatorListInstance } from "./v2/customOperator"; +import { OperatorListInstance } from "./v2/operator"; +import { OperatorAttachmentListInstance } from "./v2/operatorAttachment"; +import { OperatorAttachmentsListInstance } from "./v2/operatorAttachments"; +import { OperatorTypeListInstance } from "./v2/operatorType"; +import { PrebuiltOperatorListInstance } from "./v2/prebuiltOperator"; +import { ServiceListInstance } from "./v2/service"; +import { TranscriptListInstance } from "./v2/transcript"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Intelligence + * + * @param domain - The Twilio (Twilio.Intelligence) domain + */ + constructor(domain: IntelligenceBase) { + super(domain, "v2"); + } + + /** customOperators - { Twilio.Intelligence.V2.CustomOperatorListInstance } resource */ + protected _customOperators?: CustomOperatorListInstance; + /** operators - { Twilio.Intelligence.V2.OperatorListInstance } resource */ + protected _operators?: OperatorListInstance; + /** operatorAttachment - { Twilio.Intelligence.V2.OperatorAttachmentListInstance } resource */ + protected _operatorAttachment?: OperatorAttachmentListInstance; + /** operatorAttachments - { Twilio.Intelligence.V2.OperatorAttachmentsListInstance } resource */ + protected _operatorAttachments?: OperatorAttachmentsListInstance; + /** operatorType - { Twilio.Intelligence.V2.OperatorTypeListInstance } resource */ + protected _operatorType?: OperatorTypeListInstance; + /** prebuiltOperators - { Twilio.Intelligence.V2.PrebuiltOperatorListInstance } resource */ + protected _prebuiltOperators?: PrebuiltOperatorListInstance; + /** services - { Twilio.Intelligence.V2.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + /** transcripts - { Twilio.Intelligence.V2.TranscriptListInstance } resource */ + protected _transcripts?: TranscriptListInstance; + + /** Getter for customOperators resource */ + get customOperators(): CustomOperatorListInstance { + this._customOperators = this._customOperators || CustomOperatorListInstance(this); + return this._customOperators; + } + + /** Getter for operators resource */ + get operators(): OperatorListInstance { + this._operators = this._operators || OperatorListInstance(this); + return this._operators; + } + + /** Getter for operatorAttachment resource */ + get operatorAttachment(): OperatorAttachmentListInstance { + this._operatorAttachment = this._operatorAttachment || OperatorAttachmentListInstance(this); + return this._operatorAttachment; + } + + /** Getter for operatorAttachments resource */ + get operatorAttachments(): OperatorAttachmentsListInstance { + this._operatorAttachments = this._operatorAttachments || OperatorAttachmentsListInstance(this); + return this._operatorAttachments; + } + + /** Getter for operatorType resource */ + get operatorType(): OperatorTypeListInstance { + this._operatorType = this._operatorType || OperatorTypeListInstance(this); + return this._operatorType; + } + + /** Getter for prebuiltOperators resource */ + get prebuiltOperators(): PrebuiltOperatorListInstance { + this._prebuiltOperators = this._prebuiltOperators || PrebuiltOperatorListInstance(this); + return this._prebuiltOperators; + } + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + + /** Getter for transcripts resource */ + get transcripts(): TranscriptListInstance { + this._transcripts = this._transcripts || TranscriptListInstance(this); + return this._transcripts; + } + +} diff --git a/rest/intelligence/V3.ts b/rest/intelligence/V3.ts new file mode 100644 index 000000000..5ced42f24 --- /dev/null +++ b/rest/intelligence/V3.ts @@ -0,0 +1,88 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Conversational Intelligence API + * The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import IntelligenceBase from "../IntelligenceBase"; +import Version from "../../base/Version"; +import { ConfigurationListInstance } from "./v3/configuration"; +import { ConversationListInstance } from "./v3/conversation"; +import { OperatorListInstance } from "./v3/operator"; +import { OperatorResultListInstance } from "./v3/operatorResult"; +import { RuleExecutionListInstance } from "./v3/ruleExecution"; +import { VersionListInstance, VersionContext } from "./v3/version"; + +export default class V3 extends Version { + /** + * Initialize the V3 version of Intelligence + * + * @param domain - The Twilio (Twilio.Intelligence) domain + */ + constructor(domain: IntelligenceBase) { + super(domain, "v3"); + } + + /** configurations - { Twilio.Intelligence.V3.ConfigurationListInstance } resource */ + protected _configurations?: ConfigurationListInstance; + /** conversations - { Twilio.Intelligence.V3.ConversationListInstance } resource */ + protected _conversations?: ConversationListInstance; + /** operators - { Twilio.Intelligence.V3.OperatorListInstance } resource */ + protected _operators?: OperatorListInstance; + /** operatorResults - { Twilio.Intelligence.V3.OperatorResultListInstance } resource */ + protected _operatorResults?: OperatorResultListInstance; + /** ruleExecutions - { Twilio.Intelligence.V3.RuleExecutionListInstance } resource */ + protected _ruleExecutions?: RuleExecutionListInstance; + + /** Getter for configurations resource */ + get configurations(): ConfigurationListInstance { + this._configurations = this._configurations || ConfigurationListInstance(this); + return this._configurations; + } + + /** Getter for conversations resource */ + get conversations(): ConversationListInstance { + this._conversations = this._conversations || ConversationListInstance(this); + return this._conversations; + } + + /** Getter for operators resource */ + get operators(): OperatorListInstance { + this._operators = this._operators || OperatorListInstance(this); + return this._operators; + } + + /** Getter for operatorResults resource */ + get operatorResults(): OperatorResultListInstance { + this._operatorResults = this._operatorResults || OperatorResultListInstance(this); + return this._operatorResults; + } + + /** Getter for ruleExecutions resource */ + get ruleExecutions(): RuleExecutionListInstance { + this._ruleExecutions = this._ruleExecutions || RuleExecutionListInstance(this); + return this._ruleExecutions; + } + + /** Accessor for versions resource - list operations */ + versions(id: string): VersionListInstance; + /** Accessor for versions resource - instance operations */ + versions(id: string, version: number): VersionContext; + /** Implementation */ + versions(id: string, version?: number): VersionListInstance | VersionContext { + const listInstance = VersionListInstance(this, id); + if (version !== undefined) { + return listInstance.get(version); + } + return listInstance; + } + +} diff --git a/rest/intelligence/v2/customOperator.ts b/rest/intelligence/v2/customOperator.ts new file mode 100644 index 000000000..7965418c1 --- /dev/null +++ b/rest/intelligence/v2/customOperator.ts @@ -0,0 +1,969 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Custom Operator availability status. Possible values: internal, beta, public, retired. + */ +export type CustomOperatorAvailability = 'internal'|'beta'|'public'|'retired'|'general-availability'|'deprecated'; + + + + +/** + * Options to pass to update a CustomOperatorInstance + */ +export interface CustomOperatorContextUpdateOptions { + /** A human-readable name of this resource, up to 64 characters. */ + "friendlyName": string; + /** Operator configuration, following the schema defined by the Operator Type. */ + "config": any; + /** The If-Match HTTP request header */ + "ifMatch"?: string; +} + +/** + * Options to pass to create a CustomOperatorInstance + */ +export interface CustomOperatorListInstanceCreateOptions { + /** A human readable description of the new Operator, up to 64 characters. */ + "friendlyName": string; + /** Operator Type for this Operator. References an existing Operator Type resource. */ + "operatorType": string; + /** Operator configuration, following the schema defined by the Operator Type. */ + "config": any; +} + +/** + * Options to pass to each + */ +export interface CustomOperatorListInstanceEachOptions { + /** Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. */ + "availability"?: CustomOperatorAvailability; + /** Returns Custom Operators that support the provided language code. */ + "languageCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CustomOperatorInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CustomOperatorListInstanceOptions { + /** Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. */ + "availability"?: CustomOperatorAvailability; + /** Returns Custom Operators that support the provided language code. */ + "languageCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CustomOperatorListInstancePageOptions { + /** Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. */ + "availability"?: CustomOperatorAvailability; + /** Returns Custom Operators that support the provided language code. */ + "languageCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CustomOperatorContext { + + /** + * Remove a CustomOperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a CustomOperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a CustomOperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomOperatorInstance + */ + fetch(callback?: (error: Error | null, item?: CustomOperatorInstance) => any): Promise + + /** + * Fetch a CustomOperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomOperatorInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a CustomOperatorInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomOperatorInstance + */ + update(params: CustomOperatorContextUpdateOptions, callback?: (error: Error | null, item?: CustomOperatorInstance) => any): Promise; + + /** + * Update a CustomOperatorInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomOperatorInstance with HTTP metadata + */ + updateWithHttpInfo(params: CustomOperatorContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CustomOperatorContextSolution { + "sid": string; +} + +export class CustomOperatorContextImpl implements CustomOperatorContext { + protected _solution: CustomOperatorContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Operators/Custom/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CustomOperatorInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CustomOperatorInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CustomOperatorInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: CustomOperatorContextUpdateOptions,callback?: (error: Error | null, item?: CustomOperatorInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["config"] === null || params["config"] === undefined) { + throw new Error('Required parameter "params[\'config\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Config"] = serialize.object(params["config"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CustomOperatorInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: CustomOperatorContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["config"] === null || params["config"] === undefined) { + throw new Error('Required parameter "params[\'config\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Config"] = serialize.object(params["config"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CustomOperatorInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CustomOperatorPayload extends TwilioResponsePayload { + operators: CustomOperatorResource[]; +} + +interface CustomOperatorResource { + account_sid: string; + sid: string; + friendly_name: string; + description: string; + author: string; + operator_type: string; + version: number; + availability: CustomOperatorAvailability; + config: any; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CustomOperatorInstance { + protected _solution: CustomOperatorContextSolution; + protected _context?: CustomOperatorContext; + + constructor(protected _version: V2, payload: CustomOperatorResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.author = (payload.author); + this.operatorType = (payload.operator_type); + this.version = deserialize.integer(payload.version); + this.availability = payload.availability; + this.config = (payload.config); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique SID identifier of the Account the Custom Operator belongs to. + */ + accountSid: string; + /** + * A 34 character string that uniquely identifies this Custom Operator. + */ + sid: string; + /** + * A human-readable name of this resource, up to 64 characters. + */ + friendlyName: string; + /** + * A human-readable description of this resource, longer than the friendly name. + */ + description: string; + /** + * The creator of the Custom Operator. Custom Operators can only be created by a Twilio Account. + */ + author: string; + /** + * Operator Type for this Operator. References an existing Operator Type resource. + */ + operatorType: string; + /** + * Numeric Custom Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Custom Operator. + */ + version: number; + availability: CustomOperatorAvailability; + /** + * Operator configuration, following the schema defined by the Operator Type. Only available on Operators created by the Account. + */ + config: any; + /** + * The date that this Custom Operator was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Custom Operator was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): CustomOperatorContext { + this._context = this._context || new CustomOperatorContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CustomOperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CustomOperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CustomOperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomOperatorInstance + */ + fetch(callback?: (error: Error | null, item?: CustomOperatorInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CustomOperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomOperatorInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CustomOperatorInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomOperatorInstance + */ + update(params: CustomOperatorContextUpdateOptions, callback?: (error: Error | null, item?: CustomOperatorInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: CustomOperatorInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a CustomOperatorInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomOperatorInstance with HTTP metadata + */ + updateWithHttpInfo(params: CustomOperatorContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + friendlyName: this.friendlyName, + description: this.description, + author: this.author, + operatorType: this.operatorType, + version: this.version, + availability: this.availability, + config: this.config, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CustomOperatorSolution { +} + +export interface CustomOperatorListInstance { + _version: V2; + _solution: CustomOperatorSolution; + _uri: string; + + (sid: string, ): CustomOperatorContext; + get(sid: string, ): CustomOperatorContext; + + + + + + + + + /** + * Create a CustomOperatorInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomOperatorInstance + */ + create(params: CustomOperatorListInstanceCreateOptions, callback?: (error: Error | null, item?: CustomOperatorInstance) => any): Promise; + + /** + * Create a CustomOperatorInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomOperatorInstance with HTTP metadata + */ + createWithHttpInfo(params: CustomOperatorListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CustomOperatorInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomOperatorListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CustomOperatorInstance, done: (err?: Error) => void) => void): void; + each(params: CustomOperatorListInstanceEachOptions, callback?: (item: CustomOperatorInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CustomOperatorInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomOperatorListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CustomOperatorInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CustomOperatorListInstanceEachOptions, callback?: (item: CustomOperatorInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CustomOperatorInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CustomOperatorPage) => any): Promise; + /** + * Retrieve a single target page of CustomOperatorInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CustomOperatorInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomOperatorListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CustomOperatorInstance[]) => any): Promise; + list(params: CustomOperatorListInstanceOptions, callback?: (error: Error | null, items: CustomOperatorInstance[]) => any): Promise; + /** + * Lists CustomOperatorInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomOperatorListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CustomOperatorListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CustomOperatorInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomOperatorListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CustomOperatorPage) => any): Promise; + page(params: CustomOperatorListInstancePageOptions, callback?: (error: Error | null, items: CustomOperatorPage) => any): Promise; + /** + * Retrieve a single page of CustomOperatorInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomOperatorListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CustomOperatorListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CustomOperatorListInstance(version: V2): CustomOperatorListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CustomOperatorListInstance; + + instance.get = function get(sid, ): CustomOperatorContext { + return new CustomOperatorContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Operators/Custom`; + + instance.create = function create(params: CustomOperatorListInstanceCreateOptions, callback?: (error: Error | null, items: CustomOperatorInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["operatorType"] === null || params["operatorType"] === undefined) { + throw new Error('Required parameter "params[\'operatorType\']" missing.'); + } + + if (params["config"] === null || params["config"] === undefined) { + throw new Error('Required parameter "params[\'config\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["OperatorType"] = params["operatorType"]; + + data["Config"] = serialize.object(params["config"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CustomOperatorInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CustomOperatorListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["operatorType"] === null || params["operatorType"] === undefined) { + throw new Error('Required parameter "params[\'operatorType\']" missing.'); + } + + if (params["config"] === null || params["config"] === undefined) { + throw new Error('Required parameter "params[\'config\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["OperatorType"] = params["operatorType"]; + + data["Config"] = serialize.object(params["config"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CustomOperatorInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CustomOperatorListInstancePageOptions | ((error: Error | null, items: CustomOperatorPage) => any), callback?: (error: Error | null, items: CustomOperatorPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["availability"] !== undefined) + data["Availability"] = params["availability"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CustomOperatorPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CustomOperatorPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CustomOperatorPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CustomOperatorListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["availability"] !== undefined) + data["Availability"] = params["availability"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CustomOperatorPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CustomOperatorPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CustomOperatorPage extends Page { +/** +* Initialize the CustomOperatorPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: CustomOperatorSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CustomOperatorInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CustomOperatorResource): CustomOperatorInstance { + + return new CustomOperatorInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v2/operator.ts b/rest/intelligence/v2/operator.ts new file mode 100644 index 000000000..b075a636d --- /dev/null +++ b/rest/intelligence/v2/operator.ts @@ -0,0 +1,615 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Operator availability status. Possible values: internal, beta, public, retired. + */ +export type OperatorAvailability = 'internal'|'beta'|'public'|'deprecated'|'general-availability'|'retired'; + + + +/** + * Options to pass to each + */ +export interface OperatorListInstanceEachOptions { + /** Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. */ + "availability"?: OperatorAvailability; + /** Returns Operators that support the provided language code. */ + "languageCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: OperatorInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface OperatorListInstanceOptions { + /** Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. */ + "availability"?: OperatorAvailability; + /** Returns Operators that support the provided language code. */ + "languageCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface OperatorListInstancePageOptions { + /** Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. */ + "availability"?: OperatorAvailability; + /** Returns Operators that support the provided language code. */ + "languageCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface OperatorContext { + + /** + * Fetch a OperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorInstance) => any): Promise + + /** + * Fetch a OperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OperatorContextSolution { + "sid": string; +} + +export class OperatorContextImpl implements OperatorContext { + protected _solution: OperatorContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Operators/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: OperatorInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OperatorInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new OperatorInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface OperatorPayload extends TwilioResponsePayload { + operators: OperatorResource[]; +} + +interface OperatorResource { + account_sid: string; + sid: string; + friendly_name: string; + description: string; + author: string; + operator_type: string; + version: number; + availability: OperatorAvailability; + config: any; + date_created: Date; + date_updated: Date; + url: string; +} + +export class OperatorInstance { + protected _solution: OperatorContextSolution; + protected _context?: OperatorContext; + + constructor(protected _version: V2, payload: OperatorResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.author = (payload.author); + this.operatorType = (payload.operator_type); + this.version = deserialize.integer(payload.version); + this.availability = payload.availability; + this.config = (payload.config); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique SID identifier of the Account the Operator belongs to. + */ + accountSid: string; + /** + * A 34 character string that uniquely identifies this Operator. + */ + sid: string; + /** + * A human-readable name of this resource, up to 64 characters. + */ + friendlyName: string; + /** + * A human-readable description of this resource, longer than the friendly name. + */ + description: string; + /** + * The creator of the Operator. Either Twilio or the creating Account. + */ + author: string; + /** + * Operator Type for this Operator. References an existing Operator Type resource. + */ + operatorType: string; + /** + * Numeric Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Operator. + */ + version: number; + availability: OperatorAvailability; + /** + * Operator configuration, following the schema defined by the Operator Type. Only available on Custom Operators created by the Account. + */ + config: any; + /** + * The date that this Operator was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Operator was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): OperatorContext { + this._context = this._context || new OperatorContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a OperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a OperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + friendlyName: this.friendlyName, + description: this.description, + author: this.author, + operatorType: this.operatorType, + version: this.version, + availability: this.availability, + config: this.config, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OperatorSolution { +} + +export interface OperatorListInstance { + _version: V2; + _solution: OperatorSolution; + _uri: string; + + (sid: string, ): OperatorContext; + get(sid: string, ): OperatorContext; + + + + + + /** + * Streams OperatorInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: OperatorInstance, done: (err?: Error) => void) => void): void; + each(params: OperatorListInstanceEachOptions, callback?: (item: OperatorInstance, done: (err?: Error) => void) => void): void; + /** + * Streams OperatorInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: OperatorInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: OperatorListInstanceEachOptions, callback?: (item: OperatorInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of OperatorInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: OperatorPage) => any): Promise; + /** + * Retrieve a single target page of OperatorInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists OperatorInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: OperatorInstance[]) => any): Promise; + list(params: OperatorListInstanceOptions, callback?: (error: Error | null, items: OperatorInstance[]) => any): Promise; + /** + * Lists OperatorInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: OperatorListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of OperatorInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: OperatorPage) => any): Promise; + page(params: OperatorListInstancePageOptions, callback?: (error: Error | null, items: OperatorPage) => any): Promise; + /** + * Retrieve a single page of OperatorInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: OperatorListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OperatorListInstance(version: V2): OperatorListInstance { + const instance = ((sid, ) => instance.get(sid, )) as OperatorListInstance; + + instance.get = function get(sid, ): OperatorContext { + return new OperatorContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Operators`; + + instance.page = function page(params?: OperatorListInstancePageOptions | ((error: Error | null, items: OperatorPage) => any), callback?: (error: Error | null, items: OperatorPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["availability"] !== undefined) + data["Availability"] = params["availability"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new OperatorPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: OperatorPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new OperatorPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: OperatorListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["availability"] !== undefined) + data["Availability"] = params["availability"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OperatorPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OperatorPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class OperatorPage extends Page { +/** +* Initialize the OperatorPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: OperatorSolution) { + super(version, response, solution); + } + + /** + * Build an instance of OperatorInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: OperatorResource): OperatorInstance { + + return new OperatorInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v2/operatorAttachment.ts b/rest/intelligence/v2/operatorAttachment.ts new file mode 100644 index 000000000..307de7261 --- /dev/null +++ b/rest/intelligence/v2/operatorAttachment.ts @@ -0,0 +1,331 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface OperatorAttachmentContext { + + /** + * Create a OperatorAttachmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorAttachmentInstance + */ + create(callback?: (error: Error | null, item?: OperatorAttachmentInstance) => any): Promise + + /** + * Create a OperatorAttachmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorAttachmentInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Remove a OperatorAttachmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a OperatorAttachmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OperatorAttachmentContextSolution { + "serviceSid": string; + "operatorSid": string; +} + +export class OperatorAttachmentContextImpl implements OperatorAttachmentContext { + protected _solution: OperatorAttachmentContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, operatorSid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(operatorSid)) { + throw new Error('Parameter \'operatorSid\' is not valid.'); + } + + this._solution = { serviceSid, operatorSid, }; + this._uri = `/Services/${serviceSid}/Operators/${operatorSid}`; + } + + create(callback?: (error: Error | null, item?: OperatorAttachmentInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new OperatorAttachmentInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.operatorSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse => ({ + ...response, + body: new OperatorAttachmentInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.operatorSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface OperatorAttachmentPayload extends OperatorAttachmentResource {} + +interface OperatorAttachmentResource { + service_sid: string; + operator_sid: string; + url: string; +} + +export class OperatorAttachmentInstance { + protected _solution: OperatorAttachmentContextSolution; + protected _context?: OperatorAttachmentContext; + + constructor(protected _version: V2, payload: OperatorAttachmentResource, serviceSid?: string, operatorSid?: string) { + + this.serviceSid = (payload.service_sid); + this.operatorSid = (payload.operator_sid); + this.url = (payload.url); + + this._solution = { serviceSid: serviceSid, operatorSid: operatorSid, }; + } + + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The unique SID identifier of the Operator. + */ + operatorSid: string; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): OperatorAttachmentContext { + this._context = this._context || new OperatorAttachmentContextImpl(this._version, this._solution.serviceSid, this._solution.operatorSid); + return this._context; + } + + /** + * Create a OperatorAttachmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorAttachmentInstance + */ + create(callback?: (error: Error | null, item?: OperatorAttachmentInstance) => any): Promise + + { + return this._proxy.create(callback); + } + + /** + * Create a OperatorAttachmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorAttachmentInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.createWithHttpInfo(callback); + } + + /** + * Remove a OperatorAttachmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a OperatorAttachmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + serviceSid: this.serviceSid, + operatorSid: this.operatorSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OperatorAttachmentSolution { +} + +export interface OperatorAttachmentListInstance { + _version: V2; + _solution: OperatorAttachmentSolution; + _uri: string; + + (serviceSid: string, operatorSid: string, ): OperatorAttachmentContext; + get(serviceSid: string, operatorSid: string, ): OperatorAttachmentContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OperatorAttachmentListInstance(version: V2): OperatorAttachmentListInstance { + const instance = ((serviceSid, operatorSid, ) => instance.get(serviceSid, operatorSid, )) as OperatorAttachmentListInstance; + + instance.get = function get(serviceSid, operatorSid, ): OperatorAttachmentContext { + return new OperatorAttachmentContextImpl(version, serviceSid, operatorSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/intelligence/v2/operatorAttachments.ts b/rest/intelligence/v2/operatorAttachments.ts new file mode 100644 index 000000000..5e2fbde1d --- /dev/null +++ b/rest/intelligence/v2/operatorAttachments.ts @@ -0,0 +1,248 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +export interface OperatorAttachmentsContext { + + /** + * Fetch a OperatorAttachmentsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorAttachmentsInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorAttachmentsInstance) => any): Promise + + /** + * Fetch a OperatorAttachmentsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorAttachmentsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OperatorAttachmentsContextSolution { + "serviceSid": string; +} + +export class OperatorAttachmentsContextImpl implements OperatorAttachmentsContext { + protected _solution: OperatorAttachmentsContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + this._solution = { serviceSid, }; + this._uri = `/Services/${serviceSid}/Operators`; + } + + fetch(callback?: (error: Error | null, item?: OperatorAttachmentsInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OperatorAttachmentsInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new OperatorAttachmentsInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface OperatorAttachmentsPayload extends OperatorAttachmentsResource {} + +interface OperatorAttachmentsResource { + service_sid: string; + operator_sids: Array; + url: string; +} + +export class OperatorAttachmentsInstance { + protected _solution: OperatorAttachmentsContextSolution; + protected _context?: OperatorAttachmentsContext; + + constructor(protected _version: V2, payload: OperatorAttachmentsResource, serviceSid?: string) { + + this.serviceSid = (payload.service_sid); + this.operatorSids = (payload.operator_sids); + this.url = (payload.url); + + this._solution = { serviceSid: serviceSid, }; + } + + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * List of Operator SIDs attached to the service. Includes both Custom and Pre-built Operators. + */ + operatorSids: Array; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): OperatorAttachmentsContext { + this._context = this._context || new OperatorAttachmentsContextImpl(this._version, this._solution.serviceSid); + return this._context; + } + + /** + * Fetch a OperatorAttachmentsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorAttachmentsInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorAttachmentsInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a OperatorAttachmentsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorAttachmentsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + serviceSid: this.serviceSid, + operatorSids: this.operatorSids, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OperatorAttachmentsSolution { +} + +export interface OperatorAttachmentsListInstance { + _version: V2; + _solution: OperatorAttachmentsSolution; + _uri: string; + + (serviceSid: string, ): OperatorAttachmentsContext; + get(serviceSid: string, ): OperatorAttachmentsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OperatorAttachmentsListInstance(version: V2): OperatorAttachmentsListInstance { + const instance = ((serviceSid, ) => instance.get(serviceSid, )) as OperatorAttachmentsListInstance; + + instance.get = function get(serviceSid, ): OperatorAttachmentsContext { + return new OperatorAttachmentsContextImpl(version, serviceSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/intelligence/v2/operatorType.ts b/rest/intelligence/v2/operatorType.ts new file mode 100644 index 000000000..78c8223a3 --- /dev/null +++ b/rest/intelligence/v2/operatorType.ts @@ -0,0 +1,623 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Operator Type availability status. Possible values: internal, beta, general-availability, retired, deprecated. + */ +export type OperatorTypeAvailability = 'internal'|'beta'|'general-availability'|'retired'|'deprecated'; + +/** + * Operator Results for this Operator Type will follow this format. Possible values: text-classification, text-extraction, text-extraction-normalized, text-generation. + */ +export type OperatorTypeOutputType = 'text-classification'|'text-extraction'|'text-extraction-normalized'|'text-generation'|'json'; + +/** + * Operators with this Operator Type are executed using this provider. Possible values: twilio, amazon, openai. + */ +export type OperatorTypeProvider = 'twilio'|'amazon'|'openai'; + + + +/** + * Options to pass to each + */ +export interface OperatorTypeListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Returns Operator Types that support the provided language code. */ + "languageCode"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: OperatorTypeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface OperatorTypeListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Returns Operator Types that support the provided language code. */ + "languageCode"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface OperatorTypeListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Returns Operator Types that support the provided language code. */ + "languageCode"?: string; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface OperatorTypeContext { + + /** + * Fetch a OperatorTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorTypeInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorTypeInstance) => any): Promise + + /** + * Fetch a OperatorTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OperatorTypeContextSolution { + "sid": string; +} + +export class OperatorTypeContextImpl implements OperatorTypeContext { + protected _solution: OperatorTypeContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/OperatorTypes/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: OperatorTypeInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OperatorTypeInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new OperatorTypeInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface OperatorTypePayload extends TwilioResponsePayload { + operator_types: OperatorTypeResource[]; +} + +interface OperatorTypeResource { + name: string; + sid: string; + friendly_name: string; + description: string; + docs_link: string; + output_type: OperatorTypeOutputType; + supported_languages: Array; + provider: OperatorTypeProvider; + availability: OperatorTypeAvailability; + configurable: boolean; + config_schema: any; + date_created: Date; + date_updated: Date; + url: string; +} + +export class OperatorTypeInstance { + protected _solution: OperatorTypeContextSolution; + protected _context?: OperatorTypeContext; + + constructor(protected _version: V2, payload: OperatorTypeResource, sid?: string) { + + this.name = (payload.name); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.docsLink = (payload.docs_link); + this.outputType = payload.output_type; + this.supportedLanguages = (payload.supported_languages); + this.provider = payload.provider; + this.availability = payload.availability; + this.configurable = (payload.configurable); + this.configSchema = (payload.config_schema); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * A unique name that references an Operator\'s Operator Type. + */ + name: string; + /** + * A 34 character string that uniquely identifies this Operator Type. + */ + sid: string; + /** + * A human-readable name of this resource, up to 64 characters. + */ + friendlyName: string; + /** + * A human-readable description of this resource, longer than the friendly name. + */ + description: string; + /** + * Additional documentation for the Operator Type. + */ + docsLink: string; + outputType: OperatorTypeOutputType; + /** + * List of languages this Operator Type supports. + */ + supportedLanguages: Array; + provider: OperatorTypeProvider; + availability: OperatorTypeAvailability; + /** + * Operators can be created from configurable Operator Types. + */ + configurable: boolean; + /** + * JSON Schema for configuring an Operator with this Operator Type. Following https://json-schema.org/ + */ + configSchema: any; + /** + * The date that this Operator Type was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Operator Type was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): OperatorTypeContext { + this._context = this._context || new OperatorTypeContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a OperatorTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorTypeInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorTypeInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a OperatorTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + name: this.name, + sid: this.sid, + friendlyName: this.friendlyName, + description: this.description, + docsLink: this.docsLink, + outputType: this.outputType, + supportedLanguages: this.supportedLanguages, + provider: this.provider, + availability: this.availability, + configurable: this.configurable, + configSchema: this.configSchema, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OperatorTypeSolution { +} + +export interface OperatorTypeListInstance { + _version: V2; + _solution: OperatorTypeSolution; + _uri: string; + + (sid: string, ): OperatorTypeContext; + get(sid: string, ): OperatorTypeContext; + + + + + + /** + * Streams OperatorTypeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: OperatorTypeInstance, done: (err?: Error) => void) => void): void; + each(params: OperatorTypeListInstanceEachOptions, callback?: (item: OperatorTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams OperatorTypeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: OperatorTypeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: OperatorTypeListInstanceEachOptions, callback?: (item: OperatorTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of OperatorTypeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: OperatorTypePage) => any): Promise; + /** + * Retrieve a single target page of OperatorTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists OperatorTypeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: OperatorTypeInstance[]) => any): Promise; + list(params: OperatorTypeListInstanceOptions, callback?: (error: Error | null, items: OperatorTypeInstance[]) => any): Promise; + /** + * Lists OperatorTypeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: OperatorTypeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of OperatorTypeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: OperatorTypePage) => any): Promise; + page(params: OperatorTypeListInstancePageOptions, callback?: (error: Error | null, items: OperatorTypePage) => any): Promise; + /** + * Retrieve a single page of OperatorTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: OperatorTypeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OperatorTypeListInstance(version: V2): OperatorTypeListInstance { + const instance = ((sid, ) => instance.get(sid, )) as OperatorTypeListInstance; + + instance.get = function get(sid, ): OperatorTypeContext { + return new OperatorTypeContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/OperatorTypes`; + + instance.page = function page(params?: OperatorTypeListInstancePageOptions | ((error: Error | null, items: OperatorTypePage) => any), callback?: (error: Error | null, items: OperatorTypePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new OperatorTypePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: OperatorTypePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new OperatorTypePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: OperatorTypeListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OperatorTypePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OperatorTypePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class OperatorTypePage extends Page { +/** +* Initialize the OperatorTypePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: OperatorTypeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of OperatorTypeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: OperatorTypeResource): OperatorTypeInstance { + + return new OperatorTypeInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v2/prebuiltOperator.ts b/rest/intelligence/v2/prebuiltOperator.ts new file mode 100644 index 000000000..f5eacc3b0 --- /dev/null +++ b/rest/intelligence/v2/prebuiltOperator.ts @@ -0,0 +1,615 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Operator availability status. Possible values: internal, beta, public, retired. + */ +export type PrebuiltOperatorAvailability = 'internal'|'beta'|'public'|'retired'|'general-availability'; + + + +/** + * Options to pass to each + */ +export interface PrebuiltOperatorListInstanceEachOptions { + /** Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. */ + "availability"?: PrebuiltOperatorAvailability; + /** Returns Pre-built Operators that support the provided language code. */ + "languageCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PrebuiltOperatorInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PrebuiltOperatorListInstanceOptions { + /** Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. */ + "availability"?: PrebuiltOperatorAvailability; + /** Returns Pre-built Operators that support the provided language code. */ + "languageCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PrebuiltOperatorListInstancePageOptions { + /** Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. */ + "availability"?: PrebuiltOperatorAvailability; + /** Returns Pre-built Operators that support the provided language code. */ + "languageCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PrebuiltOperatorContext { + + /** + * Fetch a PrebuiltOperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PrebuiltOperatorInstance + */ + fetch(callback?: (error: Error | null, item?: PrebuiltOperatorInstance) => any): Promise + + /** + * Fetch a PrebuiltOperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PrebuiltOperatorInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PrebuiltOperatorContextSolution { + "sid": string; +} + +export class PrebuiltOperatorContextImpl implements PrebuiltOperatorContext { + protected _solution: PrebuiltOperatorContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Operators/PreBuilt/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: PrebuiltOperatorInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PrebuiltOperatorInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new PrebuiltOperatorInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PrebuiltOperatorPayload extends TwilioResponsePayload { + operators: PrebuiltOperatorResource[]; +} + +interface PrebuiltOperatorResource { + account_sid: string; + sid: string; + friendly_name: string; + description: string; + author: string; + operator_type: string; + version: number; + availability: PrebuiltOperatorAvailability; + config: any; + date_created: Date; + date_updated: Date; + url: string; +} + +export class PrebuiltOperatorInstance { + protected _solution: PrebuiltOperatorContextSolution; + protected _context?: PrebuiltOperatorContext; + + constructor(protected _version: V2, payload: PrebuiltOperatorResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.author = (payload.author); + this.operatorType = (payload.operator_type); + this.version = deserialize.integer(payload.version); + this.availability = payload.availability; + this.config = (payload.config); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique SID identifier of the Account the Pre-built Operator belongs to. + */ + accountSid: string; + /** + * A 34 character string that uniquely identifies this Pre-built Operator. + */ + sid: string; + /** + * A human-readable name of this resource, up to 64 characters. + */ + friendlyName: string; + /** + * A human-readable description of this resource, longer than the friendly name. + */ + description: string; + /** + * The creator of the Operator. Pre-built Operators can only be created by Twilio. + */ + author: string; + /** + * Operator Type for this Operator. References an existing Operator Type resource. + */ + operatorType: string; + /** + * Numeric Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Operator. + */ + version: number; + availability: PrebuiltOperatorAvailability; + /** + * Operator configuration, following the schema defined by the Operator Type. Only available on Custom Operators created by the Account, will be empty for Pre-Built Operators. + */ + config: any; + /** + * The date that this Pre-built Operator was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Pre-built Operator was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): PrebuiltOperatorContext { + this._context = this._context || new PrebuiltOperatorContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a PrebuiltOperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PrebuiltOperatorInstance + */ + fetch(callback?: (error: Error | null, item?: PrebuiltOperatorInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PrebuiltOperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PrebuiltOperatorInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + friendlyName: this.friendlyName, + description: this.description, + author: this.author, + operatorType: this.operatorType, + version: this.version, + availability: this.availability, + config: this.config, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PrebuiltOperatorSolution { +} + +export interface PrebuiltOperatorListInstance { + _version: V2; + _solution: PrebuiltOperatorSolution; + _uri: string; + + (sid: string, ): PrebuiltOperatorContext; + get(sid: string, ): PrebuiltOperatorContext; + + + + + + /** + * Streams PrebuiltOperatorInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PrebuiltOperatorListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PrebuiltOperatorInstance, done: (err?: Error) => void) => void): void; + each(params: PrebuiltOperatorListInstanceEachOptions, callback?: (item: PrebuiltOperatorInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PrebuiltOperatorInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PrebuiltOperatorListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PrebuiltOperatorInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PrebuiltOperatorListInstanceEachOptions, callback?: (item: PrebuiltOperatorInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PrebuiltOperatorInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PrebuiltOperatorPage) => any): Promise; + /** + * Retrieve a single target page of PrebuiltOperatorInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists PrebuiltOperatorInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PrebuiltOperatorListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PrebuiltOperatorInstance[]) => any): Promise; + list(params: PrebuiltOperatorListInstanceOptions, callback?: (error: Error | null, items: PrebuiltOperatorInstance[]) => any): Promise; + /** + * Lists PrebuiltOperatorInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PrebuiltOperatorListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: PrebuiltOperatorListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of PrebuiltOperatorInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PrebuiltOperatorListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PrebuiltOperatorPage) => any): Promise; + page(params: PrebuiltOperatorListInstancePageOptions, callback?: (error: Error | null, items: PrebuiltOperatorPage) => any): Promise; + /** + * Retrieve a single page of PrebuiltOperatorInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PrebuiltOperatorListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: PrebuiltOperatorListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PrebuiltOperatorListInstance(version: V2): PrebuiltOperatorListInstance { + const instance = ((sid, ) => instance.get(sid, )) as PrebuiltOperatorListInstance; + + instance.get = function get(sid, ): PrebuiltOperatorContext { + return new PrebuiltOperatorContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Operators/PreBuilt`; + + instance.page = function page(params?: PrebuiltOperatorListInstancePageOptions | ((error: Error | null, items: PrebuiltOperatorPage) => any), callback?: (error: Error | null, items: PrebuiltOperatorPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["availability"] !== undefined) + data["Availability"] = params["availability"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PrebuiltOperatorPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PrebuiltOperatorPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PrebuiltOperatorPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PrebuiltOperatorListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["availability"] !== undefined) + data["Availability"] = params["availability"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PrebuiltOperatorPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PrebuiltOperatorPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PrebuiltOperatorPage extends Page { +/** +* Initialize the PrebuiltOperatorPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: PrebuiltOperatorSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PrebuiltOperatorInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PrebuiltOperatorResource): PrebuiltOperatorInstance { + + return new PrebuiltOperatorInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v2/service.ts b/rest/intelligence/v2/service.ts new file mode 100644 index 000000000..e2a55f29e --- /dev/null +++ b/rest/intelligence/v2/service.ts @@ -0,0 +1,1074 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The HTTP method for the Webhook. One of `GET` or `POST`. + */ +export type ServiceHttpMethod = 'GET'|'POST'|'NULL'; + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** The If-Match HTTP request header */ + "ifMatch"?: string; + /** Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. */ + "autoTranscribe"?: boolean; + /** Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. */ + "dataLogging"?: boolean; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; + /** Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName"?: string; + /** Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. */ + "autoRedaction"?: boolean; + /** Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. */ + "mediaRedaction"?: boolean; + /** The URL Twilio will request when executing the Webhook. */ + "webhookUrl"?: string; + /** */ + "webhookHttpMethod"?: ServiceHttpMethod; + /** The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. */ + "encryptionCredentialSid"?: string; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName": string; + /** Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. */ + "autoTranscribe"?: boolean; + /** Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. */ + "dataLogging"?: boolean; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; + /** The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it\\\'s set. */ + "languageCode"?: string; + /** Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. */ + "autoRedaction"?: boolean; + /** Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. */ + "mediaRedaction"?: boolean; + /** The URL Twilio will request when executing the Webhook. */ + "webhookUrl"?: string; + /** */ + "webhookHttpMethod"?: ServiceHttpMethod; + /** The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. */ + "encryptionCredentialSid"?: string; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["autoTranscribe"] !== undefined) + data["AutoTranscribe"] = serialize.bool(params["autoTranscribe"]); + if (params["dataLogging"] !== undefined) + data["DataLogging"] = serialize.bool(params["dataLogging"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["autoRedaction"] !== undefined) + data["AutoRedaction"] = serialize.bool(params["autoRedaction"]); + if (params["mediaRedaction"] !== undefined) + data["MediaRedaction"] = serialize.bool(params["mediaRedaction"]); + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["webhookHttpMethod"] !== undefined) + data["WebhookHttpMethod"] = params["webhookHttpMethod"]; + if (params["encryptionCredentialSid"] !== undefined) + data["EncryptionCredentialSid"] = params["encryptionCredentialSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["autoTranscribe"] !== undefined) + data["AutoTranscribe"] = serialize.bool(params["autoTranscribe"]); + if (params["dataLogging"] !== undefined) + data["DataLogging"] = serialize.bool(params["dataLogging"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["autoRedaction"] !== undefined) + data["AutoRedaction"] = serialize.bool(params["autoRedaction"]); + if (params["mediaRedaction"] !== undefined) + data["MediaRedaction"] = serialize.bool(params["mediaRedaction"]); + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["webhookHttpMethod"] !== undefined) + data["WebhookHttpMethod"] = params["webhookHttpMethod"]; + if (params["encryptionCredentialSid"] !== undefined) + data["EncryptionCredentialSid"] = params["encryptionCredentialSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + account_sid: string; + auto_redaction: boolean; + media_redaction: boolean; + auto_transcribe: boolean; + data_logging: boolean; + date_created: Date; + date_updated: Date; + friendly_name: string; + language_code: string; + sid: string; + unique_name: string; + url: string; + webhook_url: string; + webhook_http_method: ServiceHttpMethod; + read_only_attached_operator_sids: Array; + version: number; + encryption_credential_sid: string; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V2, payload: ServiceResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.autoRedaction = (payload.auto_redaction); + this.mediaRedaction = (payload.media_redaction); + this.autoTranscribe = (payload.auto_transcribe); + this.dataLogging = (payload.data_logging); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.languageCode = (payload.language_code); + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.url = (payload.url); + this.webhookUrl = (payload.webhook_url); + this.webhookHttpMethod = payload.webhook_http_method; + this.readOnlyAttachedOperatorSids = (payload.read_only_attached_operator_sids); + this.version = deserialize.integer(payload.version); + this.encryptionCredentialSid = (payload.encryption_credential_sid); + + this._solution = { sid: sid, }; + } + + /** + * The unique SID identifier of the Account the Service belongs to. + */ + accountSid: string; + /** + * Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + */ + autoRedaction: boolean; + /** + * Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + */ + mediaRedaction: boolean; + /** + * Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + */ + autoTranscribe: boolean; + /** + * Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + */ + dataLogging: boolean; + /** + * The date that this Service was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Service was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * A human readable description of this resource, up to 64 characters. + */ + friendlyName: string; + /** + * The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it\'s set. + */ + languageCode: string; + /** + * A 34 character string that uniquely identifies this Service. + */ + sid: string; + /** + * Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + */ + uniqueName: string; + /** + * The URL of this resource. + */ + url: string; + /** + * The URL Twilio will request when executing the Webhook. + */ + webhookUrl: string; + webhookHttpMethod: ServiceHttpMethod; + /** + * Operator sids attached to this service, read only + */ + readOnlyAttachedOperatorSids: Array; + /** + * The version number of this Service. + */ + version: number; + /** + * The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + */ + encryptionCredentialSid: string; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + autoRedaction: this.autoRedaction, + mediaRedaction: this.mediaRedaction, + autoTranscribe: this.autoTranscribe, + dataLogging: this.dataLogging, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + languageCode: this.languageCode, + sid: this.sid, + uniqueName: this.uniqueName, + url: this.url, + webhookUrl: this.webhookUrl, + webhookHttpMethod: this.webhookHttpMethod, + readOnlyAttachedOperatorSids: this.readOnlyAttachedOperatorSids, + version: this.version, + encryptionCredentialSid: this.encryptionCredentialSid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V2; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V2): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ServiceInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + if (params["autoTranscribe"] !== undefined) + data["AutoTranscribe"] = serialize.bool(params["autoTranscribe"]); + if (params["dataLogging"] !== undefined) + data["DataLogging"] = serialize.bool(params["dataLogging"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["autoRedaction"] !== undefined) + data["AutoRedaction"] = serialize.bool(params["autoRedaction"]); + if (params["mediaRedaction"] !== undefined) + data["MediaRedaction"] = serialize.bool(params["mediaRedaction"]); + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["webhookHttpMethod"] !== undefined) + data["WebhookHttpMethod"] = params["webhookHttpMethod"]; + if (params["encryptionCredentialSid"] !== undefined) + data["EncryptionCredentialSid"] = params["encryptionCredentialSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + if (params["autoTranscribe"] !== undefined) + data["AutoTranscribe"] = serialize.bool(params["autoTranscribe"]); + if (params["dataLogging"] !== undefined) + data["DataLogging"] = serialize.bool(params["dataLogging"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["autoRedaction"] !== undefined) + data["AutoRedaction"] = serialize.bool(params["autoRedaction"]); + if (params["mediaRedaction"] !== undefined) + data["MediaRedaction"] = serialize.bool(params["mediaRedaction"]); + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["webhookHttpMethod"] !== undefined) + data["WebhookHttpMethod"] = params["webhookHttpMethod"]; + if (params["encryptionCredentialSid"] !== undefined) + data["EncryptionCredentialSid"] = params["encryptionCredentialSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v2/transcript.ts b/rest/intelligence/v2/transcript.ts new file mode 100644 index 000000000..f0cf6e98d --- /dev/null +++ b/rest/intelligence/v2/transcript.ts @@ -0,0 +1,975 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { EncryptedOperatorResultsListInstance } from "./transcript/encryptedOperatorResults"; +import { EncryptedSentencesListInstance } from "./transcript/encryptedSentences"; +import { MediaListInstance } from "./transcript/media"; +import { OperatorResultListInstance } from "./transcript/operatorResult"; +import { SentenceListInstance } from "./transcript/sentence"; + + +/** + * The Status of this Transcript. One of `queued`, `in-progress`, `completed`, `failed` or `canceled`. + */ +export type TranscriptStatus = 'queued'|'in-progress'|'completed'|'new'|'failed'|'canceled'|'error'; + + + + +/** + * Options to pass to create a TranscriptInstance + */ +export interface TranscriptListInstanceCreateOptions { + /** The unique SID identifier of the Service. */ + "serviceSid": string; + /** JSON object describing Media Channel including Source and Participants */ + "channel": any; + /** Used to store client provided metadata. Maximum of 64 double-byte UTF8 characters. */ + "customerKey"?: string; + /** The date that this Transcript\\\'s media was started, given in ISO 8601 format. */ + "mediaStartTime"?: Date; +} + +/** + * Options to pass to each + */ +export interface TranscriptListInstanceEachOptions { + /** The unique SID identifier of the Service. */ + "serviceSid"?: string; + /** Filter by before StartTime. */ + "beforeStartTime"?: string; + /** Filter by after StartTime. */ + "afterStartTime"?: string; + /** Filter by before DateCreated. */ + "beforeDateCreated"?: string; + /** Filter by after DateCreated. */ + "afterDateCreated"?: string; + /** Filter by status. */ + "status"?: string; + /** Filter by Language Code. */ + "languageCode"?: string; + /** Filter by SourceSid. */ + "sourceSid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TranscriptInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TranscriptListInstanceOptions { + /** The unique SID identifier of the Service. */ + "serviceSid"?: string; + /** Filter by before StartTime. */ + "beforeStartTime"?: string; + /** Filter by after StartTime. */ + "afterStartTime"?: string; + /** Filter by before DateCreated. */ + "beforeDateCreated"?: string; + /** Filter by after DateCreated. */ + "afterDateCreated"?: string; + /** Filter by status. */ + "status"?: string; + /** Filter by Language Code. */ + "languageCode"?: string; + /** Filter by SourceSid. */ + "sourceSid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TranscriptListInstancePageOptions { + /** The unique SID identifier of the Service. */ + "serviceSid"?: string; + /** Filter by before StartTime. */ + "beforeStartTime"?: string; + /** Filter by after StartTime. */ + "afterStartTime"?: string; + /** Filter by before DateCreated. */ + "beforeDateCreated"?: string; + /** Filter by after DateCreated. */ + "afterDateCreated"?: string; + /** Filter by status. */ + "status"?: string; + /** Filter by Language Code. */ + "languageCode"?: string; + /** Filter by SourceSid. */ + "sourceSid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TranscriptContext { + encryptedOperatorResults: EncryptedOperatorResultsListInstance; + encryptedSentences: EncryptedSentencesListInstance; + media: MediaListInstance; + operatorResults: OperatorResultListInstance; + sentences: SentenceListInstance; + + /** + * Remove a TranscriptInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a TranscriptInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a TranscriptInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptInstance) => any): Promise + + /** + * Fetch a TranscriptInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TranscriptContextSolution { + "sid": string; +} + +export class TranscriptContextImpl implements TranscriptContext { + protected _solution: TranscriptContextSolution; + protected _uri: string; + + protected _encryptedOperatorResults?: EncryptedOperatorResultsListInstance; + protected _encryptedSentences?: EncryptedSentencesListInstance; + protected _media?: MediaListInstance; + protected _operatorResults?: OperatorResultListInstance; + protected _sentences?: SentenceListInstance; + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Transcripts/${sid}`; + } + + get encryptedOperatorResults(): EncryptedOperatorResultsListInstance { + this._encryptedOperatorResults = this._encryptedOperatorResults || EncryptedOperatorResultsListInstance(this._version, this._solution.sid); + return this._encryptedOperatorResults; + } + + get encryptedSentences(): EncryptedSentencesListInstance { + this._encryptedSentences = this._encryptedSentences || EncryptedSentencesListInstance(this._version, this._solution.sid); + return this._encryptedSentences; + } + + get media(): MediaListInstance { + this._media = this._media || MediaListInstance(this._version, this._solution.sid); + return this._media; + } + + get operatorResults(): OperatorResultListInstance { + this._operatorResults = this._operatorResults || OperatorResultListInstance(this._version, this._solution.sid); + return this._operatorResults; + } + + get sentences(): SentenceListInstance { + this._sentences = this._sentences || SentenceListInstance(this._version, this._solution.sid); + return this._sentences; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TranscriptInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TranscriptInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new TranscriptInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TranscriptPayload extends TwilioResponsePayload { + transcripts: TranscriptResource[]; +} + +interface TranscriptResource { + account_sid: string; + service_sid: string; + sid: string; + date_created: Date; + date_updated: Date; + status: TranscriptStatus; + channel: any; + data_logging: boolean; + language_code: string; + customer_key: string; + media_start_time: Date; + duration: number; + url: string; + redaction: boolean; + encryption_credential_sid: string; + links: Record; +} + +export class TranscriptInstance { + protected _solution: TranscriptContextSolution; + protected _context?: TranscriptContext; + + constructor(protected _version: V2, payload: TranscriptResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.sid = (payload.sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.status = payload.status; + this.channel = (payload.channel); + this.dataLogging = (payload.data_logging); + this.languageCode = (payload.language_code); + this.customerKey = (payload.customer_key); + this.mediaStartTime = deserialize.iso8601DateTime(payload.media_start_time); + this.duration = deserialize.integer(payload.duration); + this.url = (payload.url); + this.redaction = (payload.redaction); + this.encryptionCredentialSid = (payload.encryption_credential_sid); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * A 34 character string that uniquely identifies this Transcript. + */ + sid: string; + /** + * The date that this Transcript was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Transcript was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + status: TranscriptStatus; + /** + * Media Channel describing Transcript Source and Participant Mapping + */ + channel: any; + /** + * Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + */ + dataLogging: boolean; + /** + * The default language code of the audio. + */ + languageCode: string; + customerKey: string; + /** + * The date that this Transcript\'s media was started, given in ISO 8601 format. + */ + mediaStartTime: Date; + /** + * The duration of this Transcript\'s source + */ + duration: number; + /** + * The URL of this resource. + */ + url: string; + /** + * If the transcript has been redacted, a redacted alternative of the transcript will be available. + */ + redaction: boolean; + /** + * The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + */ + encryptionCredentialSid: string; + links: Record; + + private get _proxy(): TranscriptContext { + this._context = this._context || new TranscriptContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a TranscriptInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TranscriptInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TranscriptInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TranscriptInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the encryptedOperatorResults. + */ + encryptedOperatorResults(): EncryptedOperatorResultsListInstance { + return this._proxy.encryptedOperatorResults; + } + + /** + * Access the encryptedSentences. + */ + encryptedSentences(): EncryptedSentencesListInstance { + return this._proxy.encryptedSentences; + } + + /** + * Access the media. + */ + media(): MediaListInstance { + return this._proxy.media; + } + + /** + * Access the operatorResults. + */ + operatorResults(): OperatorResultListInstance { + return this._proxy.operatorResults; + } + + /** + * Access the sentences. + */ + sentences(): SentenceListInstance { + return this._proxy.sentences; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + serviceSid: this.serviceSid, + sid: this.sid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + status: this.status, + channel: this.channel, + dataLogging: this.dataLogging, + languageCode: this.languageCode, + customerKey: this.customerKey, + mediaStartTime: this.mediaStartTime, + duration: this.duration, + url: this.url, + redaction: this.redaction, + encryptionCredentialSid: this.encryptionCredentialSid, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TranscriptSolution { +} + +export interface TranscriptListInstance { + _version: V2; + _solution: TranscriptSolution; + _uri: string; + + (sid: string, ): TranscriptContext; + get(sid: string, ): TranscriptContext; + + + + + + + /** + * Create a TranscriptInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptInstance + */ + create(params: TranscriptListInstanceCreateOptions, callback?: (error: Error | null, item?: TranscriptInstance) => any): Promise; + + /** + * Create a TranscriptInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptInstance with HTTP metadata + */ + createWithHttpInfo(params: TranscriptListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams TranscriptInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TranscriptInstance, done: (err?: Error) => void) => void): void; + each(params: TranscriptListInstanceEachOptions, callback?: (item: TranscriptInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TranscriptInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TranscriptInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TranscriptListInstanceEachOptions, callback?: (item: TranscriptInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TranscriptInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TranscriptPage) => any): Promise; + /** + * Retrieve a single target page of TranscriptInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists TranscriptInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TranscriptInstance[]) => any): Promise; + list(params: TranscriptListInstanceOptions, callback?: (error: Error | null, items: TranscriptInstance[]) => any): Promise; + /** + * Lists TranscriptInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: TranscriptListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of TranscriptInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TranscriptPage) => any): Promise; + page(params: TranscriptListInstancePageOptions, callback?: (error: Error | null, items: TranscriptPage) => any): Promise; + /** + * Retrieve a single page of TranscriptInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: TranscriptListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TranscriptListInstance(version: V2): TranscriptListInstance { + const instance = ((sid, ) => instance.get(sid, )) as TranscriptListInstance; + + instance.get = function get(sid, ): TranscriptContext { + return new TranscriptContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Transcripts`; + + instance.create = function create(params: TranscriptListInstanceCreateOptions, callback?: (error: Error | null, items: TranscriptInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["serviceSid"] === null || params["serviceSid"] === undefined) { + throw new Error('Required parameter "params[\'serviceSid\']" missing.'); + } + + if (params["channel"] === null || params["channel"] === undefined) { + throw new Error('Required parameter "params[\'channel\']" missing.'); + } + + let data: any = {}; + + + + data["ServiceSid"] = params["serviceSid"]; + + data["Channel"] = serialize.object(params["channel"]); + if (params["customerKey"] !== undefined) + data["CustomerKey"] = params["customerKey"]; + if (params["mediaStartTime"] !== undefined) + data["MediaStartTime"] = serialize.iso8601DateTime(params["mediaStartTime"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TranscriptInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TranscriptListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["serviceSid"] === null || params["serviceSid"] === undefined) { + throw new Error('Required parameter "params[\'serviceSid\']" missing.'); + } + + if (params["channel"] === null || params["channel"] === undefined) { + throw new Error('Required parameter "params[\'channel\']" missing.'); + } + + let data: any = {}; + + + + data["ServiceSid"] = params["serviceSid"]; + + data["Channel"] = serialize.object(params["channel"]); + if (params["customerKey"] !== undefined) + data["CustomerKey"] = params["customerKey"]; + if (params["mediaStartTime"] !== undefined) + data["MediaStartTime"] = serialize.iso8601DateTime(params["mediaStartTime"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new TranscriptInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TranscriptListInstancePageOptions | ((error: Error | null, items: TranscriptPage) => any), callback?: (error: Error | null, items: TranscriptPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["serviceSid"] !== undefined) + data["ServiceSid"] = params["serviceSid"]; + if (params["beforeStartTime"] !== undefined) + data["BeforeStartTime"] = params["beforeStartTime"]; + if (params["afterStartTime"] !== undefined) + data["AfterStartTime"] = params["afterStartTime"]; + if (params["beforeDateCreated"] !== undefined) + data["BeforeDateCreated"] = params["beforeDateCreated"]; + if (params["afterDateCreated"] !== undefined) + data["AfterDateCreated"] = params["afterDateCreated"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["sourceSid"] !== undefined) + data["SourceSid"] = params["sourceSid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TranscriptPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TranscriptPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TranscriptPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TranscriptListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["serviceSid"] !== undefined) + data["ServiceSid"] = params["serviceSid"]; + if (params["beforeStartTime"] !== undefined) + data["BeforeStartTime"] = params["beforeStartTime"]; + if (params["afterStartTime"] !== undefined) + data["AfterStartTime"] = params["afterStartTime"]; + if (params["beforeDateCreated"] !== undefined) + data["BeforeDateCreated"] = params["beforeDateCreated"]; + if (params["afterDateCreated"] !== undefined) + data["AfterDateCreated"] = params["afterDateCreated"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["languageCode"] !== undefined) + data["LanguageCode"] = params["languageCode"]; + if (params["sourceSid"] !== undefined) + data["SourceSid"] = params["sourceSid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TranscriptPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TranscriptPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TranscriptPage extends Page { +/** +* Initialize the TranscriptPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: TranscriptSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TranscriptInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TranscriptResource): TranscriptInstance { + + return new TranscriptInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v2/transcript/encryptedOperatorResults.ts b/rest/intelligence/v2/transcript/encryptedOperatorResults.ts new file mode 100644 index 000000000..0086be0c5 --- /dev/null +++ b/rest/intelligence/v2/transcript/encryptedOperatorResults.ts @@ -0,0 +1,324 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a EncryptedOperatorResultsInstance + */ +export interface EncryptedOperatorResultsContextFetchOptions { + /** Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. */ + "redacted"?: boolean; +} + +export interface EncryptedOperatorResultsContext { + + /** + * Fetch a EncryptedOperatorResultsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedOperatorResultsInstance + */ + fetch(callback?: (error: Error | null, item?: EncryptedOperatorResultsInstance) => any): Promise; + /** + * Fetch a EncryptedOperatorResultsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedOperatorResultsInstance + */ + fetch(params: EncryptedOperatorResultsContextFetchOptions, callback?: (error: Error | null, item?: EncryptedOperatorResultsInstance) => any): Promise; + + /** + * Fetch a EncryptedOperatorResultsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedOperatorResultsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a EncryptedOperatorResultsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedOperatorResultsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: EncryptedOperatorResultsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EncryptedOperatorResultsContextSolution { + "transcriptSid": string; +} + +export class EncryptedOperatorResultsContextImpl implements EncryptedOperatorResultsContext { + protected _solution: EncryptedOperatorResultsContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, transcriptSid: string) { + if (!isValidPathParam(transcriptSid)) { + throw new Error('Parameter \'transcriptSid\' is not valid.'); + } + + this._solution = { transcriptSid, }; + this._uri = `/Transcripts/${transcriptSid}/OperatorResults/Encrypted`; + } + + fetch(params?: EncryptedOperatorResultsContextFetchOptions | ((error: Error | null, item?: EncryptedOperatorResultsInstance) => any),callback?: (error: Error | null, item?: EncryptedOperatorResultsInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new EncryptedOperatorResultsInstance(operationVersion, payload, instance._solution.transcriptSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: EncryptedOperatorResultsContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new EncryptedOperatorResultsInstance(operationVersion, response.body, instance._solution.transcriptSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EncryptedOperatorResultsPayload extends EncryptedOperatorResultsResource {} + +interface EncryptedOperatorResultsResource { + locations: Array; + transcript_sid: string; + url: string; +} + +export class EncryptedOperatorResultsInstance { + protected _solution: EncryptedOperatorResultsContextSolution; + protected _context?: EncryptedOperatorResultsContext; + + constructor(protected _version: V2, payload: EncryptedOperatorResultsResource, transcriptSid: string) { + + this.locations = (payload.locations); + this.transcriptSid = (payload.transcript_sid); + this.url = (payload.url); + + this._solution = { transcriptSid, }; + } + + /** + * The locations of the encrypted operator results. + */ + locations: Array; + transcriptSid: string; + url: string; + + private get _proxy(): EncryptedOperatorResultsContext { + this._context = this._context || new EncryptedOperatorResultsContextImpl(this._version, this._solution.transcriptSid); + return this._context; + } + + /** + * Fetch a EncryptedOperatorResultsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedOperatorResultsInstance + */ + fetch(callback?: (error: Error | null, item?: EncryptedOperatorResultsInstance) => any): Promise; + /** + * Fetch a EncryptedOperatorResultsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedOperatorResultsInstance + */ + fetch(params: EncryptedOperatorResultsContextFetchOptions, callback?: (error: Error | null, item?: EncryptedOperatorResultsInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: EncryptedOperatorResultsInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a EncryptedOperatorResultsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedOperatorResultsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a EncryptedOperatorResultsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedOperatorResultsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: EncryptedOperatorResultsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + locations: this.locations, + transcriptSid: this.transcriptSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EncryptedOperatorResultsSolution { + transcriptSid: string; +} + +export interface EncryptedOperatorResultsListInstance { + _version: V2; + _solution: EncryptedOperatorResultsSolution; + _uri: string; + + (): EncryptedOperatorResultsContext; + get(): EncryptedOperatorResultsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EncryptedOperatorResultsListInstance(version: V2, transcriptSid: string): EncryptedOperatorResultsListInstance { + if (!isValidPathParam(transcriptSid)) { + throw new Error('Parameter \'transcriptSid\' is not valid.'); + } + + const instance = (() => instance.get()) as EncryptedOperatorResultsListInstance; + + instance.get = function get(): EncryptedOperatorResultsContext { + return new EncryptedOperatorResultsContextImpl(version, transcriptSid); + } + + instance._version = version; + instance._solution = { transcriptSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/intelligence/v2/transcript/encryptedSentences.ts b/rest/intelligence/v2/transcript/encryptedSentences.ts new file mode 100644 index 000000000..94ac38862 --- /dev/null +++ b/rest/intelligence/v2/transcript/encryptedSentences.ts @@ -0,0 +1,324 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a EncryptedSentencesInstance + */ +export interface EncryptedSentencesContextFetchOptions { + /** Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. */ + "redacted"?: boolean; +} + +export interface EncryptedSentencesContext { + + /** + * Fetch a EncryptedSentencesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedSentencesInstance + */ + fetch(callback?: (error: Error | null, item?: EncryptedSentencesInstance) => any): Promise; + /** + * Fetch a EncryptedSentencesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedSentencesInstance + */ + fetch(params: EncryptedSentencesContextFetchOptions, callback?: (error: Error | null, item?: EncryptedSentencesInstance) => any): Promise; + + /** + * Fetch a EncryptedSentencesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedSentencesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a EncryptedSentencesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedSentencesInstance with HTTP metadata + */ + fetchWithHttpInfo(params: EncryptedSentencesContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EncryptedSentencesContextSolution { + "transcriptSid": string; +} + +export class EncryptedSentencesContextImpl implements EncryptedSentencesContext { + protected _solution: EncryptedSentencesContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, transcriptSid: string) { + if (!isValidPathParam(transcriptSid)) { + throw new Error('Parameter \'transcriptSid\' is not valid.'); + } + + this._solution = { transcriptSid, }; + this._uri = `/Transcripts/${transcriptSid}/Sentences/Encrypted`; + } + + fetch(params?: EncryptedSentencesContextFetchOptions | ((error: Error | null, item?: EncryptedSentencesInstance) => any),callback?: (error: Error | null, item?: EncryptedSentencesInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new EncryptedSentencesInstance(operationVersion, payload, instance._solution.transcriptSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: EncryptedSentencesContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new EncryptedSentencesInstance(operationVersion, response.body, instance._solution.transcriptSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EncryptedSentencesPayload extends EncryptedSentencesResource {} + +interface EncryptedSentencesResource { + location: string; + transcript_sid: string; + url: string; +} + +export class EncryptedSentencesInstance { + protected _solution: EncryptedSentencesContextSolution; + protected _context?: EncryptedSentencesContext; + + constructor(protected _version: V2, payload: EncryptedSentencesResource, transcriptSid: string) { + + this.location = (payload.location); + this.transcriptSid = (payload.transcript_sid); + this.url = (payload.url); + + this._solution = { transcriptSid, }; + } + + /** + * The location of the encrypted sentences. + */ + location: string; + transcriptSid: string; + url: string; + + private get _proxy(): EncryptedSentencesContext { + this._context = this._context || new EncryptedSentencesContextImpl(this._version, this._solution.transcriptSid); + return this._context; + } + + /** + * Fetch a EncryptedSentencesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedSentencesInstance + */ + fetch(callback?: (error: Error | null, item?: EncryptedSentencesInstance) => any): Promise; + /** + * Fetch a EncryptedSentencesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedSentencesInstance + */ + fetch(params: EncryptedSentencesContextFetchOptions, callback?: (error: Error | null, item?: EncryptedSentencesInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: EncryptedSentencesInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a EncryptedSentencesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedSentencesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a EncryptedSentencesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EncryptedSentencesInstance with HTTP metadata + */ + fetchWithHttpInfo(params: EncryptedSentencesContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + location: this.location, + transcriptSid: this.transcriptSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EncryptedSentencesSolution { + transcriptSid: string; +} + +export interface EncryptedSentencesListInstance { + _version: V2; + _solution: EncryptedSentencesSolution; + _uri: string; + + (): EncryptedSentencesContext; + get(): EncryptedSentencesContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EncryptedSentencesListInstance(version: V2, transcriptSid: string): EncryptedSentencesListInstance { + if (!isValidPathParam(transcriptSid)) { + throw new Error('Parameter \'transcriptSid\' is not valid.'); + } + + const instance = (() => instance.get()) as EncryptedSentencesListInstance; + + instance.get = function get(): EncryptedSentencesContext { + return new EncryptedSentencesContextImpl(version, transcriptSid); + } + + instance._version = version; + instance._solution = { transcriptSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/intelligence/v2/transcript/media.ts b/rest/intelligence/v2/transcript/media.ts new file mode 100644 index 000000000..4595d2651 --- /dev/null +++ b/rest/intelligence/v2/transcript/media.ts @@ -0,0 +1,344 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a MediaInstance + */ +export interface MediaContextFetchOptions { + /** Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. */ + "redacted"?: boolean; +} + +export interface MediaContext { + + /** + * Fetch a MediaInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance + */ + fetch(callback?: (error: Error | null, item?: MediaInstance) => any): Promise; + /** + * Fetch a MediaInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance + */ + fetch(params: MediaContextFetchOptions, callback?: (error: Error | null, item?: MediaInstance) => any): Promise; + + /** + * Fetch a MediaInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a MediaInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance with HTTP metadata + */ + fetchWithHttpInfo(params: MediaContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MediaContextSolution { + "sid": string; +} + +export class MediaContextImpl implements MediaContext { + protected _solution: MediaContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Transcripts/${sid}/Media`; + } + + fetch(params?: MediaContextFetchOptions | ((error: Error | null, item?: MediaInstance) => any),callback?: (error: Error | null, item?: MediaInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new MediaInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: MediaContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MediaInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MediaPayload extends MediaResource {} + +interface MediaResource { + account_sid: string; + media_url: string; + service_sid: string; + sid: string; + url: string; +} + +export class MediaInstance { + protected _solution: MediaContextSolution; + protected _context?: MediaContext; + + constructor(protected _version: V2, payload: MediaResource, sid: string) { + + this.accountSid = (payload.account_sid); + this.mediaUrl = (payload.media_url); + this.serviceSid = (payload.service_sid); + this.sid = (payload.sid); + this.url = (payload.url); + + this._solution = { sid, }; + } + + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * Downloadable URL for media, if stored in Twilio AI. + */ + mediaUrl: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The unique SID identifier of the Transcript. + */ + sid: string; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): MediaContext { + this._context = this._context || new MediaContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a MediaInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance + */ + fetch(callback?: (error: Error | null, item?: MediaInstance) => any): Promise; + /** + * Fetch a MediaInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance + */ + fetch(params: MediaContextFetchOptions, callback?: (error: Error | null, item?: MediaInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: MediaInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a MediaInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a MediaInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MediaInstance with HTTP metadata + */ + fetchWithHttpInfo(params: MediaContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + mediaUrl: this.mediaUrl, + serviceSid: this.serviceSid, + sid: this.sid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MediaSolution { + sid: string; +} + +export interface MediaListInstance { + _version: V2; + _solution: MediaSolution; + _uri: string; + + (): MediaContext; + get(): MediaContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MediaListInstance(version: V2, sid: string): MediaListInstance { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + const instance = (() => instance.get()) as MediaListInstance; + + instance.get = function get(): MediaContext { + return new MediaContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { sid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/intelligence/v2/transcript/operatorResult.ts b/rest/intelligence/v2/transcript/operatorResult.ts new file mode 100644 index 000000000..6bd596259 --- /dev/null +++ b/rest/intelligence/v2/transcript/operatorResult.ts @@ -0,0 +1,718 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The type of the applied Language Understanding Operator. One of conversation-classify, utterance-classify, extract, extract-normalize, or pii-extract + */ +export type OperatorResultOperatorType = 'conversation-classify'|'utterance-classify'|'extract'|'extract-normalize'|'pii-extract'|'text-generation'|'json'; + + +/** + * Options to pass to fetch a OperatorResultInstance + */ +export interface OperatorResultContextFetchOptions { + /** Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. */ + "redacted"?: boolean; +} + +/** + * Options to pass to each + */ +export interface OperatorResultListInstanceEachOptions { + /** Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. */ + "redacted"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: OperatorResultInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface OperatorResultListInstanceOptions { + /** Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. */ + "redacted"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface OperatorResultListInstancePageOptions { + /** Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. */ + "redacted"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface OperatorResultContext { + + /** + * Fetch a OperatorResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorResultInstance) => any): Promise; + /** + * Fetch a OperatorResultInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance + */ + fetch(params: OperatorResultContextFetchOptions, callback?: (error: Error | null, item?: OperatorResultInstance) => any): Promise; + + /** + * Fetch a OperatorResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a OperatorResultInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance with HTTP metadata + */ + fetchWithHttpInfo(params: OperatorResultContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OperatorResultContextSolution { + "transcriptSid": string; + "operatorSid": string; +} + +export class OperatorResultContextImpl implements OperatorResultContext { + protected _solution: OperatorResultContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, transcriptSid: string, operatorSid: string) { + if (!isValidPathParam(transcriptSid)) { + throw new Error('Parameter \'transcriptSid\' is not valid.'); + } + + if (!isValidPathParam(operatorSid)) { + throw new Error('Parameter \'operatorSid\' is not valid.'); + } + + this._solution = { transcriptSid, operatorSid, }; + this._uri = `/Transcripts/${transcriptSid}/OperatorResults/${operatorSid}`; + } + + fetch(params?: OperatorResultContextFetchOptions | ((error: Error | null, item?: OperatorResultInstance) => any),callback?: (error: Error | null, item?: OperatorResultInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new OperatorResultInstance(operationVersion, payload, instance._solution.transcriptSid, instance._solution.operatorSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: OperatorResultContextFetchOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new OperatorResultInstance(operationVersion, response.body, instance._solution.transcriptSid, instance._solution.operatorSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface OperatorResultPayload extends TwilioResponsePayload { + operator_results: OperatorResultResource[]; +} + +interface OperatorResultResource { + operator_type: OperatorResultOperatorType; + name: string; + operator_sid: string; + extract_match: boolean; + match_probability: number; + normalized_result: string; + utterance_results: Array; + utterance_match: boolean; + predicted_label: string; + predicted_probability: number; + label_probabilities: any; + extract_results: any; + text_generation_results: any; + json_results: any; + transcript_sid: string; + url: string; +} + +export class OperatorResultInstance { + protected _solution: OperatorResultContextSolution; + protected _context?: OperatorResultContext; + + constructor(protected _version: V2, payload: OperatorResultResource, transcriptSid: string, operatorSid?: string) { + + this.operatorType = payload.operator_type; + this.name = (payload.name); + this.operatorSid = (payload.operator_sid); + this.extractMatch = (payload.extract_match); + this.matchProbability = (payload.match_probability); + this.normalizedResult = (payload.normalized_result); + this.utteranceResults = (payload.utterance_results); + this.utteranceMatch = (payload.utterance_match); + this.predictedLabel = (payload.predicted_label); + this.predictedProbability = (payload.predicted_probability); + this.labelProbabilities = (payload.label_probabilities); + this.extractResults = (payload.extract_results); + this.textGenerationResults = (payload.text_generation_results); + this.jsonResults = (payload.json_results); + this.transcriptSid = (payload.transcript_sid); + this.url = (payload.url); + + this._solution = { transcriptSid, operatorSid: operatorSid, }; + } + + operatorType: OperatorResultOperatorType; + /** + * The name of the applied Language Understanding. + */ + name: string; + /** + * A 34 character string that identifies this Language Understanding operator sid. + */ + operatorSid: string; + /** + * Boolean to tell if extract Language Understanding Processing model matches results. + */ + extractMatch: boolean; + /** + * Percentage of \'matching\' class needed to consider a sentence matches + */ + matchProbability: number; + /** + * Normalized output of extraction stage which matches Label. + */ + normalizedResult: string; + /** + * List of mapped utterance object which matches sentences. + */ + utteranceResults: Array; + /** + * Boolean to tell if Utterance matches results. + */ + utteranceMatch: boolean; + /** + * The \'matching\' class. This might be available on conversation classify model outputs. + */ + predictedLabel: string; + /** + * Percentage of \'matching\' class needed to consider a sentence matches. + */ + predictedProbability: number; + /** + * The labels probabilities. This might be available on conversation classify model outputs. + */ + labelProbabilities: any; + /** + * List of text extraction results. This might be available on classify-extract model outputs. + */ + extractResults: any; + /** + * Output of a text generation operator for example Conversation Sumamary. + */ + textGenerationResults: any; + jsonResults: any; + /** + * A 34 character string that uniquely identifies this Transcript. + */ + transcriptSid: string; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): OperatorResultContext { + this._context = this._context || new OperatorResultContextImpl(this._version, this._solution.transcriptSid, this._solution.operatorSid); + return this._context; + } + + /** + * Fetch a OperatorResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorResultInstance) => any): Promise; + /** + * Fetch a OperatorResultInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance + */ + fetch(params: OperatorResultContextFetchOptions, callback?: (error: Error | null, item?: OperatorResultInstance) => any): Promise; + + fetch(params?: any, callback?: (error: Error | null, item?: OperatorResultInstance) => any): Promise + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a OperatorResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Fetch a OperatorResultInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance with HTTP metadata + */ + fetchWithHttpInfo(params: OperatorResultContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + operatorType: this.operatorType, + name: this.name, + operatorSid: this.operatorSid, + extractMatch: this.extractMatch, + matchProbability: this.matchProbability, + normalizedResult: this.normalizedResult, + utteranceResults: this.utteranceResults, + utteranceMatch: this.utteranceMatch, + predictedLabel: this.predictedLabel, + predictedProbability: this.predictedProbability, + labelProbabilities: this.labelProbabilities, + extractResults: this.extractResults, + textGenerationResults: this.textGenerationResults, + jsonResults: this.jsonResults, + transcriptSid: this.transcriptSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OperatorResultSolution { + transcriptSid: string; +} + +export interface OperatorResultListInstance { + _version: V2; + _solution: OperatorResultSolution; + _uri: string; + + (operatorSid: string, ): OperatorResultContext; + get(operatorSid: string, ): OperatorResultContext; + + + + + + /** + * Streams OperatorResultInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: OperatorResultInstance, done: (err?: Error) => void) => void): void; + each(params: OperatorResultListInstanceEachOptions, callback?: (item: OperatorResultInstance, done: (err?: Error) => void) => void): void; + /** + * Streams OperatorResultInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: OperatorResultInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: OperatorResultListInstanceEachOptions, callback?: (item: OperatorResultInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of OperatorResultInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: OperatorResultPage) => any): Promise; + /** + * Retrieve a single target page of OperatorResultInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists OperatorResultInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: OperatorResultInstance[]) => any): Promise; + list(params: OperatorResultListInstanceOptions, callback?: (error: Error | null, items: OperatorResultInstance[]) => any): Promise; + /** + * Lists OperatorResultInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: OperatorResultListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of OperatorResultInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: OperatorResultPage) => any): Promise; + page(params: OperatorResultListInstancePageOptions, callback?: (error: Error | null, items: OperatorResultPage) => any): Promise; + /** + * Retrieve a single page of OperatorResultInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: OperatorResultListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OperatorResultListInstance(version: V2, transcriptSid: string): OperatorResultListInstance { + if (!isValidPathParam(transcriptSid)) { + throw new Error('Parameter \'transcriptSid\' is not valid.'); + } + + const instance = ((operatorSid, ) => instance.get(operatorSid, )) as OperatorResultListInstance; + + instance.get = function get(operatorSid, ): OperatorResultContext { + return new OperatorResultContextImpl(version, transcriptSid, operatorSid); + } + + instance._version = version; + instance._solution = { transcriptSid, }; + instance._uri = `/Transcripts/${transcriptSid}/OperatorResults`; + + instance.page = function page(params?: OperatorResultListInstancePageOptions | ((error: Error | null, items: OperatorResultPage) => any), callback?: (error: Error | null, items: OperatorResultPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new OperatorResultPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: OperatorResultPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new OperatorResultPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: OperatorResultListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OperatorResultPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OperatorResultPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class OperatorResultPage extends Page { +/** +* Initialize the OperatorResultPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: OperatorResultSolution) { + super(version, response, solution); + } + + /** + * Build an instance of OperatorResultInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: OperatorResultResource): OperatorResultInstance { + + return new OperatorResultInstance( + this._version, + payload, + this._solution.transcriptSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v2/transcript/sentence.ts b/rest/intelligence/v2/transcript/sentence.ts new file mode 100644 index 000000000..85833453a --- /dev/null +++ b/rest/intelligence/v2/transcript/sentence.ts @@ -0,0 +1,450 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface SentenceListInstanceEachOptions { + /** Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. */ + "redacted"?: boolean; + /** Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. */ + "wordTimestamps"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 5000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SentenceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SentenceListInstanceOptions { + /** Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. */ + "redacted"?: boolean; + /** Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. */ + "wordTimestamps"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 5000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SentenceListInstancePageOptions { + /** Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. */ + "redacted"?: boolean; + /** Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. */ + "wordTimestamps"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 5000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface SentenceSolution { + transcriptSid: string; +} + +export interface SentenceListInstance { + _version: V2; + _solution: SentenceSolution; + _uri: string; + + + + + /** + * Streams SentenceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SentenceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SentenceInstance, done: (err?: Error) => void) => void): void; + each(params: SentenceListInstanceEachOptions, callback?: (item: SentenceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SentenceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SentenceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SentenceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SentenceListInstanceEachOptions, callback?: (item: SentenceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SentenceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SentencePage) => any): Promise; + /** + * Retrieve a single target page of SentenceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists SentenceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SentenceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SentenceInstance[]) => any): Promise; + list(params: SentenceListInstanceOptions, callback?: (error: Error | null, items: SentenceInstance[]) => any): Promise; + /** + * Lists SentenceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SentenceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: SentenceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of SentenceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SentenceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SentencePage) => any): Promise; + page(params: SentenceListInstancePageOptions, callback?: (error: Error | null, items: SentencePage) => any): Promise; + /** + * Retrieve a single page of SentenceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SentenceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: SentenceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SentenceListInstance(version: V2, transcriptSid: string): SentenceListInstance { + if (!isValidPathParam(transcriptSid)) { + throw new Error('Parameter \'transcriptSid\' is not valid.'); + } + + const instance = {} as SentenceListInstance; + + instance._version = version; + instance._solution = { transcriptSid, }; + instance._uri = `/Transcripts/${transcriptSid}/Sentences`; + + instance.page = function page(params?: SentenceListInstancePageOptions | ((error: Error | null, items: SentencePage) => any), callback?: (error: Error | null, items: SentencePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + if (params["wordTimestamps"] !== undefined) + data["WordTimestamps"] = serialize.bool(params["wordTimestamps"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SentencePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SentencePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SentencePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SentenceListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["redacted"] !== undefined) + data["Redacted"] = serialize.bool(params["redacted"]); + if (params["wordTimestamps"] !== undefined) + data["WordTimestamps"] = serialize.bool(params["wordTimestamps"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SentencePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SentencePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface SentencePayload extends TwilioResponsePayload { + sentences: SentenceResource[]; +} + +interface SentenceResource { + media_channel: number; + sentence_index: number; + start_time: string; + end_time: string; + transcript: string; + sid: string; + confidence: string; + words: Array; +} + +export class SentenceInstance { + + constructor(protected _version: V2, payload: SentenceResource, transcriptSid: string) { + + this.mediaChannel = deserialize.integer(payload.media_channel); + this.sentenceIndex = deserialize.integer(payload.sentence_index); + this.startTime = (payload.start_time); + this.endTime = (payload.end_time); + this.transcript = (payload.transcript); + this.sid = (payload.sid); + this.confidence = (payload.confidence); + this.words = (payload.words); + + } + + /** + * The channel number. + */ + mediaChannel: number; + /** + * The index of the sentence in the transcript. + */ + sentenceIndex: number; + /** + * Offset from the beginning of the transcript when this sentence starts. + */ + startTime: string; + /** + * Offset from the beginning of the transcript when this sentence ends. + */ + endTime: string; + /** + * Transcript text. + */ + transcript: string; + /** + * A 34 character string that uniquely identifies this Sentence. + */ + sid: string; + confidence: string; + /** + * Detailed information for each of the words of the given Sentence. + */ + words: Array; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + mediaChannel: this.mediaChannel, + sentenceIndex: this.sentenceIndex, + startTime: this.startTime, + endTime: this.endTime, + transcript: this.transcript, + sid: this.sid, + confidence: this.confidence, + words: this.words, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class SentencePage extends Page { +/** +* Initialize the SentencePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: SentenceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SentenceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SentenceResource): SentenceInstance { + + return new SentenceInstance( + this._version, + payload, + this._solution.transcriptSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v3/configuration.ts b/rest/intelligence/v3/configuration.ts new file mode 100644 index 000000000..c5a58735c --- /dev/null +++ b/rest/intelligence/v3/configuration.ts @@ -0,0 +1,1244 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Conversational Intelligence API + * The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class Action { + /** + * The type of Action to be performed after the Rule is triggered. Supported Actions are: - `WEBHOOK`: A webhook Action sends an HTTP request to a specified URL with Rule execution results. + */ + "type": string; + /** + * The HTTP method to be used when performing the Action. Must be set to `POST`. + */ + "method": string; + /** + * The URL endpoint where the Action will send the HTTP request containing the Rule execution results. + */ + "url": string; + + constructor(payload) { + this.type = payload["type"]; + this.method = payload["method"]; + this.url = payload["url"]; + } +} + + +/** + * Controls what additional customer and enterprise context is made available to Language Operators when this Rule executes. + */ +export class Context { + "memory"?: ContextMemory; + "knowledge"?: ContextKnowledge; + + constructor(payload) { + this.memory = payload["memory"]; + this.knowledge = payload["knowledge"]; + } +} + + +/** + * Configuration for passing Enterprise Knowledge as context to Operators in this Rule (available only for Enterprise Knowledge–enabled accounts). + */ +export class ContextKnowledge { + /** + * Specifies the Knowledge Base(s) and corresponding Source(s) to pass to Language Operators in this Rule as context. Only applied to Language Operators that have Knowledge as a context source enabled. + */ + "bases": Array; + + constructor(payload) { + this.bases = payload["bases"]; + } +} + + +/** + * Configuration for passing Memory as context to Operators in this Rule (available only for Memory–enabled accounts). + */ +export class ContextMemory { + /** + * When set to `true`, allows this Intelligence Configuration Rule to pass the Profile into attached Language Operators. The profile is only passed to Language Operators that have Memory as a context source enabled. + */ + "enabled"?: boolean; + + constructor(payload) { + this.enabled = payload["enabled"]; + } +} + + +/** + * Request body for creating a new Intelligence Configuration. + */ +export class CreateConfigurationRequest { + /** + * The display name of the Intelligence Configuration describing its purpose. + */ + "displayName": string; + /** + * The description of the Intelligence Configuration further explaining its purpose. + */ + "description"?: string; + /** + * List of Intelligence Configuration Rules that govern when and how Language Operators run. Each Rule represents a bundle of Operators, Triggers, Context, and Actions to be executed by the Intelligence Configuration on a Conversation. A maximum of five (5) Rules are allowed per Intelligence Configuration. To create an Intelligence Configuration without any Rules configured yet, pass an empty array (`\"rules\": []`). The Configuration will not execute any Language Operators until at least one Rule has been added. + */ + "rules": Array; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + this.rules = payload["rules"]; + } +} + + +export class Operator { + /** + * The unique identifier for the Language Operator to be executed by the Rule. Assigned by Twilio (TTID). + */ + "id": string; + /** + * The specific version of the Language Operator to execute. When provided, the Rule will use this exact version of the Operator. When omitted, the latest active version of the Operator is used at execution time. + */ + "version"?: number; + /** + * Key-value mapping for parameters defined as part of the Operator schema. The key and value passed by the Rule must match the name and data type of the parameter defined in the Operator, respectively. These parameters will customize the behavior of the Operator when executed by the Rule via runtime substitution into the prompt. Note: For parameters of type `knowledge_base_and_source_ids`, the value must be passed in the following format: `knowledge_base_id:knowledge_source_id`. + */ + "parameters"?: Record; + + constructor(payload) { + this.id = payload["id"]; + this.version = payload["version"]; + this.parameters = payload["parameters"]; + } +} + + +export class Rule { + /** + * The unique identifier for the Rule. Assigned by Twilio (TTID). + */ + "id": string; + /** + * List of Operators to be executed by the Rule. Maximum of five (5) Operators allowed per Rule. + */ + "operators": Array; + /** + * List of Triggers that determine when to activate the Rule. Maximum of one (1) Trigger allowed per Rule. + */ + "triggers": Array; + /** + * List of Actions to be performed after the Rule is triggered. Maximum of two (2) Actions allowed per Rule. + */ + "actions": Array; + "context"?: Context; + + constructor(payload) { + this.id = payload["id"]; + this.operators = payload["operators"]; + this.triggers = payload["triggers"]; + this.actions = payload["actions"]; + this.context = payload["context"]; + } +} + + +export class RuleCreationRequestPayload { + /** + * List of Operators to be executed by the Rule. Minimum of one (1) and maximum of five (5) Operators allowed per Rule. + */ + "operators": Array; + /** + * List of Triggers that determine when to activate the Rule. Maximum of one (1) Trigger allowed per Rule. + */ + "triggers"?: Array; + /** + * List of Actions to be performed after the Rule is triggered. Maximum of two (2) Actions allowed per Rule. + */ + "actions": Array; + "context"?: Context; + + constructor(payload) { + this.operators = payload["operators"]; + this.triggers = payload["triggers"]; + this.actions = payload["actions"]; + this.context = payload["context"]; + } +} + + +export class RuleUpdateRequestPayload { + /** + * Optional field used when updating an existing Rule within an Intelligence Configuration. When provided, the Rule with this `id` is updated; when omitted, a new Rule is created. + */ + "id"?: string; + /** + * List of Operators to be executed by the Rule. Minimum of one (1) and maximum of five (5) Operators allowed per Rule. + */ + "operators": Array; + /** + * List of Triggers that determine when to activate the Rule. Maximum of one (1) Trigger allowed per Rule. + */ + "triggers"?: Array; + /** + * List of Actions to be performed after the Rule is triggered. Maximum of two (2) Actions allowed per Rule. + */ + "actions": Array; + "context"?: Context; + + constructor(payload) { + this.id = payload["id"]; + this.operators = payload["operators"]; + this.triggers = payload["triggers"]; + this.actions = payload["actions"]; + this.context = payload["context"]; + } +} + + +export class Trigger { + /** + * The conversational lifecycle event that will activate execution of the Rule. Available values are: - `COMMUNICATION`: Trigger the Rule on each communication within the Conversation. - `CONVERSATION_END`: Trigger the Rule when the Conversation moves to the `closed` state - `CONVERSATION_INACTIVE`: Trigger the Rule when the Conversation moves to `inactive` state + */ + "on": string; + "parameters"?: TriggerParameters; + + constructor(payload) { + this.on = payload["on"]; + this.parameters = payload["parameters"]; + } +} + + +/** + * Additional configuration to modify Trigger behavior. Only applies to certain Trigger types. + */ +export class TriggerParameters { + /** + * When `on` is set to `COMMUNICATION`, this value controls how often the Rule should run. A value of `1` executes the Rule for every communication event. Higher values delay execution until the specified number of communications have occurred since the last execution. + */ + "count"?: number; + + constructor(payload) { + this.count = payload["count"]; + } +} + + +export class UpdateConfigurationRequest { + /** + * The display name of the Intelligence Configuration describing its purpose. + */ + "displayName": string; + /** + * The description of the Intelligence Configuration further explaining its purpose. + */ + "description"?: string; + /** + * List of Intelligence Configuration Rules that govern when and how Language Operators run. Each Rule represents a bundle of Operators, Triggers, Context, and Actions to be executed by the Intelligence Configuration on a Conversation. A maximum of five (5) Rules are allowed per Intelligence Configuration. + */ + "rules": Array; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + this.rules = payload["rules"]; + } +} + + + + + +/** + * Options to pass to update a ConfigurationInstance + */ +export interface ConfigurationContextUpdateOptions { + /** */ + "updateConfigurationRequest": UpdateConfigurationRequest; +} + +/** + * Options to pass to create a ConfigurationInstance + */ +export interface ConfigurationListInstanceCreateOptions { + /** */ + "createConfigurationRequest": CreateConfigurationRequest; +} + +/** + * Options to pass to each + */ +export interface ConfigurationListInstanceEachOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConfigurationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConfigurationListInstanceOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConfigurationListInstancePageOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; +} + + +export interface ConfigurationContext { + + /** + * Remove a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(params: UpdateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConfigurationContextSolution { + "id": string; +} + +export class ConfigurationContextImpl implements ConfigurationContext { + protected _solution: ConfigurationContextSolution; + protected _uri: string; + + + constructor(protected _version: V3, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/ControlPlane/Configurations/${id}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: UpdateConfigurationRequest, headers?: any,callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: UpdateConfigurationRequest, headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for Action + */ +export interface Action { + type: string; + method: string; + url: string; +} + +/** + * Nested model for Context + */ +export interface Context { + memory?: ContextMemory; + knowledge?: ContextKnowledge; +} + +/** + * Nested model for ContextKnowledge + */ +export interface ContextKnowledge { + bases: Array; +} + +/** + * Nested model for ContextMemory + */ +export interface ContextMemory { + enabled?: boolean; +} + +/** + * Nested model for CreateConfigurationRequest + */ +export interface CreateConfigurationRequest { + displayName: string; + description?: string; + rules: Array; +} + +/** + * Nested model for Operator + */ +export interface Operator { + id: string; + version?: number; + parameters?: Record; +} + +/** + * Nested model for Rule + */ +export interface Rule { + id: string; + operators: Array; + triggers: Array; + actions: Array; + context?: Context; +} + +/** + * Nested model for RuleCreationRequestPayload + */ +export interface RuleCreationRequestPayload { + operators: Array; + triggers?: Array; + actions: Array; + context?: Context; +} + +/** + * Nested model for RuleUpdateRequestPayload + */ +export interface RuleUpdateRequestPayload { + id?: string; + operators: Array; + triggers?: Array; + actions: Array; + context?: Context; +} + +/** + * Nested model for Trigger + */ +export interface Trigger { + on: string; + parameters?: TriggerParameters; +} + +/** + * Nested model for TriggerParameters + */ +export interface TriggerParameters { + count?: number; +} + +/** + * Nested model for UpdateConfigurationRequest + */ +export interface UpdateConfigurationRequest { + displayName: string; + description?: string; + rules: Array; +} + + + + interface ConfigurationPayload extends TokenPaginationPayload { + items: ConfigurationResource[]; +} + +/** + * Response model for CreateConfiguration201Response operations + */ +interface CreateConfiguration201Response_ResponseResource { + accountId: string; + id: string; + displayName: string; + description?: string; + version: number; + rules: Array; + dateCreated: Date; + dateUpdated: Date; +} + +/** + * Response model for IntelligenceConfiguration operations + */ +interface IntelligenceConfiguration_ResponseResource { + accountId: string; + id: string; + displayName: string; + description?: string; + version: number; + rules: Array; + dateCreated: Date; + dateUpdated: Date; +} + +/** + * Union type for all possible response models + */ +type ConfigurationResource = CreateConfiguration201Response_ResponseResource | IntelligenceConfiguration_ResponseResource; + +/** + * An Intelligence Configuration defines how and when Language Operators execute for a given conversation. To activate an Intelligence Configuration and trigger Operator execution, two conditions must be met: 1. The Intelligence Configuration must include at least one Rule. 2. The Intelligence Configuration must be attached to a Conversations Configuration via the Conversations API. Conversation traffic received by that Conversations Configuration determines when Rules are evaluated and executed. An Intelligence Configuration that has no Rules or is not attached to a Conversations Configuration will not execute. + */ +export class ConfigurationInstance { + protected _solution: ConfigurationContextSolution; + protected _context?: ConfigurationContext; + + constructor(protected _version: V3, _payload: ConfigurationResource, id?: string) { + const payload: any = _payload; + this.accountId = (payload.accountId); + this.id = (payload.id); + this.displayName = (payload.displayName); + this.description = (payload.description); + this.version = deserialize.integer(payload.version); + this.rules = payload.rules !== null && payload.rules !== undefined ? payload.rules.map( + (payload: any) => new Rule(payload) + ) : null; + this.dateCreated = deserialize.iso8601DateTime(payload.dateCreated); + this.dateUpdated = deserialize.iso8601DateTime(payload.dateUpdated); + + this._solution = { id: id, }; + } + + /** + * The ID of the Account that created the Intelligence Configuration. + */ + accountId?: string; + /** + * The unique identifier for the Intelligence Configuration. Assigned by Twilio (TTID). + */ + id?: string; + /** + * The display name of the Intelligence Configuration describing its purpose. + */ + displayName?: string; + /** + * The description of the Intelligence Configuration further explaining its purpose. + */ + description?: string; + /** + * The numeric version of the Intelligence Configuration. Automatically incremented with each update on the resource, used to ensure integrity when updating the Configuration. + */ + version?: number; + /** + * List of Intelligence Configuration Rules that govern when and how Language Operators run. Each Rule represents a bundle of Operators, Triggers, Context, and Actions to be executed by the Intelligence Configuration on a Conversation. A maximum of five (5) Rules are allowed per Intelligence Configuration. + */ + rules?: Array; + /** + * Timestamp of when the Intelligence Configuration was created. + */ + dateCreated?: Date; + /** + * Timestamp of when the Intelligence Configuration was last updated. + */ + dateUpdated?: Date; + + private get _proxy(): ConfigurationContext { + this._context = this._context || new ConfigurationContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Remove a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + update(params: UpdateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountId: this.accountId, + id: this.id, + displayName: this.displayName, + description: this.description, + version: this.version, + rules: this.rules, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConfigurationSolution { +} + +export interface ConfigurationListInstance { + _version: V3; + _solution: ConfigurationSolution; + _uri: string; + + (id: string, ): ConfigurationContext; + get(id: string, ): ConfigurationContext; + + + + + + + + + /** + * Create a ConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + create(params: CreateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise; + + /** + * Create a ConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ConfigurationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConfigurationInstance, done: (err?: Error) => void) => void): void; + each(params: ConfigurationListInstanceEachOptions, callback?: (item: ConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConfigurationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConfigurationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConfigurationListInstanceEachOptions, callback?: (item: ConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConfigurationPage) => any): Promise; + /** + * Retrieve a single target page of ConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConfigurationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConfigurationInstance[]) => any): Promise; + list(params: ConfigurationListInstanceOptions, callback?: (error: Error | null, items: ConfigurationInstance[]) => any): Promise; + /** + * Lists ConfigurationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConfigurationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConfigurationPage) => any): Promise; + page(params: ConfigurationListInstancePageOptions, callback?: (error: Error | null, items: ConfigurationPage) => any): Promise; + /** + * Retrieve a single page of ConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConfigurationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConfigurationListInstance(version: V3): ConfigurationListInstance { + const instance = ((id, ) => instance.get(id, )) as ConfigurationListInstance; + + instance.get = function get(id, ): ConfigurationContext { + return new ConfigurationContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ControlPlane/Configurations`; + + instance.create = function create(params: CreateConfigurationRequest, headers?: any, callback?: (error: Error | null, items: ConfigurationInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateConfigurationRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ConfigurationListInstancePageOptions | ((error: Error | null, items: ConfigurationPage) => any), callback?: (error: Error | null, items: ConfigurationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConfigurationPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConfigurationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConfigurationPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConfigurationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConfigurationPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConfigurationPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConfigurationPage extends TokenPage { +/** +* Initialize the ConfigurationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V3, response: Response, uri: string, params: any, solution: ConfigurationSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of ConfigurationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConfigurationResource): ConfigurationInstance { + + return new ConfigurationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v3/conversation.ts b/rest/intelligence/v3/conversation.ts new file mode 100644 index 000000000..d2b5b91b4 --- /dev/null +++ b/rest/intelligence/v3/conversation.ts @@ -0,0 +1,813 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Conversational Intelligence API + * The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Communication channel type. + */ +export type Channel = 'VOICE'|'SMS'|'RCS'|'EMAIL'|'WHATSAPP'|'CHAT'|'API'|'SYSTEM'; + +export class Communication { + /** + * Communication `id` from the attached Conversation. + */ + "id": string; + /** + * The `id` of the Participant in the Conversation. + */ + "participantId": string; + "content": Content; + /** + * The timestamp for when the Communication was created. + */ + "createdAt": Date; + + constructor(payload) { + this.id = payload["id"]; + this.participantId = payload["participantId"]; + this.content = payload["content"]; + this.createdAt = payload["createdAt"]; + } +} + + +/** + * The content of the communication. + */ +export class Content { + /** + * The transcript of the communication. + */ + "text"?: string; + + constructor(payload) { + this.text = payload["text"]; + } +} + + +/** + * The status of the Conversation. + */ +export type ConversationStatus = 'ACTIVE'|'INACTIVE'|'CLOSED'; + +export class Participant { + /** + * The `id` of the Participant in the Conversation. + */ + "id": string; + /** + * Participant display name. + */ + "name"?: string | null; + /** + * Type of participant in the conversation. Available types: - `CUSTOMER` - `HUMAN_AGENT` - `AI_AGENT` - `AGENT` - `UNKNOWN` + */ + "type"?: string | null; + /** + * Participant address values (for example, a phone number or sender identifier). + */ + "addressValues": Array; + + constructor(payload) { + this.id = payload["id"]; + this.name = payload["name"]; + this.type = payload["type"]; + this.addressValues = payload["addressValues"]; + } +} + + + + +/** + * Options to pass to each + */ +export interface ConversationListInstanceEachOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. */ + "createdAtBefore"?: Date; + /** Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. */ + "createdAtAfter"?: Date; + /** Filter by Conversation status. */ + "status"?: 'ACTIVE' | 'INACTIVE' | 'CLOSED'; + /** Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. */ + "channelId"?: string; + /** Filters Conversations that include one or more of the specified communication channels (`OR` match). */ + "channels"?: Array<'VOICE' | 'SMS' | 'RCS' | 'EMAIL' | 'WHATSAPP' | 'CHAT' | 'API' | 'SYSTEM'>; + /** The configuration `id` used to generate the Conversation. */ + "conversationConfigurationId"?: string; + /** Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). */ + "intelligenceConfigurationIds"?: Array; + /** Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). */ + "operatorIds"?: Array; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConversationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConversationListInstanceOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. */ + "createdAtBefore"?: Date; + /** Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. */ + "createdAtAfter"?: Date; + /** Filter by Conversation status. */ + "status"?: 'ACTIVE' | 'INACTIVE' | 'CLOSED'; + /** Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. */ + "channelId"?: string; + /** Filters Conversations that include one or more of the specified communication channels (`OR` match). */ + "channels"?: Array<'VOICE' | 'SMS' | 'RCS' | 'EMAIL' | 'WHATSAPP' | 'CHAT' | 'API' | 'SYSTEM'>; + /** The configuration `id` used to generate the Conversation. */ + "conversationConfigurationId"?: string; + /** Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). */ + "intelligenceConfigurationIds"?: Array; + /** Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). */ + "operatorIds"?: Array; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConversationListInstancePageOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. */ + "createdAtBefore"?: Date; + /** Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. */ + "createdAtAfter"?: Date; + /** Filter by Conversation status. */ + "status"?: 'ACTIVE' | 'INACTIVE' | 'CLOSED'; + /** Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. */ + "channelId"?: string; + /** Filters Conversations that include one or more of the specified communication channels (`OR` match). */ + "channels"?: Array<'VOICE' | 'SMS' | 'RCS' | 'EMAIL' | 'WHATSAPP' | 'CHAT' | 'API' | 'SYSTEM'>; + /** The configuration `id` used to generate the Conversation. */ + "conversationConfigurationId"?: string; + /** Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). */ + "intelligenceConfigurationIds"?: Array; + /** Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). */ + "operatorIds"?: Array; +} + + +export interface ConversationContext { + + /** + * Fetch a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + + /** + * Fetch a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConversationContextSolution { + "id": string; +} + +export class ConversationContextImpl implements ConversationContext { + protected _solution: ConversationContextSolution; + protected _uri: string; + + + constructor(protected _version: V3, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/Conversations/${id}`; + } + + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConversationInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ConversationInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for Communication + */ +export interface Communication { + id: string; + participantId: string; + content: Content; + createdAt: Date; +} + +/** + * Nested model for Content + */ +export interface Content { + text?: string; +} + +/** + * Nested model for Participant + */ +export interface Participant { + id: string; + name?: string; + type?: string; + addressValues: Array; +} + + + + interface ConversationPayload extends TokenPaginationPayload { + items: ConversationResource[]; +} + +/** + * Response model for FetchConversation200Response operations + */ +interface FetchConversation200Response_ResponseResource { + id: string; + accountId: string; + name: string; + status: ConversationStatus; + createdAt: Date; + updatedAt: Date; + intelligenceConfigurationIds: Array; + conversationConfigurationId: string; + channels: Array; + channelIds: Array; + participants: Array; + communications: Array; + operatorResultIds: Array; +} + +/** + * Response model for ConversationListItem operations + */ +interface ConversationListItem_ResponseResource { + id: string; + accountId: string; + name: string; + status: ConversationStatus; + createdAt: Date; + updatedAt: Date; + intelligenceConfigurationIds: Array; + conversationConfigurationId: string; + channels: Array; + channelIds: Array; + participants: Array; + operatorResultIds: Array; +} + +/** + * Union type for all possible response models + */ +type ConversationResource = FetchConversation200Response_ResponseResource | ConversationListItem_ResponseResource; + +export class ConversationInstance { + protected _solution: ConversationContextSolution; + protected _context?: ConversationContext; + + constructor(protected _version: V3, _payload: ConversationResource, id?: string) { + const payload: any = _payload; + this.id = (payload.id); + this.accountId = (payload.accountId); + this.name = (payload.name); + this.status = payload.status; + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + this.intelligenceConfigurationIds = (payload.intelligenceConfigurationIds); + this.conversationConfigurationId = (payload.conversationConfigurationId); + this.channels = (payload.channels); + this.channelIds = (payload.channelIds); + this.participants = payload.participants !== null && payload.participants !== undefined ? payload.participants.map( + (payload: any) => new Participant(payload) + ) : null; + this.communications = payload.communications !== null && payload.communications !== undefined ? payload.communications.map( + (payload: any) => new Communication(payload) + ) : null; + this.operatorResultIds = (payload.operatorResultIds); + + this._solution = { id: id, }; + } + + /** + * The `id` of the Conversation attached to the Operator Result. + */ + id?: string; + /** + * The ID of the account that owns the Conversation. + */ + accountId?: string; + /** + * Display name of the Conversation. + */ + name?: string; + status?: ConversationStatus; + /** + * Timestamp for when the Conversation was created. + */ + createdAt?: Date; + /** + * Timestamp for when the Conversation was last updated. + */ + updatedAt?: Date; + /** + * The Intelligence Configuration(s) associated with the Conversation. + */ + intelligenceConfigurationIds?: Array; + /** + * The `id` of the Configuration for a Conversation. + */ + conversationConfigurationId?: string; + /** + * The communication channel(s) included in the Conversation. + */ + channels?: Array; + /** + * The underlying channel resource `id`s associated with this Conversation, such as a Call ID or Message ID. + */ + channelIds?: Array; + /** + * Metadata for Participants of the Conversation. + */ + participants?: Array; + /** + * Metadata for the Communications that make up the Conversation. + */ + communications?: Array; + /** + * List of Operator Result IDs generated from this Conversation. + */ + operatorResultIds?: Array; + + private get _proxy(): ConversationContext { + this._context = this._context || new ConversationContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Fetch a ConversationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance + */ + fetch(callback?: (error: Error | null, item?: ConversationInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConversationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + accountId: this.accountId, + name: this.name, + status: this.status, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + intelligenceConfigurationIds: this.intelligenceConfigurationIds, + conversationConfigurationId: this.conversationConfigurationId, + channels: this.channels, + channelIds: this.channelIds, + participants: this.participants, + communications: this.communications, + operatorResultIds: this.operatorResultIds, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConversationSolution { +} + +export interface ConversationListInstance { + _version: V3; + _solution: ConversationSolution; + _uri: string; + + (id: string, ): ConversationContext; + get(id: string, ): ConversationContext; + + + + + + /** + * Streams ConversationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + each(params: ConversationListInstanceEachOptions, callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConversationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConversationListInstanceEachOptions, callback?: (item: ConversationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConversationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConversationPage) => any): Promise; + /** + * Retrieve a single target page of ConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ConversationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConversationInstance[]) => any): Promise; + list(params: ConversationListInstanceOptions, callback?: (error: Error | null, items: ConversationInstance[]) => any): Promise; + /** + * Lists ConversationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ConversationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ConversationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConversationPage) => any): Promise; + page(params: ConversationListInstancePageOptions, callback?: (error: Error | null, items: ConversationPage) => any): Promise; + /** + * Retrieve a single page of ConversationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ConversationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConversationListInstance(version: V3): ConversationListInstance { + const instance = ((id, ) => instance.get(id, )) as ConversationListInstance; + + instance.get = function get(id, ): ConversationContext { + return new ConversationContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Conversations`; + + instance.page = function page(params?: ConversationListInstancePageOptions | ((error: Error | null, items: ConversationPage) => any), callback?: (error: Error | null, items: ConversationPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["createdAtBefore"] !== undefined) + data["createdAtBefore"] = serialize.iso8601DateTime(params["createdAtBefore"]); + if (params["createdAtAfter"] !== undefined) + data["createdAtAfter"] = serialize.iso8601DateTime(params["createdAtAfter"]); + if (params["status"] !== undefined) + data["status"] = params["status"]; + if (params["channelId"] !== undefined) + data["channelId"] = params["channelId"]; + if (params["channels"] !== undefined) + data["channels"] = serialize.map(params["channels"], (e: string) => (e)); + if (params["conversationConfigurationId"] !== undefined) + data["conversationConfigurationId"] = params["conversationConfigurationId"]; + if (params["intelligenceConfigurationIds"] !== undefined) + data["intelligenceConfigurationIds"] = serialize.map(params["intelligenceConfigurationIds"], (e: string) => (e)); + if (params["operatorIds"] !== undefined) + data["operatorIds"] = serialize.map(params["operatorIds"], (e: string) => (e)); + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConversationPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConversationPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConversationPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConversationListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["createdAtBefore"] !== undefined) + data["createdAtBefore"] = serialize.iso8601DateTime(params["createdAtBefore"]); + if (params["createdAtAfter"] !== undefined) + data["createdAtAfter"] = serialize.iso8601DateTime(params["createdAtAfter"]); + if (params["status"] !== undefined) + data["status"] = params["status"]; + if (params["channelId"] !== undefined) + data["channelId"] = params["channelId"]; + if (params["channels"] !== undefined) + data["channels"] = serialize.map(params["channels"], (e: string) => (e)); + if (params["conversationConfigurationId"] !== undefined) + data["conversationConfigurationId"] = params["conversationConfigurationId"]; + if (params["intelligenceConfigurationIds"] !== undefined) + data["intelligenceConfigurationIds"] = serialize.map(params["intelligenceConfigurationIds"], (e: string) => (e)); + if (params["operatorIds"] !== undefined) + data["operatorIds"] = serialize.map(params["operatorIds"], (e: string) => (e)); + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConversationPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConversationPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConversationPage extends TokenPage { +/** +* Initialize the ConversationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V3, response: Response, uri: string, params: any, solution: ConversationSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of ConversationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConversationResource): ConversationInstance { + + return new ConversationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v3/operator.ts b/rest/intelligence/v3/operator.ts new file mode 100644 index 000000000..d4a50e764 --- /dev/null +++ b/rest/intelligence/v3/operator.ts @@ -0,0 +1,1121 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Conversational Intelligence API + * The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * A Language Operator resource. + */ +export class LanguageOperator { + /** + * The unique identifier for the Language Operator. Assigned by Twilio (TTID). + */ + "id"?: string; + /** + * Display name of the Language Operator describing its purpose. + */ + "displayName"?: string; + /** + * Description of the Language Operator further explaining its purpose. + */ + "description"?: string; + /** + * Numeric Operator version. Automatically incremented with each update on the resource, used to ensure integrity when updating the Operator. + */ + "version"?: number; + "author"?: OperatorOperatorAuthor; + /** + * The natural language instructions used by the operator to analyze the conversation. Within the prompt, users can reference parameters using the `{{parameters.[param_name]}}` syntax. Parameter values are provided to the Operator by the Intelligence Configuration Rule at runtime. **Note**: Prompts will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their prompts omitted from the API. + */ + "prompt"?: string; + "outputFormat"?: OperatorOutputFormat; + /** + * Required for `JSON` output only. this will be set to a JSON Schema object describing the properties & data types of the response. Please see https://platform.openai.com/docs/guides/structured-outputs#supported-schemas Will include the following keywords: - `type` : Must be set to `object` - `properties`: An object containing the property names and their data types you would like the LLM to return Additional details on JSON output formatting: - The root level `type` of a JSON schema must be set to `object` - The following property data types are supported : `string`, `number`, `boolean`, `integer`, `object`, `array`, `anyOf` - Definitions with `$defs` / `$ref` are supported - Max 100 object properties and 10 levels of nesting are supported - Max 1000 enum values across all enum properties are supported - Notable JSON Schema keywords not supported include: - For `strings`: `minLength`, `maxLength` - For `objects`: `patternProperties`, `unevaluatedProperties`, `propertyNames`, `minProperties`, `maxProperties` - For `arrays`: `unevaluatedItems`, `contains`, `minContains`, `maxContains`, `uniqueItems` - Structured Operator Results will be returned in the same order as the ordering of keys in the schema - In the event an Operator execution request is refused for safety reasons the Operator Result API response will include a new field called `refusal` to indicate that the LLM refused to fulfill the request - Twilio will automatically set `additionalProperties` to false and specify all provided fields as required (constraints of Structured Outputs). You don\'t need to pass these fields as part of your JSON schema. Twilio will automatically overwrite any user-provided values for these fields. + */ + "outputSchema"?: Record; + /** + * An array of example input/output pairs used to illustrate the intended behavior of the Language Operator. These examples help guide the model\'s understanding of expected input–output relationships and improve consistency during evaluation and testing. **Note**: Training examples will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their training examples omitted from the API. + */ + "trainingExamples"?: Array; + "context"?: OperatorContext; + /** + * Defines the schema of the parameters that are provided when running the operator, including required and optional values that determine the operator\'s behavior. The values of the parameters themselves are passed in by the attached Intelligence Configuration. + */ + "parameters"?: { [key: string]: OperatorParameter; }; + + constructor(payload) { + this.id = payload["id"]; + this.displayName = payload["displayName"]; + this.description = payload["description"]; + this.version = payload["version"]; + this.author = payload["author"]; + this.prompt = payload["prompt"]; + this.outputFormat = payload["outputFormat"]; + this.outputSchema = payload["outputSchema"]; + this.trainingExamples = payload["trainingExamples"]; + this.context = payload["context"]; + this.parameters = payload["parameters"]; + } +} + + +/** + * The creator and maintainer of the Language Operator. Available values: - `SELF` - Created and maintained by the customer (Custom Operator) - `TWILIO` - Created and maintained by Twilio (Twilio-Authored Operator) + */ +export type OperatorOperatorAuthor = 'SELF'|'TWILIO'; + +/** + * Optionally specifies which contextual data sources (Memory, Knowledge) the operator can access during execution. Context objects will be passed in by the Intelligence Configuration Rule at runtime. **Note**: this simply gives the LLM access to these context objects – ultimately the LLM will determine whether to actually call for context at runtime. + */ +export class OperatorContext { + "memory"?: OperatorContextMemory; + "knowledge"?: OperatorContextKnowledge; + + constructor(payload) { + this.memory = payload["memory"]; + this.knowledge = payload["knowledge"]; + } +} + + +/** + * Defines whether the Operator has access to organizational Knowledge Sources (e.g., policies, FAQs, scripts) at runtime. + */ +export class OperatorContextKnowledge { + /** + * Set to true to allow access to Knowledge Sources at runtime. + */ + "enabled"?: boolean; + + constructor(payload) { + this.enabled = payload["enabled"]; + } +} + + +/** + * Defines whether the Operator has access to Memory (past conversational memories and profile traits). + */ +export class OperatorContextMemory { + /** + * Set to true to allow access to Memory at runtime. + */ + "enabled"?: boolean; + + constructor(payload) { + this.enabled = payload["enabled"]; + } +} + + +/** + * The structure of the result returned by the Language Operator (specific to what the LLM returns, not the entirety of the Operator Result resource). Available values: - `TEXT`: The Operator will return plaintext from the LLM. - `JSON`: the Operator will return a structured object with schema defined in `output_schema` - `CLASSIFICATION`: The Operator will return the determined classifier string. + */ +export type OperatorOutputFormat = 'TEXT'|'JSON'|'CLASSIFICATION'; + +export class OperatorParameter { + /** + * The data type of the parameter (e.g., STRING, INTEGER). Available values: STRING, INTEGER, NUMBER, BOOLEAN, KNOWLEDGE_BASE_AND_SOURCE_IDS KNOWLEDGE_BASE_AND_SOURCE_IDS is a special type of parameter that refers to a Memora Knowledge Source, prefixed with its Knowledge Base container. Support for KB type = plaintext only. During Intelligence Configuration creation, this parameter is linked to a specific Knowledge Source. The operator receives the resolved plaintext at runtime and injects it into the prompt. The value of this parameter is expected to be passed in the following format: knowledge_base_id:knowledge_source_id. + */ + "type": string; + /** + * Default value to use in the prompt if no value is provided by the Intelligence Configuration. Note: knowledge_base_and_source_ids does not support the default attribute, but all other param types do allow for a default value. + */ + "_default"?: any | null; + /** + * Whether this parameter must be set at Operator execution time. Defaults to false if not provided. + */ + "required"?: boolean; + /** + * A human-readable description of the parameter. + */ + "description"?: string; + + constructor(payload) { + this.type = payload["type"]; + this._default = payload["default"]; + this.required = payload["required"]; + this.description = payload["description"]; + } +} + + +export class OperatorTrainingExample { + /** + * A sample input text that demonstrates the type of content the Operator processes. + */ + "input": string; + /** + * The expected output corresponding to the provided input example. This value must be consistent with the defined `output_format` and `output_schema` of the Operator. + */ + "output": string; + + constructor(payload) { + this.input = payload["input"]; + this.output = payload["output"]; + } +} + + + + + +/** + * Options to pass to update a OperatorInstance + */ +export interface OperatorContextUpdateOptions { + /** Full replacement of a Language Operator configuration */ + "languageOperator": LanguageOperator; + /** Current ETag/version required for conditional update */ + "ifMatch"?: string; +} + +/** + * Options to pass to create a OperatorInstance + */ +export interface OperatorListInstanceCreateOptions { + /** Create Language Operator request */ + "languageOperator": LanguageOperator; +} + +/** + * Options to pass to each + */ +export interface OperatorListInstanceEachOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: OperatorInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface OperatorListInstanceOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface OperatorListInstancePageOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; +} + + +export interface OperatorContext { + + /** + * Remove a OperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a OperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a OperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorInstance) => any): Promise + + /** + * Fetch a OperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a OperatorInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance + */ + update(params: LanguageOperator, headers?: any, callback?: (error: Error | null, item?: OperatorInstance) => any): Promise; + + /** + * Update a OperatorInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance with HTTP metadata + */ + updateWithHttpInfo(params: LanguageOperator, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OperatorContextSolution { + "id": string; +} + +export class OperatorContextImpl implements OperatorContext { + protected _solution: OperatorContextSolution; + protected _uri: string; + + + constructor(protected _version: V3, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/ControlPlane/Operators/${id}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: OperatorInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OperatorInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new OperatorInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: LanguageOperator, headers?: any,callback?: (error: Error | null, item?: OperatorInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new OperatorInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: LanguageOperator, headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new OperatorInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for LanguageOperator + */ +export interface LanguageOperator { + id?: string; + displayName?: string; + description?: string; + version?: number; + author?: OperatorOperatorAuthor; + prompt?: string; + outputFormat?: OperatorOutputFormat; + outputSchema?: Record; + trainingExamples?: Array; + context?: OperatorContext; + parameters?: { [key: string]: OperatorParameter; }; +} + +/** + * Nested model for OperatorContext + */ +export interface OperatorContext { + memory?: OperatorContextMemory; + knowledge?: OperatorContextKnowledge; +} + +/** + * Nested model for OperatorContextKnowledge + */ +export interface OperatorContextKnowledge { + enabled?: boolean; +} + +/** + * Nested model for OperatorContextMemory + */ +export interface OperatorContextMemory { + enabled?: boolean; +} + +/** + * Nested model for OperatorParameter + */ +export interface OperatorParameter { + type: string; + default?: any; + required?: boolean; + description?: string; +} + +/** + * Nested model for OperatorTrainingExample + */ +export interface OperatorTrainingExample { + input: string; + output: string; +} + + + + interface OperatorPayload extends TokenPaginationPayload { + items: OperatorResource[]; +} + +/** + * Response model for CreateOperator201Response operations + */ +interface CreateOperator201Response_ResponseResource { + id?: string; + displayName?: string; + description?: string; + version?: number; + author?: OperatorOperatorAuthor; + prompt?: string; + outputFormat?: OperatorOutputFormat; + outputSchema?: Record; + trainingExamples?: Array; + context?: OperatorContext; + parameters?: { [key: string]: OperatorParameter; }; +} + +/** + * Response model for LanguageOperator operations + */ +interface LanguageOperator_ResponseResource { + id?: string; + displayName?: string; + description?: string; + version?: number; + author?: OperatorOperatorAuthor; + prompt?: string; + outputFormat?: OperatorOutputFormat; + outputSchema?: Record; + trainingExamples?: Array; + context?: OperatorContext; + parameters?: { [key: string]: OperatorParameter; }; +} + +/** + * Union type for all possible response models + */ +type OperatorResource = CreateOperator201Response_ResponseResource | LanguageOperator_ResponseResource; + +/** + * A Language Operator resource. + */ +export class OperatorInstance { + protected _solution: OperatorContextSolution; + protected _context?: OperatorContext; + + constructor(protected _version: V3, _payload: OperatorResource, id?: string) { + const payload: any = _payload; + this.id = (payload.id); + this.displayName = (payload.displayName); + this.description = (payload.description); + this.version = deserialize.integer(payload.version); + this.author = payload.author; + this.prompt = (payload.prompt); + this.outputFormat = payload.outputFormat; + this.outputSchema = (payload.outputSchema); + this.trainingExamples = payload.trainingExamples !== null && payload.trainingExamples !== undefined ? payload.trainingExamples.map( + (payload: any) => new OperatorTrainingExample(payload) + ) : null; + this.context = payload.context !== null && payload.context !== undefined ? new OperatorContext(payload.context) : null; + this.parameters = payload.parameters; + + this._solution = { id: id, }; + } + + /** + * The unique identifier for the Language Operator. Assigned by Twilio (TTID). + */ + id?: string; + /** + * Display name of the Language Operator describing its purpose. + */ + displayName?: string; + /** + * Description of the Language Operator further explaining its purpose. + */ + description?: string; + /** + * Numeric Operator version. Automatically incremented with each update on the resource, used to ensure integrity when updating the Operator. + */ + version?: number; + author?: OperatorOperatorAuthor; + /** + * The natural language instructions used by the operator to analyze the conversation. Within the prompt, users can reference parameters using the `{{parameters.[param_name]}}` syntax. Parameter values are provided to the Operator by the Intelligence Configuration Rule at runtime. **Note**: Prompts will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their prompts omitted from the API. + */ + prompt?: string; + outputFormat?: OperatorOutputFormat; + /** + * Required for `JSON` output only. this will be set to a JSON Schema object describing the properties & data types of the response. Please see https://platform.openai.com/docs/guides/structured-outputs#supported-schemas Will include the following keywords: - `type` : Must be set to `object` - `properties`: An object containing the property names and their data types you would like the LLM to return Additional details on JSON output formatting: - The root level `type` of a JSON schema must be set to `object` - The following property data types are supported : `string`, `number`, `boolean`, `integer`, `object`, `array`, `anyOf` - Definitions with `$defs` / `$ref` are supported - Max 100 object properties and 10 levels of nesting are supported - Max 1000 enum values across all enum properties are supported - Notable JSON Schema keywords not supported include: - For `strings`: `minLength`, `maxLength` - For `objects`: `patternProperties`, `unevaluatedProperties`, `propertyNames`, `minProperties`, `maxProperties` - For `arrays`: `unevaluatedItems`, `contains`, `minContains`, `maxContains`, `uniqueItems` - Structured Operator Results will be returned in the same order as the ordering of keys in the schema - In the event an Operator execution request is refused for safety reasons the Operator Result API response will include a new field called `refusal` to indicate that the LLM refused to fulfill the request - Twilio will automatically set `additionalProperties` to false and specify all provided fields as required (constraints of Structured Outputs). You don\'t need to pass these fields as part of your JSON schema. Twilio will automatically overwrite any user-provided values for these fields. + */ + outputSchema?: Record; + /** + * An array of example input/output pairs used to illustrate the intended behavior of the Language Operator. These examples help guide the model\'s understanding of expected input–output relationships and improve consistency during evaluation and testing. **Note**: Training examples will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their training examples omitted from the API. + */ + trainingExamples?: Array; + context?: OperatorContext; + /** + * Defines the schema of the parameters that are provided when running the operator, including required and optional values that determine the operator\'s behavior. The values of the parameters themselves are passed in by the attached Intelligence Configuration. + */ + parameters?: { [key: string]: OperatorParameter; }; + + private get _proxy(): OperatorContext { + this._context = this._context || new OperatorContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Remove a OperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a OperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a OperatorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a OperatorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a OperatorInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance + */ + update(params: LanguageOperator, headers?: any, callback?: (error: Error | null, item?: OperatorInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: OperatorInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a OperatorInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance with HTTP metadata + */ + updateWithHttpInfo(params: LanguageOperator, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + displayName: this.displayName, + description: this.description, + version: this.version, + author: this.author, + prompt: this.prompt, + outputFormat: this.outputFormat, + outputSchema: this.outputSchema, + trainingExamples: this.trainingExamples, + context: this.context, + parameters: this.parameters, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OperatorSolution { +} + +export interface OperatorListInstance { + _version: V3; + _solution: OperatorSolution; + _uri: string; + + (id: string, ): OperatorContext; + get(id: string, ): OperatorContext; + + + + + + + + + /** + * Create a OperatorInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance + */ + create(params: LanguageOperator, headers?: any, callback?: (error: Error | null, item?: OperatorInstance) => any): Promise; + + /** + * Create a OperatorInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorInstance with HTTP metadata + */ + createWithHttpInfo(params: LanguageOperator, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams OperatorInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: OperatorInstance, done: (err?: Error) => void) => void): void; + each(params: OperatorListInstanceEachOptions, callback?: (item: OperatorInstance, done: (err?: Error) => void) => void): void; + /** + * Streams OperatorInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: OperatorInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: OperatorListInstanceEachOptions, callback?: (item: OperatorInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of OperatorInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: OperatorPage) => any): Promise; + /** + * Retrieve a single target page of OperatorInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists OperatorInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: OperatorInstance[]) => any): Promise; + list(params: OperatorListInstanceOptions, callback?: (error: Error | null, items: OperatorInstance[]) => any): Promise; + /** + * Lists OperatorInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: OperatorListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of OperatorInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: OperatorPage) => any): Promise; + page(params: OperatorListInstancePageOptions, callback?: (error: Error | null, items: OperatorPage) => any): Promise; + /** + * Retrieve a single page of OperatorInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: OperatorListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OperatorListInstance(version: V3): OperatorListInstance { + const instance = ((id, ) => instance.get(id, )) as OperatorListInstance; + + instance.get = function get(id, ): OperatorContext { + return new OperatorContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ControlPlane/Operators`; + + instance.create = function create(params: LanguageOperator, headers?: any, callback?: (error: Error | null, items: OperatorInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new OperatorInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: LanguageOperator, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new OperatorInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: OperatorListInstancePageOptions | ((error: Error | null, items: OperatorPage) => any), callback?: (error: Error | null, items: OperatorPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new OperatorPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: OperatorPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new OperatorPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: OperatorListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OperatorPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OperatorPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class OperatorPage extends TokenPage { +/** +* Initialize the OperatorPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V3, response: Response, uri: string, params: any, solution: OperatorSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of OperatorInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: OperatorResource): OperatorInstance { + + return new OperatorInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v3/operatorResult.ts b/rest/intelligence/v3/operatorResult.ts new file mode 100644 index 000000000..91ce96a58 --- /dev/null +++ b/rest/intelligence/v3/operatorResult.ts @@ -0,0 +1,956 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Conversational Intelligence API + * The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Details about the conditions under which the Operator executed. + */ +export class ExecutionDetails { + "trigger": ExecutionDetailsTrigger; + "communications": ExecutionDetailsCommunications; + /** + * Communication channels included in the Conversation when this Operator was executed. + */ + "channels": Array; + /** + * Metadata for the participants included in the Conversation when this Operator executed. + */ + "participants": Array; + "resolvedContext"?: ResolvedContext; + + constructor(payload) { + this.trigger = payload["trigger"]; + this.communications = payload["communications"]; + this.channels = payload["channels"]; + this.participants = payload["participants"]; + this.resolvedContext = payload["resolvedContext"]; + } +} + + +/** + * Range of first and last communications in the Conversation that were processed during this Operator execution. + */ +export class ExecutionDetailsCommunications { + /** + * Communication `id` from the attached Conversation. + */ + "first": string; + /** + * Communication `id` from the attached Conversation. + */ + "last": string; + + constructor(payload) { + this.first = payload["first"]; + this.last = payload["last"]; + } +} + + +export class ExecutionDetailsParticipants { + /** + * The `id` of the Participant in the Conversation. + */ + "id": string; + /** + * Customer Memory Profile identifier + */ + "profileId"?: string; + /** + * Type of participant in the conversation. Available types: - `CUSTOMER` - `HUMAN_AGENT` - `AI_AGENT` - `AGENT` - `UNKNOWN` + */ + "type"?: string; + + constructor(payload) { + this.id = payload["id"]; + this.profileId = payload["profileId"]; + this.type = payload["type"]; + } +} + + +/** + * Metadata for the trigger that generated this Operator Result. + */ +export class ExecutionDetailsTrigger { + /** + * The conversational lifecycle event that activated execution of the Rule. Available values are: - `COMMUNICATION`: Trigger the Rule on each communication within the Conversation. - `CONVERSATION_END`: Trigger the Rule when the Conversation moves to the `closed` state. - `CONVERSATION_INACTIVE`: Trigger the Rule when the Conversation moves to the `inactive` state. + */ + "on": string; + /** + * Timestamp of when the trigger was activated. + */ + "timestamp": Date; + + constructor(payload) { + this.on = payload["on"]; + this.timestamp = payload["timestamp"]; + } +} + + +/** + * The actual result from executing the Language Operator with `EXTRACTION` output format. + */ +export class ExtractionResultResult { + /** + * List of extracted entities from the Conversation. + */ + "entities": Array; + + constructor(payload) { + this.entities = payload["entities"]; + } +} + + +export class ExtractionResultResultEntities { + /** + * The actual text of the extracted entity as it appears in the Conversation. + */ + "text": string; + /** + * The label for the extracted entity (e.g., `PERSON`, `LOCATION`). + */ + "label": string; + + constructor(payload) { + this.text = payload["text"]; + this.label = payload["label"]; + } +} + + +/** + * Reference to the Intelligence Configuration that generated the Operator Result. + */ +export class IntelligenceConfigurationReference { + /** + * Unique identifier for a Intelligence Configuration that generated the Operator Result. Assigned by Twilio (TTID). + */ + "id": string; + /** + * Unique identifier of the rule of the Intelligence Configuration that triggered the result. Assigned by Twilio (TTID). + */ + "ruleId": string; + /** + * Version of the Intelligence Configuration used to generate the Operator Result. + */ + "version": number; + + constructor(payload) { + this.id = payload["id"]; + this.ruleId = payload["ruleId"]; + this.version = payload["version"]; + } +} + + +/** + * Reference to the Language Operator that generated the Operator Result. + */ +export class OperatorReference { + /** + * The `id` of the Language Operator. + */ + "id": string; + /** + * Version of the Language Operator used to generate the Operator Result. + */ + "version": number; + /** + * Parameter values used for Operator execution, provided by the Rule at runtime. This object contains a dictionary of parameter keys and their corresponding values. + */ + "parameters": { [key: string]: any; }; + + constructor(payload) { + this.id = payload["id"]; + this.version = payload["version"]; + this.parameters = payload["parameters"]; + } +} + + +export class OperatorResultsResponseBaseMetadata { + "system": SystemMetaData; + + constructor(payload) { + this.system = payload["system"]; + } +} + + +/** + * The context that was actually used by the operator during execution + */ +export class ResolvedContext { + "memory"?: ResolvedContextMemory; + "knowledge"?: ResolvedContextKnowledge | null; + + constructor(payload) { + this.memory = payload["memory"]; + this.knowledge = payload["knowledge"]; + } +} + + +/** + * Knowledge source IDs with their respective knowledge base ID that was accessed and used by the LLM to generate the result. null if no knowledge was accessed. + */ +export class ResolvedContextKnowledge { + "sources": Array; + + constructor(payload) { + this.sources = payload["sources"]; + } +} + + +export class ResolvedContextKnowledgeSources { + /** + * Knowledge base identifier + */ + "baseId": string; + /** + * Knowledge source identifier + */ + "sourceId": string; + + constructor(payload) { + this.baseId = payload["baseId"]; + this.sourceId = payload["sourceId"]; + } +} + + +/** + * The customer profile that was accessed. null if no memory was accessed. Either observations and/or traits from the profile were used by the LLM to generate the result. + */ +export class ResolvedContextMemory { + /** + * Customer Memory Profile identifier + */ + "profileId": string; + /** + * Customer Memory store identifier + */ + "memoryStoreId": string; + + constructor(payload) { + this.profileId = payload["profileId"]; + this.memoryStoreId = payload["memoryStoreId"]; + } +} + + +export class SystemMetaData { + /** + * The underlying LLM model used for this execution. + */ + "resolvedModel"?: string; + /** + * Operator execution time in milliseconds. + */ + "latencyMs": number; + /** + * Number of characters in the input sent to the model. Aligns with the billing unit. + */ + "inputCharacters": number; + /** + * Number of characters in the model\'s response. Aligns with the billing unit. + */ + "outputCharacters": number; + /** + * Whether the conversation input was truncated to fit the model\'s context window. + */ + "inputTruncated": boolean; + + constructor(payload) { + this.resolvedModel = payload["resolvedModel"]; + this.latencyMs = payload["latencyMs"]; + this.inputCharacters = payload["inputCharacters"]; + this.outputCharacters = payload["outputCharacters"]; + this.inputTruncated = payload["inputTruncated"]; + } +} + + + + + +/** + * Options to pass to each + */ +export interface OperatorResultListInstanceEachOptions { + /** Filter Operator Results by attached Conversation `id`. */ + "conversationId"?: string; + /** Filter Operator Results by Intelligence Configuration `id` used to generate them. */ + "intelligenceConfigurationId"?: string; + /** Filter Operator Results by Language Operator `id`. */ + "operatorId"?: string; + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: OperatorResultInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface OperatorResultListInstanceOptions { + /** Filter Operator Results by attached Conversation `id`. */ + "conversationId"?: string; + /** Filter Operator Results by Intelligence Configuration `id` used to generate them. */ + "intelligenceConfigurationId"?: string; + /** Filter Operator Results by Language Operator `id`. */ + "operatorId"?: string; + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface OperatorResultListInstancePageOptions { + /** Filter Operator Results by attached Conversation `id`. */ + "conversationId"?: string; + /** Filter Operator Results by Intelligence Configuration `id` used to generate them. */ + "intelligenceConfigurationId"?: string; + /** Filter Operator Results by Language Operator `id`. */ + "operatorId"?: string; + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; +} + + +export interface OperatorResultContext { + + /** + * Remove a OperatorResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a OperatorResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a OperatorResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorResultInstance) => any): Promise + + /** + * Fetch a OperatorResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OperatorResultContextSolution { + "operatorResultId": string; +} + +export class OperatorResultContextImpl implements OperatorResultContext { + protected _solution: OperatorResultContextSolution; + protected _uri: string; + + + constructor(protected _version: V3, operatorResultId: string) { + if (!isValidPathParam(operatorResultId)) { + throw new Error('Parameter \'operatorResultId\' is not valid.'); + } + + this._solution = { operatorResultId, }; + this._uri = `/OperatorResults/${operatorResultId}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: OperatorResultInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OperatorResultInstance(operationVersion, payload, instance._solution.operatorResultId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new OperatorResultInstance(operationVersion, response.body, instance._solution.operatorResultId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface OperatorResultPayload extends TokenPaginationPayload { + items: OperatorResultResource[]; +} + +interface OperatorResultResource { + outputFormat: string; + id: string; + accountId: string; + intelligenceConfiguration: IntelligenceConfigurationReference; + conversationId: string; + operator: OperatorReference; + dateCreated: Date; + referenceIds: Array; + executionDetails: ExecutionDetails; + metadata: OperatorResultsResponseBaseMetadata; + result: ExtractionResultResult; +} + +export class OperatorResultInstance { + protected _solution: OperatorResultContextSolution; + protected _context?: OperatorResultContext; + + constructor(protected _version: V3, _payload: OperatorResultResource, operatorResultId?: string) { + const payload = _payload; + this.outputFormat = (payload.outputFormat); + this.id = (payload.id); + this.accountId = (payload.accountId); + this.intelligenceConfiguration = payload.intelligenceConfiguration !== null && payload.intelligenceConfiguration !== undefined ? new IntelligenceConfigurationReference(payload.intelligenceConfiguration) : null; + this.conversationId = (payload.conversationId); + this.operator = payload.operator !== null && payload.operator !== undefined ? new OperatorReference(payload.operator) : null; + this.dateCreated = deserialize.iso8601DateTime(payload.dateCreated); + this.referenceIds = (payload.referenceIds); + this.executionDetails = payload.executionDetails !== null && payload.executionDetails !== undefined ? new ExecutionDetails(payload.executionDetails) : null; + this.metadata = payload.metadata !== null && payload.metadata !== undefined ? new OperatorResultsResponseBaseMetadata(payload.metadata) : null; + this.result = payload.result !== null && payload.result !== undefined ? new ExtractionResultResult(payload.result) : null; + + this._solution = { operatorResultId: operatorResultId, }; + } + + /** + * The output format set on the Operator that generated this result. Determines the structure of the `result` object. + */ + outputFormat: string; + /** + * A unique identifier for the Operator Result. Assigned by Twilio (TTID). + */ + id: string; + /** + * The ID of the Account that created the Language Operator. + */ + accountId: string; + intelligenceConfiguration: IntelligenceConfigurationReference; + /** + * The `id` of the Conversation attached to the Operator Result. + */ + conversationId: string; + operator: OperatorReference; + /** + * Timestamp for when the Operator Result was created. + */ + dateCreated: Date; + /** + * The `id`s of objects related to this Operator Result. + */ + referenceIds: Array; + executionDetails: ExecutionDetails; + metadata: OperatorResultsResponseBaseMetadata; + result: ExtractionResultResult; + + private get _proxy(): OperatorResultContext { + this._context = this._context || new OperatorResultContextImpl(this._version, this._solution.operatorResultId); + return this._context; + } + + /** + * Remove a OperatorResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a OperatorResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a OperatorResultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance + */ + fetch(callback?: (error: Error | null, item?: OperatorResultInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a OperatorResultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperatorResultInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + outputFormat: this.outputFormat, + id: this.id, + accountId: this.accountId, + intelligenceConfiguration: this.intelligenceConfiguration, + conversationId: this.conversationId, + operator: this.operator, + dateCreated: this.dateCreated, + referenceIds: this.referenceIds, + executionDetails: this.executionDetails, + metadata: this.metadata, + result: this.result, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OperatorResultSolution { +} + +export interface OperatorResultListInstance { + _version: V3; + _solution: OperatorResultSolution; + _uri: string; + + (operatorResultId: string, ): OperatorResultContext; + get(operatorResultId: string, ): OperatorResultContext; + + + + + + + + /** + * Streams OperatorResultInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: OperatorResultInstance, done: (err?: Error) => void) => void): void; + each(params: OperatorResultListInstanceEachOptions, callback?: (item: OperatorResultInstance, done: (err?: Error) => void) => void): void; + /** + * Streams OperatorResultInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: OperatorResultInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: OperatorResultListInstanceEachOptions, callback?: (item: OperatorResultInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of OperatorResultInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: OperatorResultPage) => any): Promise; + /** + * Retrieve a single target page of OperatorResultInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists OperatorResultInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: OperatorResultInstance[]) => any): Promise; + list(params: OperatorResultListInstanceOptions, callback?: (error: Error | null, items: OperatorResultInstance[]) => any): Promise; + /** + * Lists OperatorResultInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: OperatorResultListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of OperatorResultInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: OperatorResultPage) => any): Promise; + page(params: OperatorResultListInstancePageOptions, callback?: (error: Error | null, items: OperatorResultPage) => any): Promise; + /** + * Retrieve a single page of OperatorResultInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OperatorResultListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: OperatorResultListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OperatorResultListInstance(version: V3): OperatorResultListInstance { + const instance = ((operatorResultId, ) => instance.get(operatorResultId, )) as OperatorResultListInstance; + + instance.get = function get(operatorResultId, ): OperatorResultContext { + return new OperatorResultContextImpl(version, operatorResultId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/OperatorResults`; + + instance.page = function page(params?: OperatorResultListInstancePageOptions | ((error: Error | null, items: OperatorResultPage) => any), callback?: (error: Error | null, items: OperatorResultPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["conversationId"] !== undefined) + data["conversationId"] = params["conversationId"]; + if (params["intelligenceConfigurationId"] !== undefined) + data["intelligenceConfigurationId"] = params["intelligenceConfigurationId"]; + if (params["operatorId"] !== undefined) + data["operatorId"] = params["operatorId"]; + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new OperatorResultPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: OperatorResultPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new OperatorResultPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: OperatorResultListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["conversationId"] !== undefined) + data["conversationId"] = params["conversationId"]; + if (params["intelligenceConfigurationId"] !== undefined) + data["intelligenceConfigurationId"] = params["intelligenceConfigurationId"]; + if (params["operatorId"] !== undefined) + data["operatorId"] = params["operatorId"]; + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OperatorResultPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OperatorResultPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class OperatorResultPage extends TokenPage { +/** +* Initialize the OperatorResultPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V3, response: Response, uri: string, params: any, solution: OperatorResultSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of OperatorResultInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: OperatorResultResource): OperatorResultInstance { + + return new OperatorResultInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/intelligence/v3/ruleExecution.ts b/rest/intelligence/v3/ruleExecution.ts new file mode 100644 index 000000000..cd2e4025a --- /dev/null +++ b/rest/intelligence/v3/ruleExecution.ts @@ -0,0 +1,176 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Conversational Intelligence API + * The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class CreateRuleExecutionRequest { + /** + * The Intelligence Configuration identifier to execute the Rule within. + */ + "intelligenceConfigurationId": string; + /** + * The rule identifier to execute within the selected Intelligence Configuration. + */ + "ruleId": string; + /** + * The Conversation identifier to execute the Rule against. + */ + "conversationId": string; + + constructor(payload) { + this.intelligenceConfigurationId = payload["intelligenceConfigurationId"]; + this.ruleId = payload["ruleId"]; + this.conversationId = payload["conversationId"]; + } +} + + + +/** + * Options to pass to create a RuleExecutionInstance + */ +export interface RuleExecutionListInstanceCreateOptions { + /** */ + "createRuleExecutionRequest": CreateRuleExecutionRequest; +} + + +export interface RuleExecutionSolution { +} + +export interface RuleExecutionListInstance { + _version: V3; + _solution: RuleExecutionSolution; + _uri: string; + + + + /** + * Create a RuleExecutionInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RuleExecutionInstance + */ + create(params: CreateRuleExecutionRequest, headers?: any, callback?: (error: Error | null, item?: RuleExecutionInstance) => any): Promise; + + /** + * Create a RuleExecutionInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RuleExecutionInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateRuleExecutionRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RuleExecutionListInstance(version: V3): RuleExecutionListInstance { + const instance = {} as RuleExecutionListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/RuleExecutions`; + + instance.create = function create(params: CreateRuleExecutionRequest, headers?: any, callback?: (error: Error | null, items: RuleExecutionInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RuleExecutionInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateRuleExecutionRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RuleExecutionInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/intelligence/v3/version.ts b/rest/intelligence/v3/version.ts new file mode 100644 index 000000000..a02890aa9 --- /dev/null +++ b/rest/intelligence/v3/version.ts @@ -0,0 +1,788 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Conversational Intelligence API + * The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The creator and maintainer of the Language Operator. Available values: - `SELF` - Created and maintained by the customer (Custom Operator) - `TWILIO` - Created and maintained by Twilio (Twilio-Authored Operator) + */ +export type VersionOperatorAuthor = 'SELF'|'TWILIO'; + +/** + * Optionally specifies which contextual data sources (Memory, Knowledge) the operator can access during execution. Context objects will be passed in by the Intelligence Configuration Rule at runtime. **Note**: this simply gives the LLM access to these context objects – ultimately the LLM will determine whether to actually call for context at runtime. + */ +export class OperatorContext { + "memory"?: OperatorContextMemory; + "knowledge"?: OperatorContextKnowledge; + + constructor(payload) { + this.memory = payload["memory"]; + this.knowledge = payload["knowledge"]; + } +} + + +/** + * Defines whether the Operator has access to organizational Knowledge Sources (e.g., policies, FAQs, scripts) at runtime. + */ +export class OperatorContextKnowledge { + /** + * Set to true to allow access to Knowledge Sources at runtime. + */ + "enabled"?: boolean; + + constructor(payload) { + this.enabled = payload["enabled"]; + } +} + + +/** + * Defines whether the Operator has access to Memory (past conversational memories and profile traits). + */ +export class OperatorContextMemory { + /** + * Set to true to allow access to Memory at runtime. + */ + "enabled"?: boolean; + + constructor(payload) { + this.enabled = payload["enabled"]; + } +} + + +/** + * The structure of the result returned by the Language Operator (specific to what the LLM returns, not the entirety of the Operator Result resource). Available values: - `TEXT`: The Operator will return plaintext from the LLM. - `JSON`: the Operator will return a structured object with schema defined in `output_schema` - `CLASSIFICATION`: The Operator will return the determined classifier string. + */ +export type OperatorOutputFormat = 'TEXT'|'JSON'|'CLASSIFICATION'; + +export class OperatorParameter { + /** + * The data type of the parameter (e.g., STRING, INTEGER). Available values: STRING, INTEGER, NUMBER, BOOLEAN, KNOWLEDGE_BASE_AND_SOURCE_IDS KNOWLEDGE_BASE_AND_SOURCE_IDS is a special type of parameter that refers to a Memora Knowledge Source, prefixed with its Knowledge Base container. Support for KB type = plaintext only. During Intelligence Configuration creation, this parameter is linked to a specific Knowledge Source. The operator receives the resolved plaintext at runtime and injects it into the prompt. The value of this parameter is expected to be passed in the following format: knowledge_base_id:knowledge_source_id. + */ + "type": string; + /** + * Default value to use in the prompt if no value is provided by the Intelligence Configuration. Note: knowledge_base_and_source_ids does not support the default attribute, but all other param types do allow for a default value. + */ + "_default"?: any | null; + /** + * Whether this parameter must be set at Operator execution time. Defaults to false if not provided. + */ + "required"?: boolean; + /** + * A human-readable description of the parameter. + */ + "description"?: string; + + constructor(payload) { + this.type = payload["type"]; + this._default = payload["default"]; + this.required = payload["required"]; + this.description = payload["description"]; + } +} + + +export class OperatorTrainingExample { + /** + * A sample input text that demonstrates the type of content the Operator processes. + */ + "input": string; + /** + * The expected output corresponding to the provided input example. This value must be consistent with the defined `output_format` and `output_schema` of the Operator. + */ + "output": string; + + constructor(payload) { + this.input = payload["input"]; + this.output = payload["output"]; + } +} + + +/** + * The lifecycle status of an Operator version. Available values: - `PREVIEW`: Available but restricted to internal/testing visibility. Normal execution. - `ACTIVE`: Available for normal use. - `DEPRECATED`: Still executes normally, but a Warn event is emitted via the Watch product lifecycle system. Customers should migrate to a newer version. - `RETIRED`: Hard failure on execution. An Error is logged in Watch. Customers must manually update their Intelligence Configuration to a valid version. + */ +export type OperatorVersionStatus = 'PREVIEW'|'ACTIVE'|'DEPRECATED'|'RETIRED'; + + + +/** + * Options to pass to each + */ +export interface VersionListInstanceEachOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: VersionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface VersionListInstanceOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface VersionListInstancePageOptions { + /** The maximum number of resources to return */ + "pageSize"?: number; + /** Token for pagination */ + "pageToken"?: string; +} + + +export interface VersionContext { + + /** + * Fetch a VersionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VersionInstance + */ + fetch(callback?: (error: Error | null, item?: VersionInstance) => any): Promise + + /** + * Fetch a VersionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VersionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface VersionContextSolution { + "id": string; + "versionParam": number; +} + +export class VersionContextImpl implements VersionContext { + protected _solution: VersionContextSolution; + protected _uri: string; + + + constructor(protected _version: V3, id: string, versionParam: number) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + if (!isValidPathParam(versionParam)) { + throw new Error('Parameter \'versionParam\' is not valid.'); + } + + this._solution = { id, versionParam, }; + this._uri = `/ControlPlane/Operators/${id}/Versions/${versionParam}`; + } + + fetch(callback?: (error: Error | null, item?: VersionInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new VersionInstance(operationVersion, payload, instance._solution.id, instance._solution.versionParam)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new VersionInstance(operationVersion, response.body, instance._solution.id, instance._solution.versionParam) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for OperatorContext + */ +export interface OperatorContext { + memory?: OperatorContextMemory; + knowledge?: OperatorContextKnowledge; +} + +/** + * Nested model for OperatorContextKnowledge + */ +export interface OperatorContextKnowledge { + enabled?: boolean; +} + +/** + * Nested model for OperatorContextMemory + */ +export interface OperatorContextMemory { + enabled?: boolean; +} + +/** + * Nested model for OperatorParameter + */ +export interface OperatorParameter { + type: string; + default?: any; + required?: boolean; + description?: string; +} + +/** + * Nested model for OperatorTrainingExample + */ +export interface OperatorTrainingExample { + input: string; + output: string; +} + + + + interface VersionPayload extends TokenPaginationPayload { + items: VersionResource[]; +} + +/** + * Response model for FetchOperatorVersion200Response operations + */ +interface FetchOperatorVersion200Response_ResponseResource { + id?: string; + displayName?: string; + description?: string; + version?: number; + author?: VersionOperatorAuthor; + prompt?: string; + outputFormat?: OperatorOutputFormat; + outputSchema?: Record; + trainingExamples?: Array; + context?: OperatorContext; + parameters?: { [key: string]: OperatorParameter; }; + status: OperatorVersionStatus; + dateCreated: Date; +} + +/** + * Response model for ListOperatorVersions200ResponseItems operations + */ +interface ListOperatorVersions200ResponseItems_ResponseResource { + version: number; + status: OperatorVersionStatus; + dateCreated: Date; + dateDeprecated?: Date; + retirementDate?: Date; + dateRetired?: Date; +} + +/** + * Union type for all possible response models + */ +type VersionResource = FetchOperatorVersion200Response_ResponseResource | ListOperatorVersions200ResponseItems_ResponseResource; + +/** + * Full detail of a specific Language Operator version. + */ +export class VersionInstance { + protected _solution: VersionContextSolution; + protected _context?: VersionContext; + + constructor(protected _version: V3, _payload: VersionResource, id: string, versionParam?: number) { + const payload: any = _payload; + this.id = (payload.id); + this.displayName = (payload.displayName); + this.description = (payload.description); + this.version = deserialize.integer(payload.version); + this.author = payload.author; + this.prompt = (payload.prompt); + this.outputFormat = payload.outputFormat; + this.outputSchema = (payload.outputSchema); + this.trainingExamples = payload.trainingExamples !== null && payload.trainingExamples !== undefined ? payload.trainingExamples.map( + (payload: any) => new OperatorTrainingExample(payload) + ) : null; + this.context = payload.context !== null && payload.context !== undefined ? new OperatorContext(payload.context) : null; + this.parameters = payload.parameters; + this.status = payload.status; + this.dateCreated = deserialize.iso8601DateTime(payload.dateCreated); + this.dateDeprecated = deserialize.iso8601DateTime(payload.dateDeprecated); + this.retirementDate = deserialize.iso8601DateTime(payload.retirementDate); + this.dateRetired = deserialize.iso8601DateTime(payload.dateRetired); + + this._solution = { id, versionParam: versionParam, }; + } + + /** + * The unique identifier for the Language Operator. Assigned by Twilio (TTID). + */ + id?: string; + /** + * Display name of the Language Operator describing its purpose. + */ + displayName?: string; + /** + * Description of the Language Operator further explaining its purpose. + */ + description?: string; + /** + * Numeric Operator version. Automatically incremented with each update on the resource, used to ensure integrity when updating the Operator. + */ + version?: number; + author?: VersionOperatorAuthor; + /** + * The natural language instructions used by the operator to analyze the conversation. Within the prompt, users can reference parameters using the `{{parameters.[param_name]}}` syntax. Parameter values are provided to the Operator by the Intelligence Configuration Rule at runtime. **Note**: Prompts will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their prompts omitted from the API. + */ + prompt?: string; + outputFormat?: OperatorOutputFormat; + /** + * Required for `JSON` output only. this will be set to a JSON Schema object describing the properties & data types of the response. Please see https://platform.openai.com/docs/guides/structured-outputs#supported-schemas Will include the following keywords: - `type` : Must be set to `object` - `properties`: An object containing the property names and their data types you would like the LLM to return Additional details on JSON output formatting: - The root level `type` of a JSON schema must be set to `object` - The following property data types are supported : `string`, `number`, `boolean`, `integer`, `object`, `array`, `anyOf` - Definitions with `$defs` / `$ref` are supported - Max 100 object properties and 10 levels of nesting are supported - Max 1000 enum values across all enum properties are supported - Notable JSON Schema keywords not supported include: - For `strings`: `minLength`, `maxLength` - For `objects`: `patternProperties`, `unevaluatedProperties`, `propertyNames`, `minProperties`, `maxProperties` - For `arrays`: `unevaluatedItems`, `contains`, `minContains`, `maxContains`, `uniqueItems` - Structured Operator Results will be returned in the same order as the ordering of keys in the schema - In the event an Operator execution request is refused for safety reasons the Operator Result API response will include a new field called `refusal` to indicate that the LLM refused to fulfill the request - Twilio will automatically set `additionalProperties` to false and specify all provided fields as required (constraints of Structured Outputs). You don\'t need to pass these fields as part of your JSON schema. Twilio will automatically overwrite any user-provided values for these fields. + */ + outputSchema?: Record; + /** + * An array of example input/output pairs used to illustrate the intended behavior of the Language Operator. These examples help guide the model\'s understanding of expected input–output relationships and improve consistency during evaluation and testing. **Note**: Training examples will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their training examples omitted from the API. + */ + trainingExamples?: Array; + context?: OperatorContext; + /** + * Defines the schema of the parameters that are provided when running the operator, including required and optional values that determine the operator\'s behavior. The values of the parameters themselves are passed in by the attached Intelligence Configuration. + */ + parameters?: { [key: string]: OperatorParameter; }; + status?: OperatorVersionStatus; + /** + * Timestamp of when this version was created. + */ + dateCreated?: Date; + /** + * Timestamp of when this version was deprecated. Present when status is `DEPRECATED` or `RETIRED`. + */ + dateDeprecated?: Date; + /** + * Scheduled retirement date for this version. Present when status is `DEPRECATED`. + */ + retirementDate?: Date; + /** + * Timestamp of when this version was retired. Present when status is `RETIRED`. + */ + dateRetired?: Date; + + private get _proxy(): VersionContext { + this._context = this._context || new VersionContextImpl(this._version, this._solution.id, this._solution.versionParam); + return this._context; + } + + /** + * Fetch a VersionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VersionInstance + */ + fetch(callback?: (error: Error | null, item?: VersionInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a VersionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VersionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + displayName: this.displayName, + description: this.description, + version: this.version, + author: this.author, + prompt: this.prompt, + outputFormat: this.outputFormat, + outputSchema: this.outputSchema, + trainingExamples: this.trainingExamples, + context: this.context, + parameters: this.parameters, + status: this.status, + dateCreated: this.dateCreated, + dateDeprecated: this.dateDeprecated, + retirementDate: this.retirementDate, + dateRetired: this.dateRetired, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface VersionSolution { + id: string; +} + +export interface VersionListInstance { + _version: V3; + _solution: VersionSolution; + _uri: string; + + (versionParam: number, ): VersionContext; + get(versionParam: number, ): VersionContext; + + + + + + /** + * Streams VersionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VersionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: VersionInstance, done: (err?: Error) => void) => void): void; + each(params: VersionListInstanceEachOptions, callback?: (item: VersionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams VersionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VersionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: VersionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: VersionListInstanceEachOptions, callback?: (item: VersionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of VersionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: VersionPage) => any): Promise; + /** + * Retrieve a single target page of VersionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists VersionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VersionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: VersionInstance[]) => any): Promise; + list(params: VersionListInstanceOptions, callback?: (error: Error | null, items: VersionInstance[]) => any): Promise; + /** + * Lists VersionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VersionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: VersionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of VersionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VersionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: VersionPage) => any): Promise; + page(params: VersionListInstancePageOptions, callback?: (error: Error | null, items: VersionPage) => any): Promise; + /** + * Retrieve a single page of VersionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VersionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: VersionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function VersionListInstance(version: V3, id: string): VersionListInstance { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + const instance = ((versionParam, ) => instance.get(versionParam, )) as VersionListInstance; + + instance.get = function get(versionParam, ): VersionContext { + return new VersionContextImpl(version, id, versionParam); + } + + instance._version = version; + instance._solution = { id, }; + instance._uri = `/ControlPlane/Operators/${id}/Versions`; + + instance.page = function page(params?: VersionListInstancePageOptions | ((error: Error | null, items: VersionPage) => any), callback?: (error: Error | null, items: VersionPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new VersionPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: VersionPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new VersionPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: VersionListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new VersionPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new VersionPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class VersionPage extends TokenPage { +/** +* Initialize the VersionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V3, response: Response, uri: string, params: any, solution: VersionSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of VersionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: VersionResource): VersionInstance { + + return new VersionInstance( + this._version, + payload, + this._solution.id, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/V1.ts b/rest/ipMessaging/V1.ts new file mode 100644 index 000000000..f23a82d44 --- /dev/null +++ b/rest/ipMessaging/V1.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import IpMessagingBase from "../IpMessagingBase"; +import Version from "../../base/Version"; +import { CredentialListInstance } from "./v1/credential"; +import { ServiceListInstance } from "./v1/service"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of IpMessaging + * + * @param domain - The Twilio (Twilio.IpMessaging) domain + */ + constructor(domain: IpMessagingBase) { + super(domain, "v1"); + } + + /** credentials - { Twilio.IpMessaging.V1.CredentialListInstance } resource */ + protected _credentials?: CredentialListInstance; + /** services - { Twilio.IpMessaging.V1.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + + /** Getter for credentials resource */ + get credentials(): CredentialListInstance { + this._credentials = this._credentials || CredentialListInstance(this); + return this._credentials; + } + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + +} diff --git a/rest/ipMessaging/V2.ts b/rest/ipMessaging/V2.ts new file mode 100644 index 000000000..294b7a5f3 --- /dev/null +++ b/rest/ipMessaging/V2.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import IpMessagingBase from "../IpMessagingBase"; +import Version from "../../base/Version"; +import { CredentialListInstance } from "./v2/credential"; +import { ServiceListInstance } from "./v2/service"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of IpMessaging + * + * @param domain - The Twilio (Twilio.IpMessaging) domain + */ + constructor(domain: IpMessagingBase) { + super(domain, "v2"); + } + + /** credentials - { Twilio.IpMessaging.V2.CredentialListInstance } resource */ + protected _credentials?: CredentialListInstance; + /** services - { Twilio.IpMessaging.V2.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + + /** Getter for credentials resource */ + get credentials(): CredentialListInstance { + this._credentials = this._credentials || CredentialListInstance(this); + return this._credentials; + } + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + +} diff --git a/rest/ipMessaging/v1/credential.ts b/rest/ipMessaging/v1/credential.ts new file mode 100644 index 000000000..f939cf4bb --- /dev/null +++ b/rest/ipMessaging/v1/credential.ts @@ -0,0 +1,947 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export type CredentialPushService = 'gcm'|'apn'|'fcm'; + + + + +/** + * Options to pass to update a CredentialInstance + */ +export interface CredentialContextUpdateOptions { + /** */ + "friendlyName"?: string; + /** */ + "certificate"?: string; + /** */ + "privateKey"?: string; + /** */ + "sandbox"?: boolean; + /** */ + "apiKey"?: string; + /** */ + "secret"?: string; +} + +/** + * Options to pass to create a CredentialInstance + */ +export interface CredentialListInstanceCreateOptions { + /** */ + "type": CredentialPushService; + /** */ + "friendlyName"?: string; + /** */ + "certificate"?: string; + /** */ + "privateKey"?: string; + /** */ + "sandbox"?: boolean; + /** */ + "apiKey"?: string; + /** */ + "secret"?: string; +} + +/** + * Options to pass to each + */ +export interface CredentialListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CredentialInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CredentialListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CredentialListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CredentialContext { + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CredentialContextSolution { + "sid": string; +} + +export class CredentialContextImpl implements CredentialContext { + protected _solution: CredentialContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Credentials/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: CredentialInstance) => any),callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CredentialPayload extends TwilioResponsePayload { + credentials: CredentialResource[]; +} + +interface CredentialResource { + sid: string; + account_sid: string; + friendly_name: string; + type: CredentialPushService; + sandbox: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CredentialInstance { + protected _solution: CredentialContextSolution; + protected _context?: CredentialContext; + + constructor(protected _version: V1, payload: CredentialResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.sandbox = (payload.sandbox); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + sid: string; + accountSid: string; + friendlyName: string; + type: CredentialPushService; + sandbox: string; + dateCreated: Date; + dateUpdated: Date; + url: string; + + private get _proxy(): CredentialContext { + this._context = this._context || new CredentialContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + type: this.type, + sandbox: this.sandbox, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CredentialSolution { +} + +export interface CredentialListInstance { + _version: V1; + _solution: CredentialSolution; + _uri: string; + + (sid: string, ): CredentialContext; + get(sid: string, ): CredentialContext; + + + + + + + + + /** + * Create a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Create a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CredentialInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + each(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CredentialInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single target page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CredentialInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + list(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + /** + * Lists CredentialInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CredentialPage) => any): Promise; + page(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CredentialListInstance(version: V1): CredentialListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CredentialListInstance; + + instance.get = function get(sid, ): CredentialContext { + return new CredentialContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Credentials`; + + instance.create = function create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: CredentialInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CredentialListInstancePageOptions | ((error: Error | null, items: CredentialPage) => any), callback?: (error: Error | null, items: CredentialPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CredentialPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CredentialPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CredentialListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CredentialPage extends Page { +/** +* Initialize the CredentialPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: CredentialSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CredentialInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CredentialResource): CredentialInstance { + + return new CredentialInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v1/service.ts b/rest/ipMessaging/v1/service.ts new file mode 100644 index 000000000..2f3f0b84a --- /dev/null +++ b/rest/ipMessaging/v1/service.ts @@ -0,0 +1,1294 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ChannelListInstance } from "./service/channel"; +import { RoleListInstance } from "./service/role"; +import { UserListInstance } from "./service/user"; + + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** */ + "friendlyName"?: string; + /** */ + "defaultServiceRoleSid"?: string; + /** */ + "defaultChannelRoleSid"?: string; + /** */ + "defaultChannelCreatorRoleSid"?: string; + /** */ + "readStatusEnabled"?: boolean; + /** */ + "reachabilityEnabled"?: boolean; + /** */ + "typingIndicatorTimeout"?: number; + /** */ + "consumptionReportInterval"?: number; + /** */ + "notifications.newMessage.enabled"?: boolean; + /** */ + "notifications.newMessage.template"?: string; + /** */ + "notifications.addedToChannel.enabled"?: boolean; + /** */ + "notifications.addedToChannel.template"?: string; + /** */ + "notifications.removedFromChannel.enabled"?: boolean; + /** */ + "notifications.removedFromChannel.template"?: string; + /** */ + "notifications.invitedToChannel.enabled"?: boolean; + /** */ + "notifications.invitedToChannel.template"?: string; + /** */ + "preWebhookUrl"?: string; + /** */ + "postWebhookUrl"?: string; + /** */ + "webhookMethod"?: string; + /** */ + "webhookFilters"?: Array; + /** */ + "webhooks.onMessageSend.url"?: string; + /** */ + "webhooks.onMessageSend.method"?: string; + /** */ + "webhooks.onMessageUpdate.url"?: string; + /** */ + "webhooks.onMessageUpdate.method"?: string; + /** */ + "webhooks.onMessageRemove.url"?: string; + /** */ + "webhooks.onMessageRemove.method"?: string; + /** */ + "webhooks.onChannelAdd.url"?: string; + /** */ + "webhooks.onChannelAdd.method"?: string; + /** */ + "webhooks.onChannelDestroy.url"?: string; + /** */ + "webhooks.onChannelDestroy.method"?: string; + /** */ + "webhooks.onChannelUpdate.url"?: string; + /** */ + "webhooks.onChannelUpdate.method"?: string; + /** */ + "webhooks.onMemberAdd.url"?: string; + /** */ + "webhooks.onMemberAdd.method"?: string; + /** */ + "webhooks.onMemberRemove.url"?: string; + /** */ + "webhooks.onMemberRemove.method"?: string; + /** */ + "webhooks.onMessageSent.url"?: string; + /** */ + "webhooks.onMessageSent.method"?: string; + /** */ + "webhooks.onMessageUpdated.url"?: string; + /** */ + "webhooks.onMessageUpdated.method"?: string; + /** */ + "webhooks.onMessageRemoved.url"?: string; + /** */ + "webhooks.onMessageRemoved.method"?: string; + /** */ + "webhooks.onChannelAdded.url"?: string; + /** */ + "webhooks.onChannelAdded.method"?: string; + /** */ + "webhooks.onChannelDestroyed.url"?: string; + /** */ + "webhooks.onChannelDestroyed.method"?: string; + /** */ + "webhooks.onChannelUpdated.url"?: string; + /** */ + "webhooks.onChannelUpdated.method"?: string; + /** */ + "webhooks.onMemberAdded.url"?: string; + /** */ + "webhooks.onMemberAdded.method"?: string; + /** */ + "webhooks.onMemberRemoved.url"?: string; + /** */ + "webhooks.onMemberRemoved.method"?: string; + /** */ + "limits.channelMembers"?: number; + /** */ + "limits.userChannels"?: number; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** */ + "friendlyName": string; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + channels: ChannelListInstance; + roles: RoleListInstance; + users: UserListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _channels?: ChannelListInstance; + protected _roles?: RoleListInstance; + protected _users?: UserListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get channels(): ChannelListInstance { + this._channels = this._channels || ChannelListInstance(this._version, this._solution.sid); + return this._channels; + } + + get roles(): RoleListInstance { + this._roles = this._roles || RoleListInstance(this._version, this._solution.sid); + return this._roles; + } + + get users(): UserListInstance { + this._users = this._users || UserListInstance(this._version, this._solution.sid); + return this._users; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["defaultServiceRoleSid"] !== undefined) + data["DefaultServiceRoleSid"] = params["defaultServiceRoleSid"]; + if (params["defaultChannelRoleSid"] !== undefined) + data["DefaultChannelRoleSid"] = params["defaultChannelRoleSid"]; + if (params["defaultChannelCreatorRoleSid"] !== undefined) + data["DefaultChannelCreatorRoleSid"] = params["defaultChannelCreatorRoleSid"]; + if (params["readStatusEnabled"] !== undefined) + data["ReadStatusEnabled"] = serialize.bool(params["readStatusEnabled"]); + if (params["reachabilityEnabled"] !== undefined) + data["ReachabilityEnabled"] = serialize.bool(params["reachabilityEnabled"]); + if (params["typingIndicatorTimeout"] !== undefined) + data["TypingIndicatorTimeout"] = params["typingIndicatorTimeout"]; + if (params["consumptionReportInterval"] !== undefined) + data["ConsumptionReportInterval"] = params["consumptionReportInterval"]; + if (params["notifications.newMessage.enabled"] !== undefined) + data["Notifications.NewMessage.Enabled"] = serialize.bool(params["notifications.newMessage.enabled"]); + if (params["notifications.newMessage.template"] !== undefined) + data["Notifications.NewMessage.Template"] = params["notifications.newMessage.template"]; + if (params["notifications.addedToChannel.enabled"] !== undefined) + data["Notifications.AddedToChannel.Enabled"] = serialize.bool(params["notifications.addedToChannel.enabled"]); + if (params["notifications.addedToChannel.template"] !== undefined) + data["Notifications.AddedToChannel.Template"] = params["notifications.addedToChannel.template"]; + if (params["notifications.removedFromChannel.enabled"] !== undefined) + data["Notifications.RemovedFromChannel.Enabled"] = serialize.bool(params["notifications.removedFromChannel.enabled"]); + if (params["notifications.removedFromChannel.template"] !== undefined) + data["Notifications.RemovedFromChannel.Template"] = params["notifications.removedFromChannel.template"]; + if (params["notifications.invitedToChannel.enabled"] !== undefined) + data["Notifications.InvitedToChannel.Enabled"] = serialize.bool(params["notifications.invitedToChannel.enabled"]); + if (params["notifications.invitedToChannel.template"] !== undefined) + data["Notifications.InvitedToChannel.Template"] = params["notifications.invitedToChannel.template"]; + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + if (params["webhookFilters"] !== undefined) + data["WebhookFilters"] = serialize.map(params["webhookFilters"], (e: string) => (e)); + if (params["webhooks.onMessageSend.url"] !== undefined) + data["Webhooks.OnMessageSend.Url"] = params["webhooks.onMessageSend.url"]; + if (params["webhooks.onMessageSend.method"] !== undefined) + data["Webhooks.OnMessageSend.Method"] = params["webhooks.onMessageSend.method"]; + if (params["webhooks.onMessageUpdate.url"] !== undefined) + data["Webhooks.OnMessageUpdate.Url"] = params["webhooks.onMessageUpdate.url"]; + if (params["webhooks.onMessageUpdate.method"] !== undefined) + data["Webhooks.OnMessageUpdate.Method"] = params["webhooks.onMessageUpdate.method"]; + if (params["webhooks.onMessageRemove.url"] !== undefined) + data["Webhooks.OnMessageRemove.Url"] = params["webhooks.onMessageRemove.url"]; + if (params["webhooks.onMessageRemove.method"] !== undefined) + data["Webhooks.OnMessageRemove.Method"] = params["webhooks.onMessageRemove.method"]; + if (params["webhooks.onChannelAdd.url"] !== undefined) + data["Webhooks.OnChannelAdd.Url"] = params["webhooks.onChannelAdd.url"]; + if (params["webhooks.onChannelAdd.method"] !== undefined) + data["Webhooks.OnChannelAdd.Method"] = params["webhooks.onChannelAdd.method"]; + if (params["webhooks.onChannelDestroy.url"] !== undefined) + data["Webhooks.OnChannelDestroy.Url"] = params["webhooks.onChannelDestroy.url"]; + if (params["webhooks.onChannelDestroy.method"] !== undefined) + data["Webhooks.OnChannelDestroy.Method"] = params["webhooks.onChannelDestroy.method"]; + if (params["webhooks.onChannelUpdate.url"] !== undefined) + data["Webhooks.OnChannelUpdate.Url"] = params["webhooks.onChannelUpdate.url"]; + if (params["webhooks.onChannelUpdate.method"] !== undefined) + data["Webhooks.OnChannelUpdate.Method"] = params["webhooks.onChannelUpdate.method"]; + if (params["webhooks.onMemberAdd.url"] !== undefined) + data["Webhooks.OnMemberAdd.Url"] = params["webhooks.onMemberAdd.url"]; + if (params["webhooks.onMemberAdd.method"] !== undefined) + data["Webhooks.OnMemberAdd.Method"] = params["webhooks.onMemberAdd.method"]; + if (params["webhooks.onMemberRemove.url"] !== undefined) + data["Webhooks.OnMemberRemove.Url"] = params["webhooks.onMemberRemove.url"]; + if (params["webhooks.onMemberRemove.method"] !== undefined) + data["Webhooks.OnMemberRemove.Method"] = params["webhooks.onMemberRemove.method"]; + if (params["webhooks.onMessageSent.url"] !== undefined) + data["Webhooks.OnMessageSent.Url"] = params["webhooks.onMessageSent.url"]; + if (params["webhooks.onMessageSent.method"] !== undefined) + data["Webhooks.OnMessageSent.Method"] = params["webhooks.onMessageSent.method"]; + if (params["webhooks.onMessageUpdated.url"] !== undefined) + data["Webhooks.OnMessageUpdated.Url"] = params["webhooks.onMessageUpdated.url"]; + if (params["webhooks.onMessageUpdated.method"] !== undefined) + data["Webhooks.OnMessageUpdated.Method"] = params["webhooks.onMessageUpdated.method"]; + if (params["webhooks.onMessageRemoved.url"] !== undefined) + data["Webhooks.OnMessageRemoved.Url"] = params["webhooks.onMessageRemoved.url"]; + if (params["webhooks.onMessageRemoved.method"] !== undefined) + data["Webhooks.OnMessageRemoved.Method"] = params["webhooks.onMessageRemoved.method"]; + if (params["webhooks.onChannelAdded.url"] !== undefined) + data["Webhooks.OnChannelAdded.Url"] = params["webhooks.onChannelAdded.url"]; + if (params["webhooks.onChannelAdded.method"] !== undefined) + data["Webhooks.OnChannelAdded.Method"] = params["webhooks.onChannelAdded.method"]; + if (params["webhooks.onChannelDestroyed.url"] !== undefined) + data["Webhooks.OnChannelDestroyed.Url"] = params["webhooks.onChannelDestroyed.url"]; + if (params["webhooks.onChannelDestroyed.method"] !== undefined) + data["Webhooks.OnChannelDestroyed.Method"] = params["webhooks.onChannelDestroyed.method"]; + if (params["webhooks.onChannelUpdated.url"] !== undefined) + data["Webhooks.OnChannelUpdated.Url"] = params["webhooks.onChannelUpdated.url"]; + if (params["webhooks.onChannelUpdated.method"] !== undefined) + data["Webhooks.OnChannelUpdated.Method"] = params["webhooks.onChannelUpdated.method"]; + if (params["webhooks.onMemberAdded.url"] !== undefined) + data["Webhooks.OnMemberAdded.Url"] = params["webhooks.onMemberAdded.url"]; + if (params["webhooks.onMemberAdded.method"] !== undefined) + data["Webhooks.OnMemberAdded.Method"] = params["webhooks.onMemberAdded.method"]; + if (params["webhooks.onMemberRemoved.url"] !== undefined) + data["Webhooks.OnMemberRemoved.Url"] = params["webhooks.onMemberRemoved.url"]; + if (params["webhooks.onMemberRemoved.method"] !== undefined) + data["Webhooks.OnMemberRemoved.Method"] = params["webhooks.onMemberRemoved.method"]; + if (params["limits.channelMembers"] !== undefined) + data["Limits.ChannelMembers"] = params["limits.channelMembers"]; + if (params["limits.userChannels"] !== undefined) + data["Limits.UserChannels"] = params["limits.userChannels"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["defaultServiceRoleSid"] !== undefined) + data["DefaultServiceRoleSid"] = params["defaultServiceRoleSid"]; + if (params["defaultChannelRoleSid"] !== undefined) + data["DefaultChannelRoleSid"] = params["defaultChannelRoleSid"]; + if (params["defaultChannelCreatorRoleSid"] !== undefined) + data["DefaultChannelCreatorRoleSid"] = params["defaultChannelCreatorRoleSid"]; + if (params["readStatusEnabled"] !== undefined) + data["ReadStatusEnabled"] = serialize.bool(params["readStatusEnabled"]); + if (params["reachabilityEnabled"] !== undefined) + data["ReachabilityEnabled"] = serialize.bool(params["reachabilityEnabled"]); + if (params["typingIndicatorTimeout"] !== undefined) + data["TypingIndicatorTimeout"] = params["typingIndicatorTimeout"]; + if (params["consumptionReportInterval"] !== undefined) + data["ConsumptionReportInterval"] = params["consumptionReportInterval"]; + if (params["notifications.newMessage.enabled"] !== undefined) + data["Notifications.NewMessage.Enabled"] = serialize.bool(params["notifications.newMessage.enabled"]); + if (params["notifications.newMessage.template"] !== undefined) + data["Notifications.NewMessage.Template"] = params["notifications.newMessage.template"]; + if (params["notifications.addedToChannel.enabled"] !== undefined) + data["Notifications.AddedToChannel.Enabled"] = serialize.bool(params["notifications.addedToChannel.enabled"]); + if (params["notifications.addedToChannel.template"] !== undefined) + data["Notifications.AddedToChannel.Template"] = params["notifications.addedToChannel.template"]; + if (params["notifications.removedFromChannel.enabled"] !== undefined) + data["Notifications.RemovedFromChannel.Enabled"] = serialize.bool(params["notifications.removedFromChannel.enabled"]); + if (params["notifications.removedFromChannel.template"] !== undefined) + data["Notifications.RemovedFromChannel.Template"] = params["notifications.removedFromChannel.template"]; + if (params["notifications.invitedToChannel.enabled"] !== undefined) + data["Notifications.InvitedToChannel.Enabled"] = serialize.bool(params["notifications.invitedToChannel.enabled"]); + if (params["notifications.invitedToChannel.template"] !== undefined) + data["Notifications.InvitedToChannel.Template"] = params["notifications.invitedToChannel.template"]; + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + if (params["webhookFilters"] !== undefined) + data["WebhookFilters"] = serialize.map(params["webhookFilters"], (e: string) => (e)); + if (params["webhooks.onMessageSend.url"] !== undefined) + data["Webhooks.OnMessageSend.Url"] = params["webhooks.onMessageSend.url"]; + if (params["webhooks.onMessageSend.method"] !== undefined) + data["Webhooks.OnMessageSend.Method"] = params["webhooks.onMessageSend.method"]; + if (params["webhooks.onMessageUpdate.url"] !== undefined) + data["Webhooks.OnMessageUpdate.Url"] = params["webhooks.onMessageUpdate.url"]; + if (params["webhooks.onMessageUpdate.method"] !== undefined) + data["Webhooks.OnMessageUpdate.Method"] = params["webhooks.onMessageUpdate.method"]; + if (params["webhooks.onMessageRemove.url"] !== undefined) + data["Webhooks.OnMessageRemove.Url"] = params["webhooks.onMessageRemove.url"]; + if (params["webhooks.onMessageRemove.method"] !== undefined) + data["Webhooks.OnMessageRemove.Method"] = params["webhooks.onMessageRemove.method"]; + if (params["webhooks.onChannelAdd.url"] !== undefined) + data["Webhooks.OnChannelAdd.Url"] = params["webhooks.onChannelAdd.url"]; + if (params["webhooks.onChannelAdd.method"] !== undefined) + data["Webhooks.OnChannelAdd.Method"] = params["webhooks.onChannelAdd.method"]; + if (params["webhooks.onChannelDestroy.url"] !== undefined) + data["Webhooks.OnChannelDestroy.Url"] = params["webhooks.onChannelDestroy.url"]; + if (params["webhooks.onChannelDestroy.method"] !== undefined) + data["Webhooks.OnChannelDestroy.Method"] = params["webhooks.onChannelDestroy.method"]; + if (params["webhooks.onChannelUpdate.url"] !== undefined) + data["Webhooks.OnChannelUpdate.Url"] = params["webhooks.onChannelUpdate.url"]; + if (params["webhooks.onChannelUpdate.method"] !== undefined) + data["Webhooks.OnChannelUpdate.Method"] = params["webhooks.onChannelUpdate.method"]; + if (params["webhooks.onMemberAdd.url"] !== undefined) + data["Webhooks.OnMemberAdd.Url"] = params["webhooks.onMemberAdd.url"]; + if (params["webhooks.onMemberAdd.method"] !== undefined) + data["Webhooks.OnMemberAdd.Method"] = params["webhooks.onMemberAdd.method"]; + if (params["webhooks.onMemberRemove.url"] !== undefined) + data["Webhooks.OnMemberRemove.Url"] = params["webhooks.onMemberRemove.url"]; + if (params["webhooks.onMemberRemove.method"] !== undefined) + data["Webhooks.OnMemberRemove.Method"] = params["webhooks.onMemberRemove.method"]; + if (params["webhooks.onMessageSent.url"] !== undefined) + data["Webhooks.OnMessageSent.Url"] = params["webhooks.onMessageSent.url"]; + if (params["webhooks.onMessageSent.method"] !== undefined) + data["Webhooks.OnMessageSent.Method"] = params["webhooks.onMessageSent.method"]; + if (params["webhooks.onMessageUpdated.url"] !== undefined) + data["Webhooks.OnMessageUpdated.Url"] = params["webhooks.onMessageUpdated.url"]; + if (params["webhooks.onMessageUpdated.method"] !== undefined) + data["Webhooks.OnMessageUpdated.Method"] = params["webhooks.onMessageUpdated.method"]; + if (params["webhooks.onMessageRemoved.url"] !== undefined) + data["Webhooks.OnMessageRemoved.Url"] = params["webhooks.onMessageRemoved.url"]; + if (params["webhooks.onMessageRemoved.method"] !== undefined) + data["Webhooks.OnMessageRemoved.Method"] = params["webhooks.onMessageRemoved.method"]; + if (params["webhooks.onChannelAdded.url"] !== undefined) + data["Webhooks.OnChannelAdded.Url"] = params["webhooks.onChannelAdded.url"]; + if (params["webhooks.onChannelAdded.method"] !== undefined) + data["Webhooks.OnChannelAdded.Method"] = params["webhooks.onChannelAdded.method"]; + if (params["webhooks.onChannelDestroyed.url"] !== undefined) + data["Webhooks.OnChannelDestroyed.Url"] = params["webhooks.onChannelDestroyed.url"]; + if (params["webhooks.onChannelDestroyed.method"] !== undefined) + data["Webhooks.OnChannelDestroyed.Method"] = params["webhooks.onChannelDestroyed.method"]; + if (params["webhooks.onChannelUpdated.url"] !== undefined) + data["Webhooks.OnChannelUpdated.Url"] = params["webhooks.onChannelUpdated.url"]; + if (params["webhooks.onChannelUpdated.method"] !== undefined) + data["Webhooks.OnChannelUpdated.Method"] = params["webhooks.onChannelUpdated.method"]; + if (params["webhooks.onMemberAdded.url"] !== undefined) + data["Webhooks.OnMemberAdded.Url"] = params["webhooks.onMemberAdded.url"]; + if (params["webhooks.onMemberAdded.method"] !== undefined) + data["Webhooks.OnMemberAdded.Method"] = params["webhooks.onMemberAdded.method"]; + if (params["webhooks.onMemberRemoved.url"] !== undefined) + data["Webhooks.OnMemberRemoved.Url"] = params["webhooks.onMemberRemoved.url"]; + if (params["webhooks.onMemberRemoved.method"] !== undefined) + data["Webhooks.OnMemberRemoved.Method"] = params["webhooks.onMemberRemoved.method"]; + if (params["limits.channelMembers"] !== undefined) + data["Limits.ChannelMembers"] = params["limits.channelMembers"]; + if (params["limits.userChannels"] !== undefined) + data["Limits.UserChannels"] = params["limits.userChannels"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + sid: string; + account_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + default_service_role_sid: string; + default_channel_role_sid: string; + default_channel_creator_role_sid: string; + read_status_enabled: boolean; + reachability_enabled: boolean; + typing_indicator_timeout: number; + consumption_report_interval: number; + limits: any; + webhooks: any; + pre_webhook_url: string; + post_webhook_url: string; + webhook_method: string; + webhook_filters: Array; + notifications: any; + url: string; + links: Record; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V1, payload: ServiceResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.defaultServiceRoleSid = (payload.default_service_role_sid); + this.defaultChannelRoleSid = (payload.default_channel_role_sid); + this.defaultChannelCreatorRoleSid = (payload.default_channel_creator_role_sid); + this.readStatusEnabled = (payload.read_status_enabled); + this.reachabilityEnabled = (payload.reachability_enabled); + this.typingIndicatorTimeout = deserialize.integer(payload.typing_indicator_timeout); + this.consumptionReportInterval = deserialize.integer(payload.consumption_report_interval); + this.limits = (payload.limits); + this.webhooks = (payload.webhooks); + this.preWebhookUrl = (payload.pre_webhook_url); + this.postWebhookUrl = (payload.post_webhook_url); + this.webhookMethod = (payload.webhook_method); + this.webhookFilters = (payload.webhook_filters); + this.notifications = (payload.notifications); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + sid: string; + accountSid: string; + friendlyName: string; + dateCreated: Date; + dateUpdated: Date; + defaultServiceRoleSid: string; + defaultChannelRoleSid: string; + defaultChannelCreatorRoleSid: string; + readStatusEnabled: boolean; + reachabilityEnabled: boolean; + typingIndicatorTimeout: number; + consumptionReportInterval: number; + limits: any; + webhooks: any; + preWebhookUrl: string; + postWebhookUrl: string; + webhookMethod: string; + webhookFilters: Array; + notifications: any; + url: string; + links: Record; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the channels. + */ + channels(): ChannelListInstance { + return this._proxy.channels; + } + + /** + * Access the roles. + */ + roles(): RoleListInstance { + return this._proxy.roles; + } + + /** + * Access the users. + */ + users(): UserListInstance { + return this._proxy.users; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + defaultServiceRoleSid: this.defaultServiceRoleSid, + defaultChannelRoleSid: this.defaultChannelRoleSid, + defaultChannelCreatorRoleSid: this.defaultChannelCreatorRoleSid, + readStatusEnabled: this.readStatusEnabled, + reachabilityEnabled: this.reachabilityEnabled, + typingIndicatorTimeout: this.typingIndicatorTimeout, + consumptionReportInterval: this.consumptionReportInterval, + limits: this.limits, + webhooks: this.webhooks, + preWebhookUrl: this.preWebhookUrl, + postWebhookUrl: this.postWebhookUrl, + webhookMethod: this.webhookMethod, + webhookFilters: this.webhookFilters, + notifications: this.notifications, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V1; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V1): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ServiceInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v1/service/channel.ts b/rest/ipMessaging/v1/service/channel.ts new file mode 100644 index 000000000..b8e8a7df2 --- /dev/null +++ b/rest/ipMessaging/v1/service/channel.ts @@ -0,0 +1,1015 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { InviteListInstance } from "./channel/invite"; +import { MemberListInstance } from "./channel/member"; +import { MessageListInstance } from "./channel/message"; + + +export type ChannelChannelType = 'public'|'private'; + + + + +/** + * Options to pass to update a ChannelInstance + */ +export interface ChannelContextUpdateOptions { + /** */ + "friendlyName"?: string; + /** */ + "uniqueName"?: string; + /** */ + "attributes"?: string; +} + +/** + * Options to pass to create a ChannelInstance + */ +export interface ChannelListInstanceCreateOptions { + /** */ + "friendlyName"?: string; + /** */ + "uniqueName"?: string; + /** */ + "attributes"?: string; + /** */ + "type"?: ChannelChannelType; +} + +/** + * Options to pass to each + */ +export interface ChannelListInstanceEachOptions { + /** */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChannelListInstanceOptions { + /** */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChannelListInstancePageOptions { + /** */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ChannelContext { + invites: InviteListInstance; + members: MemberListInstance; + messages: MessageListInstance; + + /** + * Remove a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + + /** + * Fetch a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Update a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + /** + * Update a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ChannelContextSolution { + "serviceSid": string; + "sid": string; +} + +export class ChannelContextImpl implements ChannelContext { + protected _solution: ChannelContextSolution; + protected _uri: string; + + protected _invites?: InviteListInstance; + protected _members?: MemberListInstance; + protected _messages?: MessageListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${sid}`; + } + + get invites(): InviteListInstance { + this._invites = this._invites || InviteListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._invites; + } + + get members(): MemberListInstance { + this._members = this._members || MemberListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._members; + } + + get messages(): MessageListInstance { + this._messages = this._messages || MessageListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._messages; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ChannelContextUpdateOptions | ((error: Error | null, item?: ChannelInstance) => any),callback?: (error: Error | null, item?: ChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ChannelContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ChannelPayload extends TwilioResponsePayload { + channels: ChannelResource[]; +} + +interface ChannelResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + unique_name: string; + attributes: string; + type: ChannelChannelType; + date_created: Date; + date_updated: Date; + created_by: string; + members_count: number; + messages_count: number; + url: string; + links: Record; +} + +export class ChannelInstance { + protected _solution: ChannelContextSolution; + protected _context?: ChannelContext; + + constructor(protected _version: V1, payload: ChannelResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.attributes = (payload.attributes); + this.type = payload.type; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + this.membersCount = deserialize.integer(payload.members_count); + this.messagesCount = deserialize.integer(payload.messages_count); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + sid: string; + accountSid: string; + serviceSid: string; + friendlyName: string; + uniqueName: string; + attributes: string; + type: ChannelChannelType; + dateCreated: Date; + dateUpdated: Date; + createdBy: string; + membersCount: number; + messagesCount: number; + url: string; + links: Record; + + private get _proxy(): ChannelContext { + this._context = this._context || new ChannelContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Update a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the invites. + */ + invites(): InviteListInstance { + return this._proxy.invites; + } + + /** + * Access the members. + */ + members(): MemberListInstance { + return this._proxy.members; + } + + /** + * Access the messages. + */ + messages(): MessageListInstance { + return this._proxy.messages; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + attributes: this.attributes, + type: this.type, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + membersCount: this.membersCount, + messagesCount: this.messagesCount, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ChannelSolution { + serviceSid: string; +} + +export interface ChannelListInstance { + _version: V1; + _solution: ChannelSolution; + _uri: string; + + (sid: string, ): ChannelContext; + get(sid: string, ): ChannelContext; + + + + + + + + + /** + * Create a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + create(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Create a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + create(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + /** + * Create a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + createWithHttpInfo(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + each(params: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise; + /** + * Retrieve a single target page of ChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise; + list(params: ChannelListInstanceOptions, callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise; + /** + * Lists ChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ChannelPage) => any): Promise; + page(params: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ChannelPage) => any): Promise; + /** + * Retrieve a single page of ChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChannelListInstance(version: V1, serviceSid: string): ChannelListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ChannelListInstance; + + instance.get = function get(sid, ): ChannelContext { + return new ChannelContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Channels`; + + instance.create = function create(params?: ChannelListInstanceCreateOptions | ((error: Error | null, items: ChannelInstance) => any), callback?: (error: Error | null, items: ChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["type"] !== undefined) + data["Type"] = params["type"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ChannelListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["type"] !== undefined) + data["Type"] = params["type"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ChannelListInstancePageOptions | ((error: Error | null, items: ChannelPage) => any), callback?: (error: Error | null, items: ChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["type"] !== undefined) + data["Type"] = serialize.map(params["type"], (e: ChannelChannelType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["type"] !== undefined) + data["Type"] = serialize.map(params["type"], (e: ChannelChannelType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ChannelPage extends Page { +/** +* Initialize the ChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChannelResource): ChannelInstance { + + return new ChannelInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v1/service/channel/invite.ts b/rest/ipMessaging/v1/service/channel/invite.ts new file mode 100644 index 000000000..c1426dc6b --- /dev/null +++ b/rest/ipMessaging/v1/service/channel/invite.ts @@ -0,0 +1,764 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a InviteInstance + */ +export interface InviteListInstanceCreateOptions { + /** */ + "identity": string; + /** */ + "roleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface InviteListInstanceEachOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InviteInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InviteListInstanceOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InviteListInstancePageOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InviteContext { + + /** + * Remove a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise + + /** + * Fetch a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InviteContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class InviteContextImpl implements InviteContext { + protected _solution: InviteContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Invites/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InviteInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new InviteInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InvitePayload extends TwilioResponsePayload { + invites: InviteResource[]; +} + +interface InviteResource { + sid: string; + account_sid: string; + channel_sid: string; + service_sid: string; + identity: string; + date_created: Date; + date_updated: Date; + role_sid: string; + created_by: string; + url: string; +} + +export class InviteInstance { + protected _solution: InviteContextSolution; + protected _context?: InviteContext; + + constructor(protected _version: V1, payload: InviteResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.channelSid = (payload.channel_sid); + this.serviceSid = (payload.service_sid); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.roleSid = (payload.role_sid); + this.createdBy = (payload.created_by); + this.url = (payload.url); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + sid: string; + accountSid: string; + channelSid: string; + serviceSid: string; + identity: string; + dateCreated: Date; + dateUpdated: Date; + roleSid: string; + createdBy: string; + url: string; + + private get _proxy(): InviteContext { + this._context = this._context || new InviteContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + channelSid: this.channelSid, + serviceSid: this.serviceSid, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + roleSid: this.roleSid, + createdBy: this.createdBy, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InviteSolution { + serviceSid: string; + channelSid: string; +} + +export interface InviteListInstance { + _version: V1; + _solution: InviteSolution; + _uri: string; + + (sid: string, ): InviteContext; + get(sid: string, ): InviteContext; + + + + + + + /** + * Create a InviteInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + create(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, item?: InviteInstance) => any): Promise; + + /** + * Create a InviteInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + createWithHttpInfo(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams InviteInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + each(params: InviteListInstanceEachOptions, callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InviteInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InviteListInstanceEachOptions, callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InviteInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InvitePage) => any): Promise; + /** + * Retrieve a single target page of InviteInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InviteInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InviteInstance[]) => any): Promise; + list(params: InviteListInstanceOptions, callback?: (error: Error | null, items: InviteInstance[]) => any): Promise; + /** + * Lists InviteInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InviteListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InviteInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InvitePage) => any): Promise; + page(params: InviteListInstancePageOptions, callback?: (error: Error | null, items: InvitePage) => any): Promise; + /** + * Retrieve a single page of InviteInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InviteListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InviteListInstance(version: V1, serviceSid: string, channelSid: string): InviteListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as InviteListInstance; + + instance.get = function get(sid, ): InviteContext { + return new InviteContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Invites`; + + instance.create = function create(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, items: InviteInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InviteInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InviteInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InviteListInstancePageOptions | ((error: Error | null, items: InvitePage) => any), callback?: (error: Error | null, items: InvitePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InvitePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InvitePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InvitePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InviteListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InvitePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InvitePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InvitePage extends Page { +/** +* Initialize the InvitePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: InviteSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InviteInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InviteResource): InviteInstance { + + return new InviteInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v1/service/channel/member.ts b/rest/ipMessaging/v1/service/channel/member.ts new file mode 100644 index 000000000..049261450 --- /dev/null +++ b/rest/ipMessaging/v1/service/channel/member.ts @@ -0,0 +1,935 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a MemberInstance + */ +export interface MemberContextUpdateOptions { + /** */ + "roleSid"?: string; + /** */ + "lastConsumedMessageIndex"?: number; +} + +/** + * Options to pass to create a MemberInstance + */ +export interface MemberListInstanceCreateOptions { + /** */ + "identity": string; + /** */ + "roleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface MemberListInstanceEachOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MemberInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MemberListInstanceOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MemberListInstancePageOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MemberContext { + + /** + * Remove a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise + + /** + * Fetch a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + /** + * Update a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + /** + * Update a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MemberContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class MemberContextImpl implements MemberContext { + protected _solution: MemberContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Members/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MemberContextUpdateOptions | ((error: Error | null, item?: MemberInstance) => any),callback?: (error: Error | null, item?: MemberInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MemberContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MemberPayload extends TwilioResponsePayload { + members: MemberResource[]; +} + +interface MemberResource { + sid: string; + account_sid: string; + channel_sid: string; + service_sid: string; + identity: string; + date_created: Date; + date_updated: Date; + role_sid: string; + last_consumed_message_index: number; + last_consumption_timestamp: Date; + url: string; +} + +export class MemberInstance { + protected _solution: MemberContextSolution; + protected _context?: MemberContext; + + constructor(protected _version: V1, payload: MemberResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.channelSid = (payload.channel_sid); + this.serviceSid = (payload.service_sid); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.roleSid = (payload.role_sid); + this.lastConsumedMessageIndex = deserialize.integer(payload.last_consumed_message_index); + this.lastConsumptionTimestamp = deserialize.iso8601DateTime(payload.last_consumption_timestamp); + this.url = (payload.url); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + sid: string; + accountSid: string; + channelSid: string; + serviceSid: string; + identity: string; + dateCreated: Date; + dateUpdated: Date; + roleSid: string; + lastConsumedMessageIndex: number; + lastConsumptionTimestamp: Date; + url: string; + + private get _proxy(): MemberContext { + this._context = this._context || new MemberContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + /** + * Update a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MemberInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + channelSid: this.channelSid, + serviceSid: this.serviceSid, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + roleSid: this.roleSid, + lastConsumedMessageIndex: this.lastConsumedMessageIndex, + lastConsumptionTimestamp: this.lastConsumptionTimestamp, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MemberSolution { + serviceSid: string; + channelSid: string; +} + +export interface MemberListInstance { + _version: V1; + _solution: MemberSolution; + _uri: string; + + (sid: string, ): MemberContext; + get(sid: string, ): MemberContext; + + + + + + + + + /** + * Create a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + create(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + /** + * Create a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + createWithHttpInfo(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MemberInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + each(params: MemberListInstanceEachOptions, callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MemberInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MemberListInstanceEachOptions, callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MemberInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MemberPage) => any): Promise; + /** + * Retrieve a single target page of MemberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MemberInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MemberInstance[]) => any): Promise; + list(params: MemberListInstanceOptions, callback?: (error: Error | null, items: MemberInstance[]) => any): Promise; + /** + * Lists MemberInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MemberListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MemberInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MemberPage) => any): Promise; + page(params: MemberListInstancePageOptions, callback?: (error: Error | null, items: MemberPage) => any): Promise; + /** + * Retrieve a single page of MemberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MemberListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MemberListInstance(version: V1, serviceSid: string, channelSid: string): MemberListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MemberListInstance; + + instance.get = function get(sid, ): MemberContext { + return new MemberContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Members`; + + instance.create = function create(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, items: MemberInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MemberListInstancePageOptions | ((error: Error | null, items: MemberPage) => any), callback?: (error: Error | null, items: MemberPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MemberPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MemberPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MemberPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MemberListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MemberPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MemberPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MemberPage extends Page { +/** +* Initialize the MemberPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: MemberSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MemberInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MemberResource): MemberInstance { + + return new MemberInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v1/service/channel/message.ts b/rest/ipMessaging/v1/service/channel/message.ts new file mode 100644 index 000000000..c108e6560 --- /dev/null +++ b/rest/ipMessaging/v1/service/channel/message.ts @@ -0,0 +1,951 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type MessageOrderType = 'asc'|'desc'; + + + + +/** + * Options to pass to update a MessageInstance + */ +export interface MessageContextUpdateOptions { + /** */ + "body"?: string; + /** */ + "attributes"?: string; +} + +/** + * Options to pass to create a MessageInstance + */ +export interface MessageListInstanceCreateOptions { + /** */ + "body": string; + /** */ + "from"?: string; + /** */ + "attributes"?: string; +} + +/** + * Options to pass to each + */ +export interface MessageListInstanceEachOptions { + /** */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MessageInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MessageListInstanceOptions { + /** */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MessageListInstancePageOptions { + /** */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MessageContext { + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MessageContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class MessageContextImpl implements MessageContext { + protected _solution: MessageContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Messages/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MessageContextUpdateOptions | ((error: Error | null, item?: MessageInstance) => any),callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MessageContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MessagePayload extends TwilioResponsePayload { + messages: MessageResource[]; +} + +interface MessageResource { + sid: string; + account_sid: string; + attributes: string; + service_sid: string; + to: string; + channel_sid: string; + date_created: Date; + date_updated: Date; + was_edited: boolean; + from: string; + body: string; + index: number; + url: string; +} + +export class MessageInstance { + protected _solution: MessageContextSolution; + protected _context?: MessageContext; + + constructor(protected _version: V1, payload: MessageResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.attributes = (payload.attributes); + this.serviceSid = (payload.service_sid); + this.to = (payload.to); + this.channelSid = (payload.channel_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.wasEdited = (payload.was_edited); + this.from = (payload.from); + this.body = (payload.body); + this.index = deserialize.integer(payload.index); + this.url = (payload.url); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + sid: string; + accountSid: string; + attributes: string; + serviceSid: string; + to: string; + channelSid: string; + dateCreated: Date; + dateUpdated: Date; + wasEdited: boolean; + from: string; + body: string; + index: number; + url: string; + + private get _proxy(): MessageContext { + this._context = this._context || new MessageContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MessageInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + attributes: this.attributes, + serviceSid: this.serviceSid, + to: this.to, + channelSid: this.channelSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + wasEdited: this.wasEdited, + from: this.from, + body: this.body, + index: this.index, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MessageSolution { + serviceSid: string; + channelSid: string; +} + +export interface MessageListInstance { + _version: V1; + _solution: MessageSolution; + _uri: string; + + (sid: string, ): MessageContext; + get(sid: string, ): MessageContext; + + + + + + + + + /** + * Create a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Create a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MessageInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + each(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MessageInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single target page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MessageInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + list(params: MessageListInstanceOptions, callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + /** + * Lists MessageInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MessageListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MessagePage) => any): Promise; + page(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessageListInstance(version: V1, serviceSid: string, channelSid: string): MessageListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MessageListInstance; + + instance.get = function get(sid, ): MessageContext { + return new MessageContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Messages`; + + instance.create = function create(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, items: MessageInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["body"] === null || params["body"] === undefined) { + throw new Error('Required parameter "params[\'body\']" missing.'); + } + + let data: any = {}; + + + + data["Body"] = params["body"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["body"] === null || params["body"] === undefined) { + throw new Error('Required parameter "params[\'body\']" missing.'); + } + + let data: any = {}; + + + + data["Body"] = params["body"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MessageListInstancePageOptions | ((error: Error | null, items: MessagePage) => any), callback?: (error: Error | null, items: MessagePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MessagePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MessagePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MessageListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MessagePage extends Page { +/** +* Initialize the MessagePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: MessageSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MessageInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MessageResource): MessageInstance { + + return new MessageInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v1/service/role.ts b/rest/ipMessaging/v1/service/role.ts new file mode 100644 index 000000000..53fe979e2 --- /dev/null +++ b/rest/ipMessaging/v1/service/role.ts @@ -0,0 +1,894 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export type RoleRoleType = 'channel'|'deployment'; + + + + +/** + * Options to pass to update a RoleInstance + */ +export interface RoleContextUpdateOptions { + /** */ + "permission": Array; +} + +/** + * Options to pass to create a RoleInstance + */ +export interface RoleListInstanceCreateOptions { + /** */ + "friendlyName": string; + /** */ + "type": RoleRoleType; + /** */ + "permission": Array; +} + +/** + * Options to pass to each + */ +export interface RoleListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoleInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoleListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoleListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoleContext { + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoleContextSolution { + "serviceSid": string; + "sid": string; +} + +export class RoleContextImpl implements RoleContext { + protected _solution: RoleContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Roles/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RolePayload extends TwilioResponsePayload { + roles: RoleResource[]; +} + +interface RoleResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + type: RoleRoleType; + permissions: Array; + date_created: Date; + date_updated: Date; + url: string; +} + +export class RoleInstance { + protected _solution: RoleContextSolution; + protected _context?: RoleContext; + + constructor(protected _version: V1, payload: RoleResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.permissions = (payload.permissions); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + sid: string; + accountSid: string; + serviceSid: string; + friendlyName: string; + type: RoleRoleType; + permissions: Array; + dateCreated: Date; + dateUpdated: Date; + url: string; + + private get _proxy(): RoleContext { + this._context = this._context || new RoleContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: RoleInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + type: this.type, + permissions: this.permissions, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoleSolution { + serviceSid: string; +} + +export interface RoleListInstance { + _version: V1; + _solution: RoleSolution; + _uri: string; + + (sid: string, ): RoleContext; + get(sid: string, ): RoleContext; + + + + + + + + + /** + * Create a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Create a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams RoleInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + each(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoleInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single target page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RoleInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + list(params: RoleListInstanceOptions, callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + /** + * Lists RoleInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RoleListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RolePage) => any): Promise; + page(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoleListInstance(version: V1, serviceSid: string): RoleListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RoleListInstance; + + instance.get = function get(sid, ): RoleContext { + return new RoleContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Roles`; + + instance.create = function create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RoleListInstancePageOptions | ((error: Error | null, items: RolePage) => any), callback?: (error: Error | null, items: RolePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RolePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RolePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoleListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RolePage extends Page { +/** +* Initialize the RolePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: RoleSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoleInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoleResource): RoleInstance { + + return new RoleInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v1/service/user.ts b/rest/ipMessaging/v1/service/user.ts new file mode 100644 index 000000000..df3e1f2fc --- /dev/null +++ b/rest/ipMessaging/v1/service/user.ts @@ -0,0 +1,959 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { UserChannelListInstance } from "./user/userChannel"; + + + + + +/** + * Options to pass to update a UserInstance + */ +export interface UserContextUpdateOptions { + /** */ + "roleSid"?: string; + /** */ + "attributes"?: string; + /** */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a UserInstance + */ +export interface UserListInstanceCreateOptions { + /** */ + "identity": string; + /** */ + "roleSid"?: string; + /** */ + "attributes"?: string; + /** */ + "friendlyName"?: string; +} + +/** + * Options to pass to each + */ +export interface UserListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserContext { + userChannels: UserChannelListInstance; + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserContextSolution { + "serviceSid": string; + "sid": string; +} + +export class UserContextImpl implements UserContext { + protected _solution: UserContextSolution; + protected _uri: string; + + protected _userChannels?: UserChannelListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Users/${sid}`; + } + + get userChannels(): UserChannelListInstance { + this._userChannels = this._userChannels || UserChannelListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._userChannels; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserContextUpdateOptions | ((error: Error | null, item?: UserInstance) => any),callback?: (error: Error | null, item?: UserInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserPayload extends TwilioResponsePayload { + users: UserResource[]; +} + +interface UserResource { + sid: string; + account_sid: string; + service_sid: string; + attributes: string; + friendly_name: string; + role_sid: string; + identity: string; + is_online: boolean; + is_notifiable: boolean; + date_created: Date; + date_updated: Date; + joined_channels_count: number; + links: Record; + url: string; +} + +export class UserInstance { + protected _solution: UserContextSolution; + protected _context?: UserContext; + + constructor(protected _version: V1, payload: UserResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.attributes = (payload.attributes); + this.friendlyName = (payload.friendly_name); + this.roleSid = (payload.role_sid); + this.identity = (payload.identity); + this.isOnline = (payload.is_online); + this.isNotifiable = (payload.is_notifiable); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.joinedChannelsCount = deserialize.integer(payload.joined_channels_count); + this.links = (payload.links); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + sid: string; + accountSid: string; + serviceSid: string; + attributes: string; + friendlyName: string; + roleSid: string; + identity: string; + isOnline: boolean; + isNotifiable: boolean; + dateCreated: Date; + dateUpdated: Date; + joinedChannelsCount: number; + links: Record; + url: string; + + private get _proxy(): UserContext { + this._context = this._context || new UserContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the userChannels. + */ + userChannels(): UserChannelListInstance { + return this._proxy.userChannels; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + attributes: this.attributes, + friendlyName: this.friendlyName, + roleSid: this.roleSid, + identity: this.identity, + isOnline: this.isOnline, + isNotifiable: this.isNotifiable, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + joinedChannelsCount: this.joinedChannelsCount, + links: this.links, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserSolution { + serviceSid: string; +} + +export interface UserListInstance { + _version: V1; + _solution: UserSolution; + _uri: string; + + (sid: string, ): UserContext; + get(sid: string, ): UserContext; + + + + + + + + + /** + * Create a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Create a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams UserInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + each(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single target page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + list(params: UserListInstanceOptions, callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + /** + * Lists UserInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserPage) => any): Promise; + page(params: UserListInstancePageOptions, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserListInstance(version: V1, serviceSid: string): UserListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as UserListInstance; + + instance.get = function get(sid, ): UserContext { + return new UserContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Users`; + + instance.create = function create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: UserInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: UserListInstancePageOptions | ((error: Error | null, items: UserPage) => any), callback?: (error: Error | null, items: UserPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserPage extends Page { +/** +* Initialize the UserPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: UserSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserResource): UserInstance { + + return new UserInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v1/service/user/userChannel.ts b/rest/ipMessaging/v1/service/user/userChannel.ts new file mode 100644 index 000000000..693dddb96 --- /dev/null +++ b/rest/ipMessaging/v1/service/user/userChannel.ts @@ -0,0 +1,417 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type UserChannelChannelStatus = 'joined'|'invited'|'not_participating'; + + +/** + * Options to pass to each + */ +export interface UserChannelListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserChannelListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserChannelListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface UserChannelSolution { + serviceSid: string; + userSid: string; +} + +export interface UserChannelListInstance { + _version: V1; + _solution: UserChannelSolution; + _uri: string; + + + + + /** + * Streams UserChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + each(params: UserChannelListInstanceEachOptions, callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserChannelListInstanceEachOptions, callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + /** + * Retrieve a single target page of UserChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserChannelInstance[]) => any): Promise; + list(params: UserChannelListInstanceOptions, callback?: (error: Error | null, items: UserChannelInstance[]) => any): Promise; + /** + * Lists UserChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + page(params: UserChannelListInstancePageOptions, callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + /** + * Retrieve a single page of UserChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserChannelListInstance(version: V1, serviceSid: string, userSid: string): UserChannelListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + const instance = {} as UserChannelListInstance; + + instance._version = version; + instance._solution = { serviceSid, userSid, }; + instance._uri = `/Services/${serviceSid}/Users/${userSid}/Channels`; + + instance.page = function page(params?: UserChannelListInstancePageOptions | ((error: Error | null, items: UserChannelPage) => any), callback?: (error: Error | null, items: UserChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface UserChannelPayload extends TwilioResponsePayload { + channels: UserChannelResource[]; +} + +interface UserChannelResource { + account_sid: string; + service_sid: string; + channel_sid: string; + member_sid: string; + status: UserChannelChannelStatus; + last_consumed_message_index: number; + unread_messages_count: number; + links: Record; +} + +export class UserChannelInstance { + + constructor(protected _version: V1, payload: UserChannelResource, serviceSid: string, userSid: string) { + + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.channelSid = (payload.channel_sid); + this.memberSid = (payload.member_sid); + this.status = payload.status; + this.lastConsumedMessageIndex = deserialize.integer(payload.last_consumed_message_index); + this.unreadMessagesCount = deserialize.integer(payload.unread_messages_count); + this.links = (payload.links); + + } + + accountSid: string; + serviceSid: string; + channelSid: string; + memberSid: string; + status: UserChannelChannelStatus; + lastConsumedMessageIndex: number; + unreadMessagesCount: number; + links: Record; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + serviceSid: this.serviceSid, + channelSid: this.channelSid, + memberSid: this.memberSid, + status: this.status, + lastConsumedMessageIndex: this.lastConsumedMessageIndex, + unreadMessagesCount: this.unreadMessagesCount, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class UserChannelPage extends Page { +/** +* Initialize the UserChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: UserChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserChannelResource): UserChannelInstance { + + return new UserChannelInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.userSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/credential.ts b/rest/ipMessaging/v2/credential.ts new file mode 100644 index 000000000..17f329ce0 --- /dev/null +++ b/rest/ipMessaging/v2/credential.ts @@ -0,0 +1,947 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export type CredentialPushService = 'gcm'|'apn'|'fcm'; + + + + +/** + * Options to pass to update a CredentialInstance + */ +export interface CredentialContextUpdateOptions { + /** */ + "friendlyName"?: string; + /** */ + "certificate"?: string; + /** */ + "privateKey"?: string; + /** */ + "sandbox"?: boolean; + /** */ + "apiKey"?: string; + /** */ + "secret"?: string; +} + +/** + * Options to pass to create a CredentialInstance + */ +export interface CredentialListInstanceCreateOptions { + /** */ + "type": CredentialPushService; + /** */ + "friendlyName"?: string; + /** */ + "certificate"?: string; + /** */ + "privateKey"?: string; + /** */ + "sandbox"?: boolean; + /** */ + "apiKey"?: string; + /** */ + "secret"?: string; +} + +/** + * Options to pass to each + */ +export interface CredentialListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CredentialInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CredentialListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CredentialListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CredentialContext { + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CredentialContextSolution { + "sid": string; +} + +export class CredentialContextImpl implements CredentialContext { + protected _solution: CredentialContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Credentials/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: CredentialInstance) => any),callback?: (error: Error | null, item?: CredentialInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CredentialPayload extends TwilioResponsePayload { + credentials: CredentialResource[]; +} + +interface CredentialResource { + sid: string; + account_sid: string; + friendly_name: string; + type: CredentialPushService; + sandbox: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CredentialInstance { + protected _solution: CredentialContextSolution; + protected _context?: CredentialContext; + + constructor(protected _version: V2, payload: CredentialResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.sandbox = (payload.sandbox); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + sid: string; + accountSid: string; + friendlyName: string; + type: CredentialPushService; + sandbox: string; + dateCreated: Date; + dateUpdated: Date; + url: string; + + private get _proxy(): CredentialContext { + this._context = this._context || new CredentialContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + type: this.type, + sandbox: this.sandbox, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CredentialSolution { +} + +export interface CredentialListInstance { + _version: V2; + _solution: CredentialSolution; + _uri: string; + + (sid: string, ): CredentialContext; + get(sid: string, ): CredentialContext; + + + + + + + + + /** + * Create a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise; + + /** + * Create a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams CredentialInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + each(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CredentialInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single target page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists CredentialInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + list(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise; + /** + * Lists CredentialInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CredentialPage) => any): Promise; + page(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: CredentialPage) => any): Promise; + /** + * Retrieve a single page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CredentialListInstance(version: V2): CredentialListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CredentialListInstance; + + instance.get = function get(sid, ): CredentialContext { + return new CredentialContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Credentials`; + + instance.create = function create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: CredentialInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CredentialListInstancePageOptions | ((error: Error | null, items: CredentialPage) => any), callback?: (error: Error | null, items: CredentialPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CredentialPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CredentialPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CredentialListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CredentialPage extends Page { +/** +* Initialize the CredentialPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: CredentialSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CredentialInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CredentialResource): CredentialInstance { + + return new CredentialInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service.ts b/rest/ipMessaging/v2/service.ts new file mode 100644 index 000000000..8410ffd58 --- /dev/null +++ b/rest/ipMessaging/v2/service.ts @@ -0,0 +1,1179 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { BindingListInstance } from "./service/binding"; +import { ChannelListInstance } from "./service/channel"; +import { RoleListInstance } from "./service/role"; +import { UserListInstance } from "./service/user"; + + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** */ + "friendlyName"?: string; + /** */ + "defaultServiceRoleSid"?: string; + /** */ + "defaultChannelRoleSid"?: string; + /** */ + "defaultChannelCreatorRoleSid"?: string; + /** */ + "readStatusEnabled"?: boolean; + /** */ + "reachabilityEnabled"?: boolean; + /** */ + "typingIndicatorTimeout"?: number; + /** */ + "consumptionReportInterval"?: number; + /** */ + "notifications.newMessage.enabled"?: boolean; + /** */ + "notifications.newMessage.template"?: string; + /** */ + "notifications.newMessage.sound"?: string; + /** */ + "notifications.newMessage.badgeCountEnabled"?: boolean; + /** */ + "notifications.addedToChannel.enabled"?: boolean; + /** */ + "notifications.addedToChannel.template"?: string; + /** */ + "notifications.addedToChannel.sound"?: string; + /** */ + "notifications.removedFromChannel.enabled"?: boolean; + /** */ + "notifications.removedFromChannel.template"?: string; + /** */ + "notifications.removedFromChannel.sound"?: string; + /** */ + "notifications.invitedToChannel.enabled"?: boolean; + /** */ + "notifications.invitedToChannel.template"?: string; + /** */ + "notifications.invitedToChannel.sound"?: string; + /** */ + "preWebhookUrl"?: string; + /** */ + "postWebhookUrl"?: string; + /** */ + "webhookMethod"?: string; + /** */ + "webhookFilters"?: Array; + /** */ + "limits.channelMembers"?: number; + /** */ + "limits.userChannels"?: number; + /** */ + "media.compatibilityMessage"?: string; + /** */ + "preWebhookRetryCount"?: number; + /** */ + "postWebhookRetryCount"?: number; + /** */ + "notifications.logEnabled"?: boolean; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** */ + "friendlyName": string; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + bindings: BindingListInstance; + channels: ChannelListInstance; + roles: RoleListInstance; + users: UserListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _bindings?: BindingListInstance; + protected _channels?: ChannelListInstance; + protected _roles?: RoleListInstance; + protected _users?: UserListInstance; + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get bindings(): BindingListInstance { + this._bindings = this._bindings || BindingListInstance(this._version, this._solution.sid); + return this._bindings; + } + + get channels(): ChannelListInstance { + this._channels = this._channels || ChannelListInstance(this._version, this._solution.sid); + return this._channels; + } + + get roles(): RoleListInstance { + this._roles = this._roles || RoleListInstance(this._version, this._solution.sid); + return this._roles; + } + + get users(): UserListInstance { + this._users = this._users || UserListInstance(this._version, this._solution.sid); + return this._users; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["defaultServiceRoleSid"] !== undefined) + data["DefaultServiceRoleSid"] = params["defaultServiceRoleSid"]; + if (params["defaultChannelRoleSid"] !== undefined) + data["DefaultChannelRoleSid"] = params["defaultChannelRoleSid"]; + if (params["defaultChannelCreatorRoleSid"] !== undefined) + data["DefaultChannelCreatorRoleSid"] = params["defaultChannelCreatorRoleSid"]; + if (params["readStatusEnabled"] !== undefined) + data["ReadStatusEnabled"] = serialize.bool(params["readStatusEnabled"]); + if (params["reachabilityEnabled"] !== undefined) + data["ReachabilityEnabled"] = serialize.bool(params["reachabilityEnabled"]); + if (params["typingIndicatorTimeout"] !== undefined) + data["TypingIndicatorTimeout"] = params["typingIndicatorTimeout"]; + if (params["consumptionReportInterval"] !== undefined) + data["ConsumptionReportInterval"] = params["consumptionReportInterval"]; + if (params["notifications.newMessage.enabled"] !== undefined) + data["Notifications.NewMessage.Enabled"] = serialize.bool(params["notifications.newMessage.enabled"]); + if (params["notifications.newMessage.template"] !== undefined) + data["Notifications.NewMessage.Template"] = params["notifications.newMessage.template"]; + if (params["notifications.newMessage.sound"] !== undefined) + data["Notifications.NewMessage.Sound"] = params["notifications.newMessage.sound"]; + if (params["notifications.newMessage.badgeCountEnabled"] !== undefined) + data["Notifications.NewMessage.BadgeCountEnabled"] = serialize.bool(params["notifications.newMessage.badgeCountEnabled"]); + if (params["notifications.addedToChannel.enabled"] !== undefined) + data["Notifications.AddedToChannel.Enabled"] = serialize.bool(params["notifications.addedToChannel.enabled"]); + if (params["notifications.addedToChannel.template"] !== undefined) + data["Notifications.AddedToChannel.Template"] = params["notifications.addedToChannel.template"]; + if (params["notifications.addedToChannel.sound"] !== undefined) + data["Notifications.AddedToChannel.Sound"] = params["notifications.addedToChannel.sound"]; + if (params["notifications.removedFromChannel.enabled"] !== undefined) + data["Notifications.RemovedFromChannel.Enabled"] = serialize.bool(params["notifications.removedFromChannel.enabled"]); + if (params["notifications.removedFromChannel.template"] !== undefined) + data["Notifications.RemovedFromChannel.Template"] = params["notifications.removedFromChannel.template"]; + if (params["notifications.removedFromChannel.sound"] !== undefined) + data["Notifications.RemovedFromChannel.Sound"] = params["notifications.removedFromChannel.sound"]; + if (params["notifications.invitedToChannel.enabled"] !== undefined) + data["Notifications.InvitedToChannel.Enabled"] = serialize.bool(params["notifications.invitedToChannel.enabled"]); + if (params["notifications.invitedToChannel.template"] !== undefined) + data["Notifications.InvitedToChannel.Template"] = params["notifications.invitedToChannel.template"]; + if (params["notifications.invitedToChannel.sound"] !== undefined) + data["Notifications.InvitedToChannel.Sound"] = params["notifications.invitedToChannel.sound"]; + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + if (params["webhookFilters"] !== undefined) + data["WebhookFilters"] = serialize.map(params["webhookFilters"], (e: string) => (e)); + if (params["limits.channelMembers"] !== undefined) + data["Limits.ChannelMembers"] = params["limits.channelMembers"]; + if (params["limits.userChannels"] !== undefined) + data["Limits.UserChannels"] = params["limits.userChannels"]; + if (params["media.compatibilityMessage"] !== undefined) + data["Media.CompatibilityMessage"] = params["media.compatibilityMessage"]; + if (params["preWebhookRetryCount"] !== undefined) + data["PreWebhookRetryCount"] = params["preWebhookRetryCount"]; + if (params["postWebhookRetryCount"] !== undefined) + data["PostWebhookRetryCount"] = params["postWebhookRetryCount"]; + if (params["notifications.logEnabled"] !== undefined) + data["Notifications.LogEnabled"] = serialize.bool(params["notifications.logEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["defaultServiceRoleSid"] !== undefined) + data["DefaultServiceRoleSid"] = params["defaultServiceRoleSid"]; + if (params["defaultChannelRoleSid"] !== undefined) + data["DefaultChannelRoleSid"] = params["defaultChannelRoleSid"]; + if (params["defaultChannelCreatorRoleSid"] !== undefined) + data["DefaultChannelCreatorRoleSid"] = params["defaultChannelCreatorRoleSid"]; + if (params["readStatusEnabled"] !== undefined) + data["ReadStatusEnabled"] = serialize.bool(params["readStatusEnabled"]); + if (params["reachabilityEnabled"] !== undefined) + data["ReachabilityEnabled"] = serialize.bool(params["reachabilityEnabled"]); + if (params["typingIndicatorTimeout"] !== undefined) + data["TypingIndicatorTimeout"] = params["typingIndicatorTimeout"]; + if (params["consumptionReportInterval"] !== undefined) + data["ConsumptionReportInterval"] = params["consumptionReportInterval"]; + if (params["notifications.newMessage.enabled"] !== undefined) + data["Notifications.NewMessage.Enabled"] = serialize.bool(params["notifications.newMessage.enabled"]); + if (params["notifications.newMessage.template"] !== undefined) + data["Notifications.NewMessage.Template"] = params["notifications.newMessage.template"]; + if (params["notifications.newMessage.sound"] !== undefined) + data["Notifications.NewMessage.Sound"] = params["notifications.newMessage.sound"]; + if (params["notifications.newMessage.badgeCountEnabled"] !== undefined) + data["Notifications.NewMessage.BadgeCountEnabled"] = serialize.bool(params["notifications.newMessage.badgeCountEnabled"]); + if (params["notifications.addedToChannel.enabled"] !== undefined) + data["Notifications.AddedToChannel.Enabled"] = serialize.bool(params["notifications.addedToChannel.enabled"]); + if (params["notifications.addedToChannel.template"] !== undefined) + data["Notifications.AddedToChannel.Template"] = params["notifications.addedToChannel.template"]; + if (params["notifications.addedToChannel.sound"] !== undefined) + data["Notifications.AddedToChannel.Sound"] = params["notifications.addedToChannel.sound"]; + if (params["notifications.removedFromChannel.enabled"] !== undefined) + data["Notifications.RemovedFromChannel.Enabled"] = serialize.bool(params["notifications.removedFromChannel.enabled"]); + if (params["notifications.removedFromChannel.template"] !== undefined) + data["Notifications.RemovedFromChannel.Template"] = params["notifications.removedFromChannel.template"]; + if (params["notifications.removedFromChannel.sound"] !== undefined) + data["Notifications.RemovedFromChannel.Sound"] = params["notifications.removedFromChannel.sound"]; + if (params["notifications.invitedToChannel.enabled"] !== undefined) + data["Notifications.InvitedToChannel.Enabled"] = serialize.bool(params["notifications.invitedToChannel.enabled"]); + if (params["notifications.invitedToChannel.template"] !== undefined) + data["Notifications.InvitedToChannel.Template"] = params["notifications.invitedToChannel.template"]; + if (params["notifications.invitedToChannel.sound"] !== undefined) + data["Notifications.InvitedToChannel.Sound"] = params["notifications.invitedToChannel.sound"]; + if (params["preWebhookUrl"] !== undefined) + data["PreWebhookUrl"] = params["preWebhookUrl"]; + if (params["postWebhookUrl"] !== undefined) + data["PostWebhookUrl"] = params["postWebhookUrl"]; + if (params["webhookMethod"] !== undefined) + data["WebhookMethod"] = params["webhookMethod"]; + if (params["webhookFilters"] !== undefined) + data["WebhookFilters"] = serialize.map(params["webhookFilters"], (e: string) => (e)); + if (params["limits.channelMembers"] !== undefined) + data["Limits.ChannelMembers"] = params["limits.channelMembers"]; + if (params["limits.userChannels"] !== undefined) + data["Limits.UserChannels"] = params["limits.userChannels"]; + if (params["media.compatibilityMessage"] !== undefined) + data["Media.CompatibilityMessage"] = params["media.compatibilityMessage"]; + if (params["preWebhookRetryCount"] !== undefined) + data["PreWebhookRetryCount"] = params["preWebhookRetryCount"]; + if (params["postWebhookRetryCount"] !== undefined) + data["PostWebhookRetryCount"] = params["postWebhookRetryCount"]; + if (params["notifications.logEnabled"] !== undefined) + data["Notifications.LogEnabled"] = serialize.bool(params["notifications.logEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + sid: string; + account_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + default_service_role_sid: string; + default_channel_role_sid: string; + default_channel_creator_role_sid: string; + read_status_enabled: boolean; + reachability_enabled: boolean; + typing_indicator_timeout: number; + consumption_report_interval: number; + limits: any; + pre_webhook_url: string; + post_webhook_url: string; + webhook_method: string; + webhook_filters: Array; + pre_webhook_retry_count: number; + post_webhook_retry_count: number; + notifications: any; + media: any; + url: string; + links: Record; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V2, payload: ServiceResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.defaultServiceRoleSid = (payload.default_service_role_sid); + this.defaultChannelRoleSid = (payload.default_channel_role_sid); + this.defaultChannelCreatorRoleSid = (payload.default_channel_creator_role_sid); + this.readStatusEnabled = (payload.read_status_enabled); + this.reachabilityEnabled = (payload.reachability_enabled); + this.typingIndicatorTimeout = deserialize.integer(payload.typing_indicator_timeout); + this.consumptionReportInterval = deserialize.integer(payload.consumption_report_interval); + this.limits = (payload.limits); + this.preWebhookUrl = (payload.pre_webhook_url); + this.postWebhookUrl = (payload.post_webhook_url); + this.webhookMethod = (payload.webhook_method); + this.webhookFilters = (payload.webhook_filters); + this.preWebhookRetryCount = deserialize.integer(payload.pre_webhook_retry_count); + this.postWebhookRetryCount = deserialize.integer(payload.post_webhook_retry_count); + this.notifications = (payload.notifications); + this.media = (payload.media); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + sid: string; + accountSid: string; + friendlyName: string; + dateCreated: Date; + dateUpdated: Date; + defaultServiceRoleSid: string; + defaultChannelRoleSid: string; + defaultChannelCreatorRoleSid: string; + readStatusEnabled: boolean; + reachabilityEnabled: boolean; + typingIndicatorTimeout: number; + consumptionReportInterval: number; + limits: any; + preWebhookUrl: string; + postWebhookUrl: string; + webhookMethod: string; + webhookFilters: Array; + preWebhookRetryCount: number; + postWebhookRetryCount: number; + notifications: any; + media: any; + url: string; + links: Record; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the bindings. + */ + bindings(): BindingListInstance { + return this._proxy.bindings; + } + + /** + * Access the channels. + */ + channels(): ChannelListInstance { + return this._proxy.channels; + } + + /** + * Access the roles. + */ + roles(): RoleListInstance { + return this._proxy.roles; + } + + /** + * Access the users. + */ + users(): UserListInstance { + return this._proxy.users; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + defaultServiceRoleSid: this.defaultServiceRoleSid, + defaultChannelRoleSid: this.defaultChannelRoleSid, + defaultChannelCreatorRoleSid: this.defaultChannelCreatorRoleSid, + readStatusEnabled: this.readStatusEnabled, + reachabilityEnabled: this.reachabilityEnabled, + typingIndicatorTimeout: this.typingIndicatorTimeout, + consumptionReportInterval: this.consumptionReportInterval, + limits: this.limits, + preWebhookUrl: this.preWebhookUrl, + postWebhookUrl: this.postWebhookUrl, + webhookMethod: this.webhookMethod, + webhookFilters: this.webhookFilters, + preWebhookRetryCount: this.preWebhookRetryCount, + postWebhookRetryCount: this.postWebhookRetryCount, + notifications: this.notifications, + media: this.media, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V2; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V2): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ServiceInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service/binding.ts b/rest/ipMessaging/v2/service/binding.ts new file mode 100644 index 000000000..2b9acebb6 --- /dev/null +++ b/rest/ipMessaging/v2/service/binding.ts @@ -0,0 +1,668 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export type BindingBindingType = 'gcm'|'apn'|'fcm'; + + + + +/** + * Options to pass to each + */ +export interface BindingListInstanceEachOptions { + /** */ + "bindingType"?: Array; + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BindingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BindingListInstanceOptions { + /** */ + "bindingType"?: Array; + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BindingListInstancePageOptions { + /** */ + "bindingType"?: Array; + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface BindingContext { + + /** + * Remove a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance + */ + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise + + /** + * Fetch a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BindingContextSolution { + "serviceSid": string; + "sid": string; +} + +export class BindingContextImpl implements BindingContext { + protected _solution: BindingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Bindings/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BindingInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new BindingInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BindingPayload extends TwilioResponsePayload { + bindings: BindingResource[]; +} + +interface BindingResource { + sid: string; + account_sid: string; + service_sid: string; + date_created: Date; + date_updated: Date; + endpoint: string; + identity: string; + credential_sid: string; + binding_type: BindingBindingType; + message_types: Array; + url: string; + links: Record; +} + +export class BindingInstance { + protected _solution: BindingContextSolution; + protected _context?: BindingContext; + + constructor(protected _version: V2, payload: BindingResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.endpoint = (payload.endpoint); + this.identity = (payload.identity); + this.credentialSid = (payload.credential_sid); + this.bindingType = payload.binding_type; + this.messageTypes = (payload.message_types); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + sid: string; + accountSid: string; + serviceSid: string; + dateCreated: Date; + dateUpdated: Date; + endpoint: string; + identity: string; + credentialSid: string; + bindingType: BindingBindingType; + messageTypes: Array; + url: string; + links: Record; + + private get _proxy(): BindingContext { + this._context = this._context || new BindingContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance + */ + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + endpoint: this.endpoint, + identity: this.identity, + credentialSid: this.credentialSid, + bindingType: this.bindingType, + messageTypes: this.messageTypes, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BindingSolution { + serviceSid: string; +} + +export interface BindingListInstance { + _version: V2; + _solution: BindingSolution; + _uri: string; + + (sid: string, ): BindingContext; + get(sid: string, ): BindingContext; + + + + + + + + /** + * Streams BindingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + each(params: BindingListInstanceEachOptions, callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BindingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BindingListInstanceEachOptions, callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BindingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BindingPage) => any): Promise; + /** + * Retrieve a single target page of BindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists BindingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BindingInstance[]) => any): Promise; + list(params: BindingListInstanceOptions, callback?: (error: Error | null, items: BindingInstance[]) => any): Promise; + /** + * Lists BindingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: BindingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of BindingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BindingPage) => any): Promise; + page(params: BindingListInstancePageOptions, callback?: (error: Error | null, items: BindingPage) => any): Promise; + /** + * Retrieve a single page of BindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: BindingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BindingListInstance(version: V2, serviceSid: string): BindingListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as BindingListInstance; + + instance.get = function get(sid, ): BindingContext { + return new BindingContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Bindings`; + + instance.page = function page(params?: BindingListInstancePageOptions | ((error: Error | null, items: BindingPage) => any), callback?: (error: Error | null, items: BindingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["bindingType"] !== undefined) + data["BindingType"] = serialize.map(params["bindingType"], (e: BindingBindingType) => (e)); + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BindingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BindingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BindingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BindingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["bindingType"] !== undefined) + data["BindingType"] = serialize.map(params["bindingType"], (e: BindingBindingType) => (e)); + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BindingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BindingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class BindingPage extends Page { +/** +* Initialize the BindingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: BindingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of BindingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BindingResource): BindingInstance { + + return new BindingInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service/channel.ts b/rest/ipMessaging/v2/service/channel.ts new file mode 100644 index 000000000..13020d0c7 --- /dev/null +++ b/rest/ipMessaging/v2/service/channel.ts @@ -0,0 +1,1151 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { InviteListInstance } from "./channel/invite"; +import { MemberListInstance } from "./channel/member"; +import { MessageListInstance } from "./channel/message"; +import { WebhookListInstance } from "./channel/webhook"; + + +export type ChannelChannelType = 'public'|'private'; + +export type ChannelWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a ChannelInstance + */ +export interface ChannelContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ChannelWebhookEnabledType; +} + + +/** + * Options to pass to update a ChannelInstance + */ +export interface ChannelContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ChannelWebhookEnabledType; + /** */ + "friendlyName"?: string; + /** */ + "uniqueName"?: string; + /** */ + "attributes"?: string; + /** */ + "dateCreated"?: Date; + /** */ + "dateUpdated"?: Date; + /** */ + "createdBy"?: string; +} + +/** + * Options to pass to create a ChannelInstance + */ +export interface ChannelListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: ChannelWebhookEnabledType; + /** */ + "friendlyName"?: string; + /** */ + "uniqueName"?: string; + /** */ + "attributes"?: string; + /** */ + "type"?: ChannelChannelType; + /** */ + "dateCreated"?: Date; + /** */ + "dateUpdated"?: Date; + /** */ + "createdBy"?: string; +} + +/** + * Options to pass to each + */ +export interface ChannelListInstanceEachOptions { + /** */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChannelListInstanceOptions { + /** */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChannelListInstancePageOptions { + /** */ + "type"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ChannelContext { + invites: InviteListInstance; + members: MemberListInstance; + messages: MessageListInstance; + webhooks: WebhookListInstance; + + /** + * Remove a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + remove(params: ChannelContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + removeWithHttpInfo(params: ChannelContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + + /** + * Fetch a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Update a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + /** + * Update a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ChannelContextSolution { + "serviceSid": string; + "sid": string; +} + +export class ChannelContextImpl implements ChannelContext { + protected _solution: ChannelContextSolution; + protected _uri: string; + + protected _invites?: InviteListInstance; + protected _members?: MemberListInstance; + protected _messages?: MessageListInstance; + protected _webhooks?: WebhookListInstance; + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${sid}`; + } + + get invites(): InviteListInstance { + this._invites = this._invites || InviteListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._invites; + } + + get members(): MemberListInstance { + this._members = this._members || MemberListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._members; + } + + get messages(): MessageListInstance { + this._messages = this._messages || MessageListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._messages; + } + + get webhooks(): WebhookListInstance { + this._webhooks = this._webhooks || WebhookListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._webhooks; + } + + remove(params?: ChannelContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: ChannelContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ChannelContextUpdateOptions | ((error: Error | null, item?: ChannelInstance) => any),callback?: (error: Error | null, item?: ChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["createdBy"] !== undefined) + data["CreatedBy"] = params["createdBy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ChannelContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["createdBy"] !== undefined) + data["CreatedBy"] = params["createdBy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ChannelPayload extends TwilioResponsePayload { + channels: ChannelResource[]; +} + +interface ChannelResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + unique_name: string; + attributes: string; + type: ChannelChannelType; + date_created: Date; + date_updated: Date; + created_by: string; + members_count: number; + messages_count: number; + url: string; + links: Record; +} + +export class ChannelInstance { + protected _solution: ChannelContextSolution; + protected _context?: ChannelContext; + + constructor(protected _version: V2, payload: ChannelResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.attributes = (payload.attributes); + this.type = payload.type; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + this.membersCount = deserialize.integer(payload.members_count); + this.messagesCount = deserialize.integer(payload.messages_count); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + sid: string; + accountSid: string; + serviceSid: string; + friendlyName: string; + uniqueName: string; + attributes: string; + type: ChannelChannelType; + dateCreated: Date; + dateUpdated: Date; + createdBy: string; + membersCount: number; + messagesCount: number; + url: string; + links: Record; + + private get _proxy(): ChannelContext { + this._context = this._context || new ChannelContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + remove(params: ChannelContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + removeWithHttpInfo(params: ChannelContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Update a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + update(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the invites. + */ + invites(): InviteListInstance { + return this._proxy.invites; + } + + /** + * Access the members. + */ + members(): MemberListInstance { + return this._proxy.members; + } + + /** + * Access the messages. + */ + messages(): MessageListInstance { + return this._proxy.messages; + } + + /** + * Access the webhooks. + */ + webhooks(): WebhookListInstance { + return this._proxy.webhooks; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + attributes: this.attributes, + type: this.type, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + membersCount: this.membersCount, + messagesCount: this.messagesCount, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ChannelSolution { + serviceSid: string; +} + +export interface ChannelListInstance { + _version: V2; + _solution: ChannelSolution; + _uri: string; + + (sid: string, ): ChannelContext; + get(sid: string, ): ChannelContext; + + + + + + + + + /** + * Create a ChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + create(callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + /** + * Create a ChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance + */ + create(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ChannelInstance) => any): Promise; + + /** + * Create a ChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a ChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelInstance with HTTP metadata + */ + createWithHttpInfo(params: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams ChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + each(params: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise; + /** + * Retrieve a single target page of ChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise; + list(params: ChannelListInstanceOptions, callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise; + /** + * Lists ChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ChannelPage) => any): Promise; + page(params: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ChannelPage) => any): Promise; + /** + * Retrieve a single page of ChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChannelListInstance(version: V2, serviceSid: string): ChannelListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ChannelListInstance; + + instance.get = function get(sid, ): ChannelContext { + return new ChannelContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Channels`; + + instance.create = function create(params?: ChannelListInstanceCreateOptions | ((error: Error | null, items: ChannelInstance) => any), callback?: (error: Error | null, items: ChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["createdBy"] !== undefined) + data["CreatedBy"] = params["createdBy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ChannelListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["createdBy"] !== undefined) + data["CreatedBy"] = params["createdBy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new ChannelInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ChannelListInstancePageOptions | ((error: Error | null, items: ChannelPage) => any), callback?: (error: Error | null, items: ChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["type"] !== undefined) + data["Type"] = serialize.map(params["type"], (e: ChannelChannelType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["type"] !== undefined) + data["Type"] = serialize.map(params["type"], (e: ChannelChannelType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ChannelPage extends Page { +/** +* Initialize the ChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: ChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChannelResource): ChannelInstance { + + return new ChannelInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service/channel/invite.ts b/rest/ipMessaging/v2/service/channel/invite.ts new file mode 100644 index 000000000..e3ca64f03 --- /dev/null +++ b/rest/ipMessaging/v2/service/channel/invite.ts @@ -0,0 +1,764 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a InviteInstance + */ +export interface InviteListInstanceCreateOptions { + /** */ + "identity": string; + /** */ + "roleSid"?: string; +} + +/** + * Options to pass to each + */ +export interface InviteListInstanceEachOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InviteInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InviteListInstanceOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InviteListInstancePageOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InviteContext { + + /** + * Remove a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise + + /** + * Fetch a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InviteContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class InviteContextImpl implements InviteContext { + protected _solution: InviteContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Invites/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InviteInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new InviteInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InvitePayload extends TwilioResponsePayload { + invites: InviteResource[]; +} + +interface InviteResource { + sid: string; + account_sid: string; + channel_sid: string; + service_sid: string; + identity: string; + date_created: Date; + date_updated: Date; + role_sid: string; + created_by: string; + url: string; +} + +export class InviteInstance { + protected _solution: InviteContextSolution; + protected _context?: InviteContext; + + constructor(protected _version: V2, payload: InviteResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.channelSid = (payload.channel_sid); + this.serviceSid = (payload.service_sid); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.roleSid = (payload.role_sid); + this.createdBy = (payload.created_by); + this.url = (payload.url); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + sid: string; + accountSid: string; + channelSid: string; + serviceSid: string; + identity: string; + dateCreated: Date; + dateUpdated: Date; + roleSid: string; + createdBy: string; + url: string; + + private get _proxy(): InviteContext { + this._context = this._context || new InviteContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a InviteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + fetch(callback?: (error: Error | null, item?: InviteInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InviteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + channelSid: this.channelSid, + serviceSid: this.serviceSid, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + roleSid: this.roleSid, + createdBy: this.createdBy, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InviteSolution { + serviceSid: string; + channelSid: string; +} + +export interface InviteListInstance { + _version: V2; + _solution: InviteSolution; + _uri: string; + + (sid: string, ): InviteContext; + get(sid: string, ): InviteContext; + + + + + + + /** + * Create a InviteInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance + */ + create(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, item?: InviteInstance) => any): Promise; + + /** + * Create a InviteInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InviteInstance with HTTP metadata + */ + createWithHttpInfo(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams InviteInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + each(params: InviteListInstanceEachOptions, callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InviteInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InviteListInstanceEachOptions, callback?: (item: InviteInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InviteInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InvitePage) => any): Promise; + /** + * Retrieve a single target page of InviteInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists InviteInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InviteInstance[]) => any): Promise; + list(params: InviteListInstanceOptions, callback?: (error: Error | null, items: InviteInstance[]) => any): Promise; + /** + * Lists InviteInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: InviteListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of InviteInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InvitePage) => any): Promise; + page(params: InviteListInstancePageOptions, callback?: (error: Error | null, items: InvitePage) => any): Promise; + /** + * Retrieve a single page of InviteInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InviteListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: InviteListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InviteListInstance(version: V2, serviceSid: string, channelSid: string): InviteListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as InviteListInstance; + + instance.get = function get(sid, ): InviteContext { + return new InviteContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Invites`; + + instance.create = function create(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, items: InviteInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InviteInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InviteListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new InviteInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InviteListInstancePageOptions | ((error: Error | null, items: InvitePage) => any), callback?: (error: Error | null, items: InvitePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InvitePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InvitePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InvitePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InviteListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InvitePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InvitePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InvitePage extends Page { +/** +* Initialize the InvitePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: InviteSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InviteInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InviteResource): InviteInstance { + + return new InviteInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service/channel/member.ts b/rest/ipMessaging/v2/service/channel/member.ts new file mode 100644 index 000000000..da9b3db5d --- /dev/null +++ b/rest/ipMessaging/v2/service/channel/member.ts @@ -0,0 +1,1078 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type MemberWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a MemberInstance + */ +export interface MemberContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MemberWebhookEnabledType; +} + + +/** + * Options to pass to update a MemberInstance + */ +export interface MemberContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MemberWebhookEnabledType; + /** */ + "roleSid"?: string; + /** */ + "lastConsumedMessageIndex"?: number; + /** */ + "lastConsumptionTimestamp"?: Date; + /** */ + "dateCreated"?: Date; + /** */ + "dateUpdated"?: Date; + /** */ + "attributes"?: string; +} + +/** + * Options to pass to create a MemberInstance + */ +export interface MemberListInstanceCreateOptions { + /** */ + "identity": string; + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MemberWebhookEnabledType; + /** */ + "roleSid"?: string; + /** */ + "lastConsumedMessageIndex"?: number; + /** */ + "lastConsumptionTimestamp"?: Date; + /** */ + "dateCreated"?: Date; + /** */ + "dateUpdated"?: Date; + /** */ + "attributes"?: string; +} + +/** + * Options to pass to each + */ +export interface MemberListInstanceEachOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MemberInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MemberListInstanceOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MemberListInstancePageOptions { + /** */ + "identity"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MemberContext { + + /** + * Remove a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + remove(params: MemberContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + removeWithHttpInfo(params: MemberContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise + + /** + * Fetch a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + /** + * Update a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + /** + * Update a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MemberContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class MemberContextImpl implements MemberContext { + protected _solution: MemberContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Members/${sid}`; + } + + remove(params?: MemberContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: MemberContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MemberContextUpdateOptions | ((error: Error | null, item?: MemberInstance) => any),callback?: (error: Error | null, item?: MemberInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MemberContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MemberPayload extends TwilioResponsePayload { + members: MemberResource[]; +} + +interface MemberResource { + sid: string; + account_sid: string; + channel_sid: string; + service_sid: string; + identity: string; + date_created: Date; + date_updated: Date; + role_sid: string; + last_consumed_message_index: number; + last_consumption_timestamp: Date; + url: string; + attributes: string; +} + +export class MemberInstance { + protected _solution: MemberContextSolution; + protected _context?: MemberContext; + + constructor(protected _version: V2, payload: MemberResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.channelSid = (payload.channel_sid); + this.serviceSid = (payload.service_sid); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.roleSid = (payload.role_sid); + this.lastConsumedMessageIndex = deserialize.integer(payload.last_consumed_message_index); + this.lastConsumptionTimestamp = deserialize.iso8601DateTime(payload.last_consumption_timestamp); + this.url = (payload.url); + this.attributes = (payload.attributes); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + sid: string; + accountSid: string; + channelSid: string; + serviceSid: string; + identity: string; + dateCreated: Date; + dateUpdated: Date; + roleSid: string; + lastConsumedMessageIndex: number; + lastConsumptionTimestamp: Date; + url: string; + attributes: string; + + private get _proxy(): MemberContext { + this._context = this._context || new MemberContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + remove(params: MemberContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + removeWithHttpInfo(params: MemberContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + fetch(callback?: (error: Error | null, item?: MemberInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MemberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + /** + * Update a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + update(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MemberInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MemberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + updateWithHttpInfo(params: MemberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + channelSid: this.channelSid, + serviceSid: this.serviceSid, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + roleSid: this.roleSid, + lastConsumedMessageIndex: this.lastConsumedMessageIndex, + lastConsumptionTimestamp: this.lastConsumptionTimestamp, + url: this.url, + attributes: this.attributes, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MemberSolution { + serviceSid: string; + channelSid: string; +} + +export interface MemberListInstance { + _version: V2; + _solution: MemberSolution; + _uri: string; + + (sid: string, ): MemberContext; + get(sid: string, ): MemberContext; + + + + + + + + + /** + * Create a MemberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance + */ + create(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, item?: MemberInstance) => any): Promise; + + /** + * Create a MemberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MemberInstance with HTTP metadata + */ + createWithHttpInfo(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MemberInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + each(params: MemberListInstanceEachOptions, callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MemberInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MemberListInstanceEachOptions, callback?: (item: MemberInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MemberInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MemberPage) => any): Promise; + /** + * Retrieve a single target page of MemberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MemberInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MemberInstance[]) => any): Promise; + list(params: MemberListInstanceOptions, callback?: (error: Error | null, items: MemberInstance[]) => any): Promise; + /** + * Lists MemberInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MemberListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MemberInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MemberPage) => any): Promise; + page(params: MemberListInstancePageOptions, callback?: (error: Error | null, items: MemberPage) => any): Promise; + /** + * Retrieve a single page of MemberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MemberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MemberListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MemberListInstance(version: V2, serviceSid: string, channelSid: string): MemberListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MemberListInstance; + + instance.get = function get(sid, ): MemberContext { + return new MemberContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Members`; + + instance.create = function create(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, items: MemberInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MemberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MemberListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MemberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MemberListInstancePageOptions | ((error: Error | null, items: MemberPage) => any), callback?: (error: Error | null, items: MemberPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MemberPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MemberPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MemberPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MemberListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MemberPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MemberPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MemberPage extends Page { +/** +* Initialize the MemberPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: MemberSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MemberInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MemberResource): MemberInstance { + + return new MemberInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service/channel/message.ts b/rest/ipMessaging/v2/service/channel/message.ts new file mode 100644 index 000000000..aff2a6dd6 --- /dev/null +++ b/rest/ipMessaging/v2/service/channel/message.ts @@ -0,0 +1,1110 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type MessageOrderType = 'asc'|'desc'; + +export type MessageWebhookEnabledType = 'true'|'false'; + + +/** + * Options to pass to remove a MessageInstance + */ +export interface MessageContextRemoveOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; +} + + +/** + * Options to pass to update a MessageInstance + */ +export interface MessageContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; + /** */ + "body"?: string; + /** */ + "attributes"?: string; + /** */ + "dateCreated"?: Date; + /** */ + "dateUpdated"?: Date; + /** */ + "lastUpdatedBy"?: string; + /** */ + "from"?: string; +} + +/** + * Options to pass to create a MessageInstance + */ +export interface MessageListInstanceCreateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: MessageWebhookEnabledType; + /** */ + "from"?: string; + /** */ + "attributes"?: string; + /** */ + "dateCreated"?: Date; + /** */ + "dateUpdated"?: Date; + /** */ + "lastUpdatedBy"?: string; + /** */ + "body"?: string; + /** */ + "mediaSid"?: string; +} + +/** + * Options to pass to each + */ +export interface MessageListInstanceEachOptions { + /** */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MessageInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MessageListInstanceOptions { + /** */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MessageListInstancePageOptions { + /** */ + "order"?: MessageOrderType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MessageContext { + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + remove(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + removeWithHttpInfo(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MessageContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class MessageContextImpl implements MessageContext { + protected _solution: MessageContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Messages/${sid}`; + } + + remove(params?: MessageContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: MessageContextRemoveOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MessageContextUpdateOptions | ((error: Error | null, item?: MessageInstance) => any),callback?: (error: Error | null, item?: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["lastUpdatedBy"] !== undefined) + data["LastUpdatedBy"] = params["lastUpdatedBy"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MessageContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["lastUpdatedBy"] !== undefined) + data["LastUpdatedBy"] = params["lastUpdatedBy"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MessagePayload extends TwilioResponsePayload { + messages: MessageResource[]; +} + +interface MessageResource { + sid: string; + account_sid: string; + attributes: string; + service_sid: string; + to: string; + channel_sid: string; + date_created: Date; + date_updated: Date; + last_updated_by: string; + was_edited: boolean; + from: string; + body: string; + index: number; + type: string; + media: any; + url: string; +} + +export class MessageInstance { + protected _solution: MessageContextSolution; + protected _context?: MessageContext; + + constructor(protected _version: V2, payload: MessageResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.attributes = (payload.attributes); + this.serviceSid = (payload.service_sid); + this.to = (payload.to); + this.channelSid = (payload.channel_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.lastUpdatedBy = (payload.last_updated_by); + this.wasEdited = (payload.was_edited); + this.from = (payload.from); + this.body = (payload.body); + this.index = deserialize.integer(payload.index); + this.type = (payload.type); + this.media = (payload.media); + this.url = (payload.url); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + sid: string; + accountSid: string; + attributes: string; + serviceSid: string; + to: string; + channelSid: string; + dateCreated: Date; + dateUpdated: Date; + lastUpdatedBy: string; + wasEdited: boolean; + from: string; + body: string; + index: number; + type: string; + media: any; + url: string; + + private get _proxy(): MessageContext { + this._context = this._context || new MessageContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise; + /** + * Remove a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + remove(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Remove a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + removeWithHttpInfo(params: MessageContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Update a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + update(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: MessageInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessageContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + attributes: this.attributes, + serviceSid: this.serviceSid, + to: this.to, + channelSid: this.channelSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + lastUpdatedBy: this.lastUpdatedBy, + wasEdited: this.wasEdited, + from: this.from, + body: this.body, + index: this.index, + type: this.type, + media: this.media, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MessageSolution { + serviceSid: string; + channelSid: string; +} + +export interface MessageListInstance { + _version: V2; + _solution: MessageSolution; + _uri: string; + + (sid: string, ): MessageContext; + get(sid: string, ): MessageContext; + + + + + + + + + /** + * Create a MessageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + /** + * Create a MessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance + */ + create(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: MessageInstance) => any): Promise; + + /** + * Create a MessageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Create a MessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInstance with HTTP metadata + */ + createWithHttpInfo(params: MessageListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams MessageInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + each(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MessageInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MessageListInstanceEachOptions, callback?: (item: MessageInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single target page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists MessageInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + list(params: MessageListInstanceOptions, callback?: (error: Error | null, items: MessageInstance[]) => any): Promise; + /** + * Lists MessageInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: MessageListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of MessageInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MessagePage) => any): Promise; + page(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: MessagePage) => any): Promise; + /** + * Retrieve a single page of MessageInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: MessageListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessageListInstance(version: V2, serviceSid: string, channelSid: string): MessageListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MessageListInstance; + + instance.get = function get(sid, ): MessageContext { + return new MessageContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Messages`; + + instance.create = function create(params?: MessageListInstanceCreateOptions | ((error: Error | null, items: MessageInstance) => any), callback?: (error: Error | null, items: MessageInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["lastUpdatedBy"] !== undefined) + data["LastUpdatedBy"] = params["lastUpdatedBy"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["mediaSid"] !== undefined) + data["MediaSid"] = params["mediaSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: MessageListInstanceCreateOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["dateCreated"] !== undefined) + data["DateCreated"] = serialize.iso8601DateTime(params["dateCreated"]); + if (params["dateUpdated"] !== undefined) + data["DateUpdated"] = serialize.iso8601DateTime(params["dateUpdated"]); + if (params["lastUpdatedBy"] !== undefined) + data["LastUpdatedBy"] = params["lastUpdatedBy"]; + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["mediaSid"] !== undefined) + data["MediaSid"] = params["mediaSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new MessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MessageListInstancePageOptions | ((error: Error | null, items: MessagePage) => any), callback?: (error: Error | null, items: MessagePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MessagePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MessagePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MessagePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MessageListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MessagePage extends Page { +/** +* Initialize the MessagePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: MessageSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MessageInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MessageResource): MessageInstance { + + return new MessageInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service/channel/webhook.ts b/rest/ipMessaging/v2/service/channel/webhook.ts new file mode 100644 index 000000000..6fe04e2a4 --- /dev/null +++ b/rest/ipMessaging/v2/service/channel/webhook.ts @@ -0,0 +1,975 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type WebhookMethod = 'GET'|'POST'; + +export type WebhookType = 'webhook'|'trigger'|'studio'; + + + + +/** + * Options to pass to update a WebhookInstance + */ +export interface WebhookContextUpdateOptions { + /** */ + "configuration.url"?: string; + /** */ + "configuration.method"?: WebhookMethod; + /** */ + "configuration.filters"?: Array; + /** */ + "configuration.triggers"?: Array; + /** */ + "configuration.flowSid"?: string; + /** */ + "configuration.retryCount"?: number; +} + +/** + * Options to pass to create a WebhookInstance + */ +export interface WebhookListInstanceCreateOptions { + /** */ + "type": WebhookType; + /** */ + "configuration.url"?: string; + /** */ + "configuration.method"?: WebhookMethod; + /** */ + "configuration.filters"?: Array; + /** */ + "configuration.triggers"?: Array; + /** */ + "configuration.flowSid"?: string; + /** */ + "configuration.retryCount"?: number; +} + +/** + * Options to pass to each + */ +export interface WebhookListInstanceEachOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: WebhookInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface WebhookListInstanceOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface WebhookListInstancePageOptions { + /** How many resources to return in each list page. The default is 5, and the maximum is 5. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface WebhookContext { + + /** + * Remove a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WebhookContextSolution { + "serviceSid": string; + "channelSid": string; + "sid": string; +} + +export class WebhookContextImpl implements WebhookContext { + protected _solution: WebhookContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, channelSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, channelSid, sid, }; + this._uri = `/Services/${serviceSid}/Channels/${channelSid}/Webhooks/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: WebhookInstance) => any),callback?: (error: Error | null, item?: WebhookInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.retryCount"] !== undefined) + data["Configuration.RetryCount"] = params["configuration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.retryCount"] !== undefined) + data["Configuration.RetryCount"] = params["configuration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WebhookPayload extends TwilioResponsePayload { + webhooks: WebhookResource[]; +} + +interface WebhookResource { + sid: string; + account_sid: string; + service_sid: string; + channel_sid: string; + type: string; + url: string; + configuration: any; + date_created: Date; + date_updated: Date; +} + +export class WebhookInstance { + protected _solution: WebhookContextSolution; + protected _context?: WebhookContext; + + constructor(protected _version: V2, payload: WebhookResource, serviceSid: string, channelSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.channelSid = (payload.channel_sid); + this.type = (payload.type); + this.url = (payload.url); + this.configuration = (payload.configuration); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { serviceSid, channelSid, sid: sid, }; + } + + sid: string; + accountSid: string; + serviceSid: string; + channelSid: string; + type: string; + url: string; + configuration: any; + dateCreated: Date; + dateUpdated: Date; + + private get _proxy(): WebhookContext { + this._context = this._context || new WebhookContextImpl(this._version, this._solution.serviceSid, this._solution.channelSid, this._solution.sid); + return this._context; + } + + /** + * Remove a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + channelSid: this.channelSid, + type: this.type, + url: this.url, + configuration: this.configuration, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WebhookSolution { + serviceSid: string; + channelSid: string; +} + +export interface WebhookListInstance { + _version: V2; + _solution: WebhookSolution; + _uri: string; + + (sid: string, ): WebhookContext; + get(sid: string, ): WebhookContext; + + + + + + + + + /** + * Create a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + create(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise; + + /** + * Create a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + createWithHttpInfo(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams WebhookInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + each(params: WebhookListInstanceEachOptions, callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + /** + * Streams WebhookInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: WebhookListInstanceEachOptions, callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of WebhookInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: WebhookPage) => any): Promise; + /** + * Retrieve a single target page of WebhookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists WebhookInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: WebhookInstance[]) => any): Promise; + list(params: WebhookListInstanceOptions, callback?: (error: Error | null, items: WebhookInstance[]) => any): Promise; + /** + * Lists WebhookInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: WebhookListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of WebhookInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: WebhookPage) => any): Promise; + page(params: WebhookListInstancePageOptions, callback?: (error: Error | null, items: WebhookPage) => any): Promise; + /** + * Retrieve a single page of WebhookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: WebhookListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WebhookListInstance(version: V2, serviceSid: string, channelSid: string): WebhookListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as WebhookListInstance; + + instance.get = function get(sid, ): WebhookContext { + return new WebhookContextImpl(version, serviceSid, channelSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, channelSid, }; + instance._uri = `/Services/${serviceSid}/Channels/${channelSid}/Webhooks`; + + instance.create = function create(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, items: WebhookInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.retryCount"] !== undefined) + data["Configuration.RetryCount"] = params["configuration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["configuration.url"] !== undefined) + data["Configuration.Url"] = params["configuration.url"]; + if (params["configuration.method"] !== undefined) + data["Configuration.Method"] = params["configuration.method"]; + if (params["configuration.filters"] !== undefined) + data["Configuration.Filters"] = serialize.map(params["configuration.filters"], (e: string) => (e)); + if (params["configuration.triggers"] !== undefined) + data["Configuration.Triggers"] = serialize.map(params["configuration.triggers"], (e: string) => (e)); + if (params["configuration.flowSid"] !== undefined) + data["Configuration.FlowSid"] = params["configuration.flowSid"]; + if (params["configuration.retryCount"] !== undefined) + data["Configuration.RetryCount"] = params["configuration.retryCount"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: WebhookListInstancePageOptions | ((error: Error | null, items: WebhookPage) => any), callback?: (error: Error | null, items: WebhookPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new WebhookPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: WebhookPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new WebhookPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: WebhookListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebhookPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebhookPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class WebhookPage extends Page { +/** +* Initialize the WebhookPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: WebhookSolution) { + super(version, response, solution); + } + + /** + * Build an instance of WebhookInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: WebhookResource): WebhookInstance { + + return new WebhookInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.channelSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service/role.ts b/rest/ipMessaging/v2/service/role.ts new file mode 100644 index 000000000..ff559fa6a --- /dev/null +++ b/rest/ipMessaging/v2/service/role.ts @@ -0,0 +1,894 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export type RoleRoleType = 'channel'|'deployment'; + + + + +/** + * Options to pass to update a RoleInstance + */ +export interface RoleContextUpdateOptions { + /** */ + "permission": Array; +} + +/** + * Options to pass to create a RoleInstance + */ +export interface RoleListInstanceCreateOptions { + /** */ + "friendlyName": string; + /** */ + "type": RoleRoleType; + /** */ + "permission": Array; +} + +/** + * Options to pass to each + */ +export interface RoleListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoleInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoleListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoleListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoleContext { + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoleContextSolution { + "serviceSid": string; + "sid": string; +} + +export class RoleContextImpl implements RoleContext { + protected _solution: RoleContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Roles/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: RoleContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RolePayload extends TwilioResponsePayload { + roles: RoleResource[]; +} + +interface RoleResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + type: RoleRoleType; + permissions: Array; + date_created: Date; + date_updated: Date; + url: string; +} + +export class RoleInstance { + protected _solution: RoleContextSolution; + protected _context?: RoleContext; + + constructor(protected _version: V2, payload: RoleResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.permissions = (payload.permissions); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + sid: string; + accountSid: string; + serviceSid: string; + friendlyName: string; + type: RoleRoleType; + permissions: Array; + dateCreated: Date; + dateUpdated: Date; + url: string; + + private get _proxy(): RoleContext { + this._context = this._context || new RoleContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RoleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + fetch(callback?: (error: Error | null, item?: RoleInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RoleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + update(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: RoleInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + type: this.type, + permissions: this.permissions, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoleSolution { + serviceSid: string; +} + +export interface RoleListInstance { + _version: V2; + _solution: RoleSolution; + _uri: string; + + (sid: string, ): RoleContext; + get(sid: string, ): RoleContext; + + + + + + + + + /** + * Create a RoleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance + */ + create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: RoleInstance) => any): Promise; + + /** + * Create a RoleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleInstance with HTTP metadata + */ + createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams RoleInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + each(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoleInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoleListInstanceEachOptions, callback?: (item: RoleInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single target page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists RoleInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + list(params: RoleListInstanceOptions, callback?: (error: Error | null, items: RoleInstance[]) => any): Promise; + /** + * Lists RoleInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: RoleListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of RoleInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RolePage) => any): Promise; + page(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: RolePage) => any): Promise; + /** + * Retrieve a single page of RoleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: RoleListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoleListInstance(version: V2, serviceSid: string): RoleListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RoleListInstance; + + instance.get = function get(sid, ): RoleContext { + return new RoleContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Roles`; + + instance.create = function create(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: RoleInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: RoleListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + if (params["permission"] === null || params["permission"] === undefined) { + throw new Error('Required parameter "params[\'permission\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + + data["Permission"] = serialize.map(params["permission"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new RoleInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RoleListInstancePageOptions | ((error: Error | null, items: RolePage) => any), callback?: (error: Error | null, items: RolePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RolePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RolePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RolePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoleListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RolePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RolePage extends Page { +/** +* Initialize the RolePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: RoleSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoleInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoleResource): RoleInstance { + + return new RoleInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service/user.ts b/rest/ipMessaging/v2/service/user.ts new file mode 100644 index 000000000..409f4391b --- /dev/null +++ b/rest/ipMessaging/v2/service/user.ts @@ -0,0 +1,984 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { UserBindingListInstance } from "./user/userBinding"; +import { UserChannelListInstance } from "./user/userChannel"; + + +export type UserWebhookEnabledType = 'true'|'false'; + + + + +/** + * Options to pass to update a UserInstance + */ +export interface UserContextUpdateOptions { + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserWebhookEnabledType; + /** */ + "roleSid"?: string; + /** */ + "attributes"?: string; + /** */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a UserInstance + */ +export interface UserListInstanceCreateOptions { + /** */ + "identity": string; + /** The X-Twilio-Webhook-Enabled HTTP request header */ + "xTwilioWebhookEnabled"?: UserWebhookEnabledType; + /** */ + "roleSid"?: string; + /** */ + "attributes"?: string; + /** */ + "friendlyName"?: string; +} + +/** + * Options to pass to each + */ +export interface UserListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserContext { + userBindings: UserBindingListInstance; + userChannels: UserChannelListInstance; + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserContextSolution { + "serviceSid": string; + "sid": string; +} + +export class UserContextImpl implements UserContext { + protected _solution: UserContextSolution; + protected _uri: string; + + protected _userBindings?: UserBindingListInstance; + protected _userChannels?: UserChannelListInstance; + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Users/${sid}`; + } + + get userBindings(): UserBindingListInstance { + this._userBindings = this._userBindings || UserBindingListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._userBindings; + } + + get userChannels(): UserChannelListInstance { + this._userChannels = this._userChannels || UserChannelListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._userChannels; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserContextUpdateOptions | ((error: Error | null, item?: UserInstance) => any),callback?: (error: Error | null, item?: UserInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserPayload extends TwilioResponsePayload { + users: UserResource[]; +} + +interface UserResource { + sid: string; + account_sid: string; + service_sid: string; + attributes: string; + friendly_name: string; + role_sid: string; + identity: string; + is_online: boolean; + is_notifiable: boolean; + date_created: Date; + date_updated: Date; + joined_channels_count: number; + links: Record; + url: string; +} + +export class UserInstance { + protected _solution: UserContextSolution; + protected _context?: UserContext; + + constructor(protected _version: V2, payload: UserResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.attributes = (payload.attributes); + this.friendlyName = (payload.friendly_name); + this.roleSid = (payload.role_sid); + this.identity = (payload.identity); + this.isOnline = (payload.is_online); + this.isNotifiable = (payload.is_notifiable); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.joinedChannelsCount = deserialize.integer(payload.joined_channels_count); + this.links = (payload.links); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + sid: string; + accountSid: string; + serviceSid: string; + attributes: string; + friendlyName: string; + roleSid: string; + identity: string; + isOnline: boolean; + isNotifiable: boolean; + dateCreated: Date; + dateUpdated: Date; + joinedChannelsCount: number; + links: Record; + url: string; + + private get _proxy(): UserContext { + this._context = this._context || new UserContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(callback?: (error: Error | null, item?: UserInstance) => any): Promise; + /** + * Update a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the userBindings. + */ + userBindings(): UserBindingListInstance { + return this._proxy.userBindings; + } + + /** + * Access the userChannels. + */ + userChannels(): UserChannelListInstance { + return this._proxy.userChannels; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + attributes: this.attributes, + friendlyName: this.friendlyName, + roleSid: this.roleSid, + identity: this.identity, + isOnline: this.isOnline, + isNotifiable: this.isNotifiable, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + joinedChannelsCount: this.joinedChannelsCount, + links: this.links, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserSolution { + serviceSid: string; +} + +export interface UserListInstance { + _version: V2; + _solution: UserSolution; + _uri: string; + + (sid: string, ): UserContext; + get(sid: string, ): UserContext; + + + + + + + + + /** + * Create a UserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: UserInstance) => any): Promise; + + /** + * Create a UserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams UserInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + each(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single target page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + list(params: UserListInstanceOptions, callback?: (error: Error | null, items: UserInstance[]) => any): Promise; + /** + * Lists UserInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserPage) => any): Promise; + page(params: UserListInstancePageOptions, callback?: (error: Error | null, items: UserPage) => any): Promise; + /** + * Retrieve a single page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserListInstance(version: V2, serviceSid: string): UserListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as UserListInstance; + + instance.get = function get(sid, ): UserContext { + return new UserContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Users`; + + instance.create = function create(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: UserInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: UserListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + if (params["roleSid"] !== undefined) + data["RoleSid"] = params["roleSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioWebhookEnabled"] !== undefined) headers["X-Twilio-Webhook-Enabled"] = params["xTwilioWebhookEnabled"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: UserListInstancePageOptions | ((error: Error | null, items: UserPage) => any), callback?: (error: Error | null, items: UserPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserPage extends Page { +/** +* Initialize the UserPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: UserSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserResource): UserInstance { + + return new UserInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service/user/userBinding.ts b/rest/ipMessaging/v2/service/user/userBinding.ts new file mode 100644 index 000000000..ad9e1250a --- /dev/null +++ b/rest/ipMessaging/v2/service/user/userBinding.ts @@ -0,0 +1,669 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type UserBindingBindingType = 'gcm'|'apn'|'fcm'; + + + + +/** + * Options to pass to each + */ +export interface UserBindingListInstanceEachOptions { + /** */ + "bindingType"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserBindingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserBindingListInstanceOptions { + /** */ + "bindingType"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserBindingListInstancePageOptions { + /** */ + "bindingType"?: Array; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserBindingContext { + + /** + * Remove a UserBindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a UserBindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a UserBindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserBindingInstance + */ + fetch(callback?: (error: Error | null, item?: UserBindingInstance) => any): Promise + + /** + * Fetch a UserBindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserBindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserBindingContextSolution { + "serviceSid": string; + "userSid": string; + "sid": string; +} + +export class UserBindingContextImpl implements UserBindingContext { + protected _solution: UserBindingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, userSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, userSid, sid, }; + this._uri = `/Services/${serviceSid}/Users/${userSid}/Bindings/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserBindingInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserBindingInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.userSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserBindingInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.userSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserBindingPayload extends TwilioResponsePayload { + bindings: UserBindingResource[]; +} + +interface UserBindingResource { + sid: string; + account_sid: string; + service_sid: string; + date_created: Date; + date_updated: Date; + endpoint: string; + identity: string; + user_sid: string; + credential_sid: string; + binding_type: UserBindingBindingType; + message_types: Array; + url: string; +} + +export class UserBindingInstance { + protected _solution: UserBindingContextSolution; + protected _context?: UserBindingContext; + + constructor(protected _version: V2, payload: UserBindingResource, serviceSid: string, userSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.endpoint = (payload.endpoint); + this.identity = (payload.identity); + this.userSid = (payload.user_sid); + this.credentialSid = (payload.credential_sid); + this.bindingType = payload.binding_type; + this.messageTypes = (payload.message_types); + this.url = (payload.url); + + this._solution = { serviceSid, userSid, sid: sid, }; + } + + sid: string; + accountSid: string; + serviceSid: string; + dateCreated: Date; + dateUpdated: Date; + endpoint: string; + identity: string; + userSid: string; + credentialSid: string; + bindingType: UserBindingBindingType; + messageTypes: Array; + url: string; + + private get _proxy(): UserBindingContext { + this._context = this._context || new UserBindingContextImpl(this._version, this._solution.serviceSid, this._solution.userSid, this._solution.sid); + return this._context; + } + + /** + * Remove a UserBindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserBindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserBindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserBindingInstance + */ + fetch(callback?: (error: Error | null, item?: UserBindingInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserBindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserBindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + endpoint: this.endpoint, + identity: this.identity, + userSid: this.userSid, + credentialSid: this.credentialSid, + bindingType: this.bindingType, + messageTypes: this.messageTypes, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserBindingSolution { + serviceSid: string; + userSid: string; +} + +export interface UserBindingListInstance { + _version: V2; + _solution: UserBindingSolution; + _uri: string; + + (sid: string, ): UserBindingContext; + get(sid: string, ): UserBindingContext; + + + + + + + + /** + * Streams UserBindingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserBindingInstance, done: (err?: Error) => void) => void): void; + each(params: UserBindingListInstanceEachOptions, callback?: (item: UserBindingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserBindingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserBindingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserBindingListInstanceEachOptions, callback?: (item: UserBindingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserBindingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserBindingPage) => any): Promise; + /** + * Retrieve a single target page of UserBindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserBindingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserBindingInstance[]) => any): Promise; + list(params: UserBindingListInstanceOptions, callback?: (error: Error | null, items: UserBindingInstance[]) => any): Promise; + /** + * Lists UserBindingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserBindingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserBindingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserBindingPage) => any): Promise; + page(params: UserBindingListInstancePageOptions, callback?: (error: Error | null, items: UserBindingPage) => any): Promise; + /** + * Retrieve a single page of UserBindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserBindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserBindingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserBindingListInstance(version: V2, serviceSid: string, userSid: string): UserBindingListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as UserBindingListInstance; + + instance.get = function get(sid, ): UserBindingContext { + return new UserBindingContextImpl(version, serviceSid, userSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, userSid, }; + instance._uri = `/Services/${serviceSid}/Users/${userSid}/Bindings`; + + instance.page = function page(params?: UserBindingListInstancePageOptions | ((error: Error | null, items: UserBindingPage) => any), callback?: (error: Error | null, items: UserBindingPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["bindingType"] !== undefined) + data["BindingType"] = serialize.map(params["bindingType"], (e: UserBindingBindingType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserBindingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserBindingPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserBindingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserBindingListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["bindingType"] !== undefined) + data["BindingType"] = serialize.map(params["bindingType"], (e: UserBindingBindingType) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserBindingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserBindingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserBindingPage extends Page { +/** +* Initialize the UserBindingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: UserBindingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserBindingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserBindingResource): UserBindingInstance { + + return new UserBindingInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.userSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/ipMessaging/v2/service/user/userChannel.ts b/rest/ipMessaging/v2/service/user/userChannel.ts new file mode 100644 index 000000000..bfd172e5e --- /dev/null +++ b/rest/ipMessaging/v2/service/user/userChannel.ts @@ -0,0 +1,830 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Ip_messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type UserChannelChannelStatus = 'joined'|'invited'|'not_participating'; + +export type UserChannelNotificationLevel = 'default'|'muted'; + + + + +/** + * Options to pass to update a UserChannelInstance + */ +export interface UserChannelContextUpdateOptions { + /** */ + "notificationLevel"?: UserChannelNotificationLevel; + /** */ + "lastConsumedMessageIndex"?: number; + /** */ + "lastConsumptionTimestamp"?: Date; +} + +/** + * Options to pass to each + */ +export interface UserChannelListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserChannelListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserChannelListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserChannelContext { + + /** + * Remove a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + fetch(callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise + + /** + * Fetch a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + update(callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise; + /** + * Update a UserChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + update(params: UserChannelContextUpdateOptions, callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise; + + /** + * Update a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserChannelContextSolution { + "serviceSid": string; + "userSid": string; + "channelSid": string; +} + +export class UserChannelContextImpl implements UserChannelContext { + protected _solution: UserChannelContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, userSid: string, channelSid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + if (!isValidPathParam(channelSid)) { + throw new Error('Parameter \'channelSid\' is not valid.'); + } + + this._solution = { serviceSid, userSid, channelSid, }; + this._uri = `/Services/${serviceSid}/Users/${userSid}/Channels/${channelSid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.userSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.userSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: UserChannelContextUpdateOptions | ((error: Error | null, item?: UserChannelInstance) => any),callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["notificationLevel"] !== undefined) + data["NotificationLevel"] = params["notificationLevel"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserChannelInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.userSid, instance._solution.channelSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: UserChannelContextUpdateOptions | ((error: Error | null, item?: ApiResponse) => any),callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["notificationLevel"] !== undefined) + data["NotificationLevel"] = params["notificationLevel"]; + if (params["lastConsumedMessageIndex"] !== undefined) + data["LastConsumedMessageIndex"] = params["lastConsumedMessageIndex"]; + if (params["lastConsumptionTimestamp"] !== undefined) + data["LastConsumptionTimestamp"] = serialize.iso8601DateTime(params["lastConsumptionTimestamp"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new UserChannelInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.userSid, instance._solution.channelSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserChannelPayload extends TwilioResponsePayload { + channels: UserChannelResource[]; +} + +interface UserChannelResource { + account_sid: string; + service_sid: string; + channel_sid: string; + user_sid: string; + member_sid: string; + status: UserChannelChannelStatus; + last_consumed_message_index: number; + unread_messages_count: number; + links: Record; + url: string; + notification_level: UserChannelNotificationLevel; +} + +export class UserChannelInstance { + protected _solution: UserChannelContextSolution; + protected _context?: UserChannelContext; + + constructor(protected _version: V2, payload: UserChannelResource, serviceSid: string, userSid: string, channelSid?: string) { + + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.channelSid = (payload.channel_sid); + this.userSid = (payload.user_sid); + this.memberSid = (payload.member_sid); + this.status = payload.status; + this.lastConsumedMessageIndex = deserialize.integer(payload.last_consumed_message_index); + this.unreadMessagesCount = deserialize.integer(payload.unread_messages_count); + this.links = (payload.links); + this.url = (payload.url); + this.notificationLevel = payload.notification_level; + + this._solution = { serviceSid, userSid, channelSid: channelSid, }; + } + + accountSid: string; + serviceSid: string; + channelSid: string; + userSid: string; + memberSid: string; + status: UserChannelChannelStatus; + lastConsumedMessageIndex: number; + unreadMessagesCount: number; + links: Record; + url: string; + notificationLevel: UserChannelNotificationLevel; + + private get _proxy(): UserChannelContext { + this._context = this._context || new UserChannelContextImpl(this._version, this._solution.serviceSid, this._solution.userSid, this._solution.channelSid); + return this._context; + } + + /** + * Remove a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + fetch(callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a UserChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + update(callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise; + /** + * Update a UserChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance + */ + update(params: UserChannelContextUpdateOptions, callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: UserChannelInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a UserChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: UserChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + serviceSid: this.serviceSid, + channelSid: this.channelSid, + userSid: this.userSid, + memberSid: this.memberSid, + status: this.status, + lastConsumedMessageIndex: this.lastConsumedMessageIndex, + unreadMessagesCount: this.unreadMessagesCount, + links: this.links, + url: this.url, + notificationLevel: this.notificationLevel, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserChannelSolution { + serviceSid: string; + userSid: string; +} + +export interface UserChannelListInstance { + _version: V2; + _solution: UserChannelSolution; + _uri: string; + + (channelSid: string, ): UserChannelContext; + get(channelSid: string, ): UserChannelContext; + + + + + + + + + + /** + * Streams UserChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + each(params: UserChannelListInstanceEachOptions, callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserChannelListInstanceEachOptions, callback?: (item: UserChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + /** + * Retrieve a single target page of UserChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists UserChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserChannelInstance[]) => any): Promise; + list(params: UserChannelListInstanceOptions, callback?: (error: Error | null, items: UserChannelInstance[]) => any): Promise; + /** + * Lists UserChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: UserChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of UserChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + page(params: UserChannelListInstancePageOptions, callback?: (error: Error | null, items: UserChannelPage) => any): Promise; + /** + * Retrieve a single page of UserChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: UserChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserChannelListInstance(version: V2, serviceSid: string, userSid: string): UserChannelListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + const instance = ((channelSid, ) => instance.get(channelSid, )) as UserChannelListInstance; + + instance.get = function get(channelSid, ): UserChannelContext { + return new UserChannelContextImpl(version, serviceSid, userSid, channelSid); + } + + instance._version = version; + instance._solution = { serviceSid, userSid, }; + instance._uri = `/Services/${serviceSid}/Users/${userSid}/Channels`; + + instance.page = function page(params?: UserChannelListInstancePageOptions | ((error: Error | null, items: UserChannelPage) => any), callback?: (error: Error | null, items: UserChannelPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserChannelPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserChannelPage extends Page { +/** +* Initialize the UserChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response, solution: UserChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserChannelResource): UserChannelInstance { + + return new UserChannelInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.userSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/knowledge/V1.ts b/rest/knowledge/V1.ts new file mode 100644 index 000000000..fe270efae --- /dev/null +++ b/rest/knowledge/V1.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Knowledge + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import KnowledgeBase from "../KnowledgeBase"; +import Version from "../../base/Version"; +import { KnowledgeListInstance } from "./v1/knowledge"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Knowledge + * + * @param domain - The Twilio (Twilio.Knowledge) domain + */ + constructor(domain: KnowledgeBase) { + super(domain, "v1"); + } + + /** knowledge - { Twilio.Knowledge.V1.KnowledgeListInstance } resource */ + protected _knowledge?: KnowledgeListInstance; + + /** Getter for knowledge resource */ + get knowledge(): KnowledgeListInstance { + this._knowledge = this._knowledge || KnowledgeListInstance(this); + return this._knowledge; + } + +} diff --git a/rest/knowledge/V2.ts b/rest/knowledge/V2.ts new file mode 100644 index 000000000..8f8a79002 --- /dev/null +++ b/rest/knowledge/V2.ts @@ -0,0 +1,73 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Knowledge API + * APIs for managing knowledge bases and knowledge content for AI-powered applications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import KnowledgeBase from "../KnowledgeBase"; +import Version from "../../base/Version"; +import { ChunkListInstance } from "./v2/chunk"; +import { KnowledgeListInstance, KnowledgeContext } from "./v2/knowledge"; +import { KnowledgeBasisListInstance } from "./v2/knowledgeBasis"; +import { OperationListInstance } from "./v2/operation"; +import { SearchListInstance } from "./v2/search"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Knowledge + * + * @param domain - The Twilio (Twilio.Knowledge) domain + */ + constructor(domain: KnowledgeBase) { + super(domain, "v2"); + } + + /** knowledgeBases - { Twilio.Knowledge.V2.KnowledgeBasisListInstance } resource */ + protected _knowledgeBases?: KnowledgeBasisListInstance; + /** operations - { Twilio.Knowledge.V2.OperationListInstance } resource */ + protected _operations?: OperationListInstance; + + /** Accessor for chunks resource */ + chunks(kbId: string, knowledgeId: string): ChunkListInstance { + return ChunkListInstance(this, kbId, knowledgeId); + } + + /** Accessor for knowledge resource - list operations */ + knowledge(kbId: string): KnowledgeListInstance; + /** Accessor for knowledge resource - instance operations */ + knowledge(kbId: string, knowledgeId: string): KnowledgeContext; + /** Implementation */ + knowledge(kbId: string, knowledgeId?: string): KnowledgeListInstance | KnowledgeContext { + const listInstance = KnowledgeListInstance(this, kbId); + if (knowledgeId !== undefined) { + return listInstance.get(knowledgeId); + } + return listInstance; + } + + /** Getter for knowledgeBases resource */ + get knowledgeBases(): KnowledgeBasisListInstance { + this._knowledgeBases = this._knowledgeBases || KnowledgeBasisListInstance(this); + return this._knowledgeBases; + } + + /** Getter for operations resource */ + get operations(): OperationListInstance { + this._operations = this._operations || OperationListInstance(this); + return this._operations; + } + + /** Accessor for search resource */ + search(kbId: string): SearchListInstance { + return SearchListInstance(this, kbId); + } + +} diff --git a/rest/knowledge/v1/knowledge.ts b/rest/knowledge/v1/knowledge.ts new file mode 100644 index 000000000..60937a93f --- /dev/null +++ b/rest/knowledge/v1/knowledge.ts @@ -0,0 +1,1059 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Knowledge + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ChunkListInstance } from "./knowledge/chunk"; +import { KnowledgeStatusListInstance } from "./knowledge/knowledgeStatus"; + + +export class KnowledgeV1ServiceCreateKnowledgeRequest { + /** + * The description of the knowledge source. + */ + "description"?: string; + /** + * The details of the knowledge source based on the type. + */ + "knowledgeSourceDetails"?: Record; + /** + * The name of the tool. + */ + "name": string; + "policy"?: KnowledgeV1ServiceCreatePolicyRequest; + /** + * The type of the knowledge source. + */ + "type": string; + /** + * The embedding model to be used for the knowledge source. It\'s required for \'Database\' type but disallowed for other types. + */ + "embeddingModel"?: string; + + constructor(payload) { + this.description = payload["description"]; + this.knowledgeSourceDetails = payload["knowledge_source_details"]; + this.name = payload["name"]; + this.policy = payload["policy"]; + this.type = payload["type"]; + this.embeddingModel = payload["embedding_model"]; + } +} + + +export class KnowledgeV1ServiceCreatePolicyRequest { + /** + * The description of the policy. + */ + "description"?: string; + /** + * The Policy ID. + */ + "id"?: string; + /** + * The name of the policy. + */ + "name"?: string; + "policyDetails": any | null; + /** + * The description of the policy. + */ + "type"?: string; + + constructor(payload) { + this.description = payload["description"]; + this.id = payload["id"]; + this.name = payload["name"]; + this.policyDetails = payload["policy_details"]; + this.type = payload["type"]; + } +} + + +export class KnowledgeV1ServiceUpdateKnowledgeRequest { + /** + * The description of the knowledge source. + */ + "description"?: string; + /** + * The details of the knowledge source based on the type. + */ + "knowledgeSourceDetails"?: Record; + /** + * The name of the knowledge source. + */ + "name"?: string; + "policy"?: KnowledgeV1ServiceCreatePolicyRequest; + /** + * The description of the knowledge source. + */ + "type"?: string; + /** + * The embedding model to be used for the knowledge source. It\'s only applicable to \'Database\' type. + */ + "embeddingModel"?: string; + + constructor(payload) { + this.description = payload["description"]; + this.knowledgeSourceDetails = payload["knowledge_source_details"]; + this.name = payload["name"]; + this.policy = payload["policy"]; + this.type = payload["type"]; + this.embeddingModel = payload["embedding_model"]; + } +} + + + + + +/** + * Options to pass to update a KnowledgeInstance + */ +export interface KnowledgeContextUpdateOptions { + /** */ + "knowledgeV1ServiceUpdateKnowledgeRequest"?: KnowledgeV1ServiceUpdateKnowledgeRequest; +} + +/** + * Options to pass to create a KnowledgeInstance + */ +export interface KnowledgeListInstanceCreateOptions { + /** */ + "knowledgeV1ServiceCreateKnowledgeRequest": KnowledgeV1ServiceCreateKnowledgeRequest; +} + +/** + * Options to pass to each + */ +export interface KnowledgeListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Json array of tag and value pairs for tag filtering. */ + "tags"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface KnowledgeListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Json array of tag and value pairs for tag filtering. */ + "tags"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface KnowledgeListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Json array of tag and value pairs for tag filtering. */ + "tags"?: string; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface KnowledgeContext { + chunks: ChunkListInstance; + knowledgeStatus: KnowledgeStatusListInstance; + + /** + * Remove a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + /** + * Remove a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Fetch a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise + + /** + * Fetch a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Update a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise; + /** + * Update a KnowledgeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(params: KnowledgeV1ServiceUpdateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise; + + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(params: KnowledgeV1ServiceUpdateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface KnowledgeContextSolution { + "id": string; +} + +export class KnowledgeContextImpl implements KnowledgeContext { + protected _solution: KnowledgeContextSolution; + protected _uri: string; + + protected _chunks?: ChunkListInstance; + protected _knowledgeStatus?: KnowledgeStatusListInstance; + + constructor(protected _version: V1, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/Knowledge/${id}`; + } + + get chunks(): ChunkListInstance { + this._chunks = this._chunks || ChunkListInstance(this._version, this._solution.id); + return this._chunks; + } + + get knowledgeStatus(): KnowledgeStatusListInstance { + this._knowledgeStatus = this._knowledgeStatus || KnowledgeStatusListInstance(this._version, this._solution.id); + return this._knowledgeStatus; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new KnowledgeInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: KnowledgeV1ServiceUpdateKnowledgeRequest | ((error: Error | null, item?: KnowledgeInstance) => any), headers?: any,callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {} as Partial as KnowledgeV1ServiceUpdateKnowledgeRequest; + } else { + params = params || {} as Partial as KnowledgeV1ServiceUpdateKnowledgeRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: KnowledgeV1ServiceUpdateKnowledgeRequest | ((error: Error | null, item?: ApiResponse) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {} as Partial as KnowledgeV1ServiceUpdateKnowledgeRequest; + } else { + params = params || {} as Partial as KnowledgeV1ServiceUpdateKnowledgeRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new KnowledgeInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface KnowledgePayload extends TwilioResponsePayload { + knowledge: KnowledgeResource[]; +} + +interface KnowledgeResource { + description: string; + id: string; + account_sid: string; + knowledge_source_details: Record; + name: string; + status: string; + type: string; + url: string; + embedding_model: string; + date_created: Date; + date_updated: Date; +} + +export class KnowledgeInstance { + protected _solution: KnowledgeContextSolution; + protected _context?: KnowledgeContext; + + constructor(protected _version: V1, payload: KnowledgeResource, id?: string) { + + this.description = (payload.description); + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.knowledgeSourceDetails = (payload.knowledge_source_details); + this.name = (payload.name); + this.status = (payload.status); + this.type = (payload.type); + this.url = (payload.url); + this.embeddingModel = (payload.embedding_model); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { id: id, }; + } + + /** + * The type of knowledge source. + */ + description: string; + /** + * The description of knowledge. + */ + id: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + */ + accountSid: string; + /** + * The details of the knowledge source based on the type. + */ + knowledgeSourceDetails: Record; + /** + * The name of the knowledge source. + */ + name: string; + /** + * The status of processing the knowledge source (\'QUEUED\', \'PROCESSING\', \'COMPLETED\', \'FAILED\') + */ + status: string; + /** + * The type of knowledge source (\'Web\', \'Database\', \'Text\', \'File\') + */ + type: string; + /** + * The url of the knowledge resource. + */ + url: string; + /** + * The embedding model to be used for the knowledge source. + */ + embeddingModel: string; + /** + * The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + private get _proxy(): KnowledgeContext { + this._context = this._context || new KnowledgeContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Remove a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise + + { + return this._proxy.remove(callback); + } + + /** + * Remove a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise; + /** + * Update a KnowledgeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(params: KnowledgeV1ServiceUpdateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise; + + update(params?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise + { + return this._proxy.update(params, callback); + } + + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(params: KnowledgeV1ServiceUpdateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the chunks. + */ + chunks(): ChunkListInstance { + return this._proxy.chunks; + } + + /** + * Access the knowledgeStatus. + */ + knowledgeStatus(): KnowledgeStatusListInstance { + return this._proxy.knowledgeStatus; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + description: this.description, + id: this.id, + accountSid: this.accountSid, + knowledgeSourceDetails: this.knowledgeSourceDetails, + name: this.name, + status: this.status, + type: this.type, + url: this.url, + embeddingModel: this.embeddingModel, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface KnowledgeSolution { +} + +export interface KnowledgeListInstance { + _version: V1; + _solution: KnowledgeSolution; + _uri: string; + + (id: string, ): KnowledgeContext; + get(id: string, ): KnowledgeContext; + + + + + + + + + /** + * Create a KnowledgeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + create(params: KnowledgeV1ServiceCreateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise; + + /** + * Create a KnowledgeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + createWithHttpInfo(params: KnowledgeV1ServiceCreateKnowledgeRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse) => any): Promise>; + + + + + /** + * Streams KnowledgeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + each(params: KnowledgeListInstanceEachOptions, callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams KnowledgeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: KnowledgeListInstanceEachOptions, callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of KnowledgeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: KnowledgePage) => any): Promise; + /** + * Retrieve a single target page of KnowledgeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists KnowledgeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: KnowledgeInstance[]) => any): Promise; + list(params: KnowledgeListInstanceOptions, callback?: (error: Error | null, items: KnowledgeInstance[]) => any): Promise; + /** + * Lists KnowledgeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: KnowledgeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of KnowledgeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: KnowledgePage) => any): Promise; + page(params: KnowledgeListInstancePageOptions, callback?: (error: Error | null, items: KnowledgePage) => any): Promise; + /** + * Retrieve a single page of KnowledgeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: KnowledgeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function KnowledgeListInstance(version: V1): KnowledgeListInstance { + const instance = ((id, ) => instance.get(id, )) as KnowledgeListInstance; + + instance.get = function get(id, ): KnowledgeContext { + return new KnowledgeContextImpl(version, id); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Knowledge`; + + instance.create = function create(params: KnowledgeV1ServiceCreateKnowledgeRequest, headers?: any, callback?: (error: Error | null, items: KnowledgeInstance) => any): Promise { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: KnowledgeV1ServiceCreateKnowledgeRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse => ({ + ...response, + body: new KnowledgeInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: KnowledgeListInstancePageOptions | ((error: Error | null, items: KnowledgePage) => any), callback?: (error: Error | null, items: KnowledgePage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["tags"] !== undefined) + data["Tags"] = params["tags"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new KnowledgePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: KnowledgePage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new KnowledgePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: KnowledgeListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["tags"] !== undefined) + data["Tags"] = params["tags"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new KnowledgePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new KnowledgePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class KnowledgePage extends Page { +/** +* Initialize the KnowledgePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: KnowledgeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of KnowledgeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: KnowledgeResource): KnowledgeInstance { + + return new KnowledgeInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/knowledge/v1/knowledge/chunk.ts b/rest/knowledge/v1/knowledge/chunk.ts new file mode 100644 index 000000000..e22c25277 --- /dev/null +++ b/rest/knowledge/v1/knowledge/chunk.ts @@ -0,0 +1,412 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Knowledge + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface ChunkListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChunkInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChunkListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChunkListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface ChunkSolution { + id: string; +} + +export interface ChunkListInstance { + _version: V1; + _solution: ChunkSolution; + _uri: string; + + + + + /** + * Streams ChunkInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + each(params: ChunkListInstanceEachOptions, callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChunkInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ChunkListInstanceEachOptions, callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChunkInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChunkPage) => any): Promise; + /** + * Retrieve a single target page of ChunkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ChunkInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ChunkInstance[]) => any): Promise; + list(params: ChunkListInstanceOptions, callback?: (error: Error | null, items: ChunkInstance[]) => any): Promise; + /** + * Lists ChunkInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ChunkListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ChunkInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ChunkPage) => any): Promise; + page(params: ChunkListInstancePageOptions, callback?: (error: Error | null, items: ChunkPage) => any): Promise; + /** + * Retrieve a single page of ChunkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ChunkListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChunkListInstance(version: V1, id: string): ChunkListInstance { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + const instance = {} as ChunkListInstance; + + instance._version = version; + instance._solution = { id, }; + instance._uri = `/Knowledge/${id}/Chunks`; + + instance.page = function page(params?: ChunkListInstancePageOptions | ((error: Error | null, items: ChunkPage) => any), callback?: (error: Error | null, items: ChunkPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChunkPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChunkPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChunkPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ChunkListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChunkPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChunkPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ChunkPayload extends TwilioResponsePayload { + chunks: ChunkResource[]; +} + +interface ChunkResource { + account_sid: string; + content: string; + metadata: Record; + date_created: Date; + date_updated: Date; +} + +export class ChunkInstance { + + constructor(protected _version: V1, payload: ChunkResource, id: string) { + + this.accountSid = (payload.account_sid); + this.content = (payload.content); + this.metadata = (payload.metadata); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + */ + accountSid: string; + /** + * The chunk content. + */ + content: string; + /** + * The metadata of the chunk. + */ + metadata: Record; + /** + * The date and time in GMT when the Chunk was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Chunk was updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + content: this.content, + metadata: this.metadata, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class ChunkPage extends Page { +/** +* Initialize the ChunkPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response, solution: ChunkSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ChunkInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChunkResource): ChunkInstance { + + return new ChunkInstance( + this._version, + payload, + this._solution.id, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/knowledge/v1/knowledge/knowledgeStatus.ts b/rest/knowledge/v1/knowledge/knowledgeStatus.ts new file mode 100644 index 000000000..76e2172ef --- /dev/null +++ b/rest/knowledge/v1/knowledge/knowledgeStatus.ts @@ -0,0 +1,260 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Knowledge + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +export interface KnowledgeStatusContext { + + /** + * Fetch a KnowledgeStatusInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeStatusInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeStatusInstance) => any): Promise + + /** + * Fetch a KnowledgeStatusInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeStatusInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface KnowledgeStatusContextSolution { + "id": string; +} + +export class KnowledgeStatusContextImpl implements KnowledgeStatusContext { + protected _solution: KnowledgeStatusContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, id: string) { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { id, }; + this._uri = `/Knowledge/${id}/Status`; + } + + fetch(callback?: (error: Error | null, item?: KnowledgeStatusInstance) => any): Promise { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeStatusInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse => ({ + ...response, + body: new KnowledgeStatusInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface KnowledgeStatusPayload extends KnowledgeStatusResource {} + +interface KnowledgeStatusResource { + account_sid: string; + status: string; + last_status: string; + date_updated: Date; +} + +export class KnowledgeStatusInstance { + protected _solution: KnowledgeStatusContextSolution; + protected _context?: KnowledgeStatusContext; + + constructor(protected _version: V1, payload: KnowledgeStatusResource, id: string) { + + this.accountSid = (payload.account_sid); + this.status = (payload.status); + this.lastStatus = (payload.last_status); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { id, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + */ + accountSid: string; + /** + * The status of processing the knowledge source (\'QUEUED\', \'PROCESSING\', \'COMPLETED\', \'FAILED\') + */ + status: string; + /** + * The last status of processing the knowledge source (\'QUEUED\', \'PROCESSING\', \'COMPLETED\', \'FAILED\') + */ + lastStatus: string; + /** + * The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + private get _proxy(): KnowledgeStatusContext { + this._context = this._context || new KnowledgeStatusContextImpl(this._version, this._solution.id); + return this._context; + } + + /** + * Fetch a KnowledgeStatusInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeStatusInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeStatusInstance) => any): Promise + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a KnowledgeStatusInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeStatusInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse) => any): Promise> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + status: this.status, + lastStatus: this.lastStatus, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface KnowledgeStatusSolution { + id: string; +} + +export interface KnowledgeStatusListInstance { + _version: V1; + _solution: KnowledgeStatusSolution; + _uri: string; + + (): KnowledgeStatusContext; + get(): KnowledgeStatusContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function KnowledgeStatusListInstance(version: V1, id: string): KnowledgeStatusListInstance { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + const instance = (() => instance.get()) as KnowledgeStatusListInstance; + + instance.get = function get(): KnowledgeStatusContext { + return new KnowledgeStatusContextImpl(version, id); + } + + instance._version = version; + instance._solution = { id, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/knowledge/v2/chunk.ts b/rest/knowledge/v2/chunk.ts new file mode 100644 index 000000000..9f0132b6a --- /dev/null +++ b/rest/knowledge/v2/chunk.ts @@ -0,0 +1,428 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Knowledge API + * APIs for managing knowledge bases and knowledge content for AI-powered applications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface ChunkListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** The page token. This is provided by the API. */ + "pageToken"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChunkInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChunkListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** The page token. This is provided by the API. */ + "pageToken"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChunkListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** The page token. This is provided by the API. */ + "pageToken"?: string; +} + + + +export interface ChunkSolution { + kbId: string; + knowledgeId: string; +} + +export interface ChunkListInstance { + _version: V2; + _solution: ChunkSolution; + _uri: string; + + + + + /** + * Streams ChunkInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + each(params: ChunkListInstanceEachOptions, callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChunkInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ChunkListInstanceEachOptions, callback?: (item: ChunkInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChunkInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChunkPage) => any): Promise; + /** + * Retrieve a single target page of ChunkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Lists ChunkInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ChunkInstance[]) => any): Promise; + list(params: ChunkListInstanceOptions, callback?: (error: Error | null, items: ChunkInstance[]) => any): Promise; + /** + * Lists ChunkInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + listWithHttpInfo(params: ChunkListInstanceOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + /** + * Retrieve a single page of ChunkInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ChunkPage) => any): Promise; + page(params: ChunkListInstancePageOptions, callback?: (error: Error | null, items: ChunkPage) => any): Promise; + /** + * Retrieve a single page of ChunkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChunkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + pageWithHttpInfo(params: ChunkListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse) => any): Promise>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChunkListInstance(version: V2, kbId: string, knowledgeId: string): ChunkListInstance { + if (!isValidPathParam(kbId)) { + throw new Error('Parameter \'kbId\' is not valid.'); + } + + if (!isValidPathParam(knowledgeId)) { + throw new Error('Parameter \'knowledgeId\' is not valid.'); + } + + const instance = {} as ChunkListInstance; + + instance._version = version; + instance._solution = { kbId, knowledgeId, }; + instance._uri = `/KnowledgeBases/${kbId}/Knowledge/${knowledgeId}/Chunks`; + + instance.page = function page(params?: ChunkListInstancePageOptions | ((error: Error | null, items: ChunkPage) => any), callback?: (error: Error | null, items: ChunkPage) => any): Promise { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChunkPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChunkPage) => any): Promise { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChunkPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ChunkListInstancePageOptions | ((error: Error | null, items: ApiResponse) => any), callback?: (error: Error | null, items: ApiResponse) => any): Promise> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChunkPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse) => any): Promise> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChunkPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ChunkPayload extends TokenPaginationPayload { + chunks: ChunkResource[]; +} + +interface ChunkResource { + content: string; + createdAt: Date; + chunkIndex: number; + documentTitle: string; + documentUrl: string; + documentNumber: number; +} + +export class ChunkInstance { + + constructor(protected _version: V2, _payload: ChunkResource, kbId: string, knowledgeId: string) { + const payload = _payload; + this.content = (payload.content); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.chunkIndex = deserialize.integer(payload.chunkIndex); + this.documentTitle = (payload.documentTitle); + this.documentUrl = (payload.documentUrl); + this.documentNumber = deserialize.integer(payload.documentNumber); + + } + + /** + * The chunk content. + */ + content: string; + /** + * The date and time in GMT when the Chunk was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + createdAt: Date; + /** + * 0-based position of this chunk within its source document for a single ingestion run. + */ + chunkIndex: number; + /** + * Human-readable title of the source document. Web: HTML from the crawled page. File: filename from Unstructured metadata. Text: knowledge name from the knowledge source. + */ + documentTitle: string; + /** + * Specific page URL this chunk was crawled from. Web sources only; null for File and Text sources. + */ + documentUrl: string; + /** + * Physical page number (1-based). PDF sources only; omitted for all other source types. + */ + documentNumber: number; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + content: this.content, + createdAt: this.createdAt, + chunkIndex: this.chunkIndex, + documentTitle: this.documentTitle, + documentUrl: this.documentUrl, + documentNumber: this.documentNumber, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class ChunkPage extends TokenPage<V2, ChunkPayload, ChunkResource, ChunkInstance> { +/** +* Initialize the ChunkPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, uri: string, params: any, solution: ChunkSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of ChunkInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChunkResource): ChunkInstance { + + return new ChunkInstance( + this._version, + payload, + this._solution.kbId, + this._solution.knowledgeId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/knowledge/v2/knowledge.ts b/rest/knowledge/v2/knowledge.ts new file mode 100644 index 000000000..2e4d3d686 --- /dev/null +++ b/rest/knowledge/v2/knowledge.ts @@ -0,0 +1,1005 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Knowledge API + * APIs for managing knowledge bases and knowledge content for AI-powered applications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Core properties for knowledge source that can be set at creation time. Regularly update and organize your Knowledge sources to ensure it contains the most accurate and relevant information. This includes adding new entries, updating existing ones, and removing outdated content. + */ +export class KnowledgeCore { + /** + * The name of the knowledge source. + */ + "name": string; + /** + * A detailed description of the knowledge source and when to use it. This helps provide context about the content and its intended purpose. + */ + "description"?: string; + "source"?: KnowledgeSourceTypes; + + constructor(payload) { + this.name = payload["name"]; + this.description = payload["description"]; + this.source = payload["source"]; + } +} + + +/** + * Details specific to the knowledge source type. Each knowledge source type has its own set of configuration parameters and source specific properties. + */ +export class KnowledgeSourceTypes { + /** + * Raw text knowledge sources + */ + "type": string; + /** + * The raw text content to be processed + */ + "content": string; + /** + * The URL to crawl for web content + */ + "url": string; + /** + * The maximum depth to crawl from the source URL + */ + "crawlDepth"?: number; + /** + * Frequency of re-crawling the website for updated content + */ + "crawlPeriod"?: string; + /** + * Name of the file to be uploaded + */ + "fileName": string; + /** + * Expected size of the file in bytes + */ + "fileSize": number; + "mimeType": SupportedFileMimeType; + /** + * Presigned S3 URL for file upload (when status is SCHEDULED). Use PUT method to upload the file to this URL when status is SCHEDULED. + */ + "importUrl"?: string; + /** + * Expiration time of the presigned upload URL in ISO 8601 format (only present when status is SCHEDULED) + */ + "uploadExpiration"?: Date; + + constructor(payload) { + this.type = payload["type"]; + this.content = payload["content"]; + this.url = payload["url"]; + this.crawlDepth = payload["crawlDepth"]; + this.crawlPeriod = payload["crawlPeriod"]; + this.fileName = payload["fileName"]; + this.fileSize = payload["fileSize"]; + this.mimeType = payload["mimeType"]; + this.importUrl = payload["importUrl"]; + this.uploadExpiration = payload["uploadExpiration"]; + } +} + + +/** + * Supported MIME types for knowledge file imports. Maximum file size for any file is 16MB (16 * 1024 * 1024 bytes). Extensions → MIME: .csv → text/csv .md → text/markdown .pdf → application/pdf .tsv → text/tab-separated-values .txt → text/plain + */ +export type SupportedFileMimeType = 'text/csv'|'text/markdown'|'application/pdf'|'text/tab-separated-values'|'text/plain'; + + + + +/** + * Options to pass to update a KnowledgeInstance + */ +export interface KnowledgeContextUpdateOptions { + /** When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. */ + "refresh"?: boolean; + /** */ + "knowledgeCore"?: KnowledgeCore; +} + +/** + * Options to pass to create a KnowledgeInstance + */ +export interface KnowledgeListInstanceCreateOptions { + /** */ + "knowledgeCore": KnowledgeCore; +} + +/** + * Options to pass to each + */ +export interface KnowledgeListInstanceEachOptions { + /** The page index. This value is simply for client state. */ + "page"?: number; + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface KnowledgeListInstanceOptions { + /** The page index. This value is simply for client state. */ + "page"?: number; + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface KnowledgeListInstancePageOptions { + /** The page index. This value is simply for client state. */ + "page"?: number; + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; +} + + +export interface KnowledgeContext { + + /** + * Remove a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise<KnowledgeInstance> + + /** + * Fetch a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>> + + /** + * Update a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise<KnowledgeInstance>; + /** + * Update a KnowledgeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(params: KnowledgeCore, headers?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise<KnowledgeInstance>; + + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>>; + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(params: KnowledgeCore, headers?: any, callback?: (error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface KnowledgeContextSolution { + "kbId": string; + "knowledgeId": string; +} + +export class KnowledgeContextImpl implements KnowledgeContext { + protected _solution: KnowledgeContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, kbId: string, knowledgeId: string) { + if (!isValidPathParam(kbId)) { + throw new Error('Parameter \'kbId\' is not valid.'); + } + + if (!isValidPathParam(knowledgeId)) { + throw new Error('Parameter \'knowledgeId\' is not valid.'); + } + + this._solution = { kbId, knowledgeId, }; + this._uri = `/KnowledgeBases/${kbId}/Knowledge/${knowledgeId}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise<KnowledgeInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeInstance(operationVersion, payload, instance._solution.kbId, instance._solution.knowledgeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<KnowledgeResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<KnowledgeInstance> => ({ + ...response, + body: new KnowledgeInstance(operationVersion, response.body, instance._solution.kbId, instance._solution.knowledgeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: KnowledgeCore | ((error: Error | null, item?: KnowledgeInstance) => any), headers?: any,callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise<KnowledgeInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<KnowledgeCore> as KnowledgeCore; + } else { + params = params || {} as Partial<KnowledgeCore> as KnowledgeCore; + } + + let data: any = {}; + + if (params["refresh"] !== undefined) + data["refresh"] = serialize.bool(params["refresh"]); + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeInstance(operationVersion, payload, instance._solution.kbId, instance._solution.knowledgeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: KnowledgeCore | ((error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<KnowledgeCore> as KnowledgeCore; + } else { + params = params || {} as Partial<KnowledgeCore> as KnowledgeCore; + } + + let data: any = {}; + + if (params["refresh"] !== undefined) + data["refresh"] = serialize.bool(params["refresh"]); + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<KnowledgeResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<KnowledgeInstance> => ({ + ...response, + body: new KnowledgeInstance(operationVersion, response.body, instance._solution.kbId, instance._solution.knowledgeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface KnowledgePayload extends TokenPaginationPayload { + knowledge: KnowledgeResource[]; +} + +interface KnowledgeResource { + name: string; + description: string; + source: KnowledgeSourceTypes; + id: string; + status: string; + createdAt: Date; + updatedAt: Date; +} + +export class KnowledgeInstance { + protected _solution: KnowledgeContextSolution; + protected _context?: KnowledgeContext; + + constructor(protected _version: V2, _payload: KnowledgeResource, kbId: string, knowledgeId?: string) { + const payload = _payload; + this.name = (payload.name); + this.description = (payload.description); + this.source = payload.source !== null && payload.source !== undefined ? new KnowledgeSourceTypes(payload.source) : null; + this.id = (payload.id); + this.status = (payload.status); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + + this._solution = { kbId, knowledgeId: knowledgeId, }; + } + + /** + * The name of the knowledge source. + */ + name: string; + /** + * A detailed description of the knowledge source and when to use it. This helps provide context about the content and its intended purpose. + */ + description: string; + source: KnowledgeSourceTypes; + /** + * The unique identifier of knowledge source. + */ + id: string; + /** + * The status of processing the knowledge source (\'SCHEDULED\', \'QUEUED\', \'PROCESSING\', \'COMPLETED\', \'FAILED\'). + */ + status: string; + /** + * The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + createdAt: Date; + /** + * The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + updatedAt: Date; + + private get _proxy(): KnowledgeContext { + this._context = this._context || new KnowledgeContextImpl(this._version, this._solution.kbId, this._solution.knowledgeId); + return this._context; + } + + /** + * Remove a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise<KnowledgeInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a KnowledgeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise<KnowledgeInstance>; + /** + * Update a KnowledgeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + update(params: KnowledgeCore, headers?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise<KnowledgeInstance>; + + update(params?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise<KnowledgeInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>>; + /** + * Update a KnowledgeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + updateWithHttpInfo(params: KnowledgeCore, headers?: any, callback?: (error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + name: this.name, + description: this.description, + source: this.source, + id: this.id, + status: this.status, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface KnowledgeSolution { + kbId: string; +} + +export interface KnowledgeListInstance { + _version: V2; + _solution: KnowledgeSolution; + _uri: string; + + (knowledgeId: string, ): KnowledgeContext; + get(knowledgeId: string, ): KnowledgeContext; + + + + + + + + + /** + * Create a KnowledgeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance + */ + create(params: KnowledgeCore, headers?: any, callback?: (error: Error | null, item?: KnowledgeInstance) => any): Promise<KnowledgeInstance>; + + /** + * Create a KnowledgeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeInstance with HTTP metadata + */ + createWithHttpInfo(params: KnowledgeCore, headers?: any, callback?: (error: Error | null, item?: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>>; + + + + + /** + * Streams KnowledgeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + each(params: KnowledgeListInstanceEachOptions, callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams KnowledgeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: KnowledgeListInstanceEachOptions, callback?: (item: KnowledgeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of KnowledgeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: KnowledgePage) => any): Promise<KnowledgePage>; + /** + * Retrieve a single target page of KnowledgeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<KnowledgePage>) => any): Promise<ApiResponse<KnowledgePage>>; + /** + * Lists KnowledgeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: KnowledgeInstance[]) => any): Promise<KnowledgeInstance[]>; + list(params: KnowledgeListInstanceOptions, callback?: (error: Error | null, items: KnowledgeInstance[]) => any): Promise<KnowledgeInstance[]>; + /** + * Lists KnowledgeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<KnowledgeInstance[]>) => any): Promise<ApiResponse<KnowledgeInstance[]>>; + listWithHttpInfo(params: KnowledgeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<KnowledgeInstance[]>) => any): Promise<ApiResponse<KnowledgeInstance[]>>; + /** + * Retrieve a single page of KnowledgeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: KnowledgePage) => any): Promise<KnowledgePage>; + page(params: KnowledgeListInstancePageOptions, callback?: (error: Error | null, items: KnowledgePage) => any): Promise<KnowledgePage>; + /** + * Retrieve a single page of KnowledgeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<KnowledgePage>) => any): Promise<ApiResponse<KnowledgePage>>; + pageWithHttpInfo(params: KnowledgeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<KnowledgePage>) => any): Promise<ApiResponse<KnowledgePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function KnowledgeListInstance(version: V2, kbId: string): KnowledgeListInstance { + if (!isValidPathParam(kbId)) { + throw new Error('Parameter \'kbId\' is not valid.'); + } + + const instance = ((knowledgeId, ) => instance.get(knowledgeId, )) as KnowledgeListInstance; + + instance.get = function get(knowledgeId, ): KnowledgeContext { + return new KnowledgeContextImpl(version, kbId, knowledgeId); + } + + instance._version = version; + instance._solution = { kbId, }; + instance._uri = `/KnowledgeBases/${kbId}/Knowledge`; + + instance.create = function create(params: KnowledgeCore, headers?: any, callback?: (error: Error | null, items: KnowledgeInstance) => any): Promise<KnowledgeInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeInstance(operationVersion, payload, instance._solution.kbId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: KnowledgeCore, headers?: any, callback?: (error: Error | null, items: ApiResponse<KnowledgeInstance>) => any): Promise<ApiResponse<KnowledgeInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<KnowledgeResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<KnowledgeInstance> => ({ + ...response, + body: new KnowledgeInstance(operationVersion, response.body, instance._solution.kbId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: KnowledgeListInstancePageOptions | ((error: Error | null, items: KnowledgePage) => any), callback?: (error: Error | null, items: KnowledgePage) => any): Promise<KnowledgePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["page"] !== undefined) + data["page"] = params["page"]; + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new KnowledgePage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: KnowledgePage) => any): Promise<KnowledgePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new KnowledgePage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: KnowledgeListInstancePageOptions | ((error: Error | null, items: ApiResponse<KnowledgePage>) => any), callback?: (error: Error | null, items: ApiResponse<KnowledgePage>) => any): Promise<ApiResponse<KnowledgePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["page"] !== undefined) + data["page"] = params["page"]; + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<KnowledgePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new KnowledgePage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<KnowledgePage>) => any): Promise<ApiResponse<KnowledgePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<KnowledgePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new KnowledgePage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class KnowledgePage extends TokenPage<V2, KnowledgePayload, KnowledgeResource, KnowledgeInstance> { +/** +* Initialize the KnowledgePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, uri: string, params: any, solution: KnowledgeSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of KnowledgeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: KnowledgeResource): KnowledgeInstance { + + return new KnowledgeInstance( + this._version, + payload, + this._solution.kbId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/knowledge/v2/knowledgeBasis.ts b/rest/knowledge/v2/knowledgeBasis.ts new file mode 100644 index 000000000..401442765 --- /dev/null +++ b/rest/knowledge/v2/knowledgeBasis.ts @@ -0,0 +1,966 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Knowledge API + * APIs for managing knowledge bases and knowledge content for AI-powered applications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class KnowledgeBaseCore { + /** + * Provides a unique and addressable name to be assigned to this Knowledge Base. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + */ + "displayName": string; + /** + * A human readable description of this resource, up to 128 characters. + */ + "description"?: string; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + } +} + + +export class UpdateKnowledgeBaseRequest { + /** + * Provides a unique and addressable name to be assigned to this Knowledge Base. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + */ + "displayName"?: string; + /** + * A human readable description of this resource, up to 128 characters. + */ + "description"?: string; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + } +} + + + + + +/** + * Options to pass to update a KnowledgeBasisInstance + */ +export interface KnowledgeBasisContextUpdateOptions { + /** */ + "updateKnowledgeBaseRequest": UpdateKnowledgeBaseRequest; + /** Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource\'s current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. */ + "ifMatch"?: string; +} + +/** + * Options to pass to create a KnowledgeBasisInstance + */ +export interface KnowledgeBasisListInstanceCreateOptions { + /** */ + "knowledgeBaseCore": KnowledgeBaseCore; +} + +/** + * Options to pass to each + */ +export interface KnowledgeBasisListInstanceEachOptions { + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: KnowledgeBasisInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface KnowledgeBasisListInstanceOptions { + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface KnowledgeBasisListInstancePageOptions { + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; +} + + +export interface KnowledgeBasisContext { + + /** + * Remove a KnowledgeBasisInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance + */ + remove(callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance> + + /** + * Remove a KnowledgeBasisInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>> + + /** + * Fetch a KnowledgeBasisInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance> + + /** + * Fetch a KnowledgeBasisInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>> + + /** + * Update a KnowledgeBasisInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance + */ + update(params: UpdateKnowledgeBaseRequest, headers?: any, callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance>; + + /** + * Update a KnowledgeBasisInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateKnowledgeBaseRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface KnowledgeBasisContextSolution { + "kbId": string; +} + +export class KnowledgeBasisContextImpl implements KnowledgeBasisContext { + protected _solution: KnowledgeBasisContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, kbId: string) { + if (!isValidPathParam(kbId)) { + throw new Error('Parameter \'kbId\' is not valid.'); + } + + this._solution = { kbId, }; + this._uri = `/ControlPlane/KnowledgeBases/${kbId}`; + } + + remove(callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "delete", headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeBasisInstance(operationVersion, payload, instance._solution.kbId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // DELETE operation that returns a response model + let operationPromise = operationVersion.fetchWithResponseInfo<KnowledgeBasisResource>({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<KnowledgeBasisInstance> => ({ + ...response, + body: new KnowledgeBasisInstance(operationVersion, response.body, instance._solution.kbId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeBasisInstance(operationVersion, payload, instance._solution.kbId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<KnowledgeBasisResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<KnowledgeBasisInstance> => ({ + ...response, + body: new KnowledgeBasisInstance(operationVersion, response.body, instance._solution.kbId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: UpdateKnowledgeBaseRequest, headers?: any,callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeBasisInstance(operationVersion, payload, instance._solution.kbId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: UpdateKnowledgeBaseRequest, headers?: any,callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<KnowledgeBasisResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<KnowledgeBasisInstance> => ({ + ...response, + body: new KnowledgeBasisInstance(operationVersion, response.body, instance._solution.kbId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for KnowledgeBaseCore + */ +export interface KnowledgeBaseCore { + displayName: string; + description?: string; +} + +/** + * Nested model for UpdateKnowledgeBaseRequest + */ +export interface UpdateKnowledgeBaseRequest { + displayName?: string; + description?: string; +} + + + + interface KnowledgeBasisPayload extends TokenPaginationPayload { + knowledgeBases: KnowledgeBasisResource[]; +} + +/** + * Response model for CreateKnowledgeBase202Response operations + */ +interface CreateKnowledgeBase202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Response model for DeleteKnowledgeBase202Response operations + */ +interface DeleteKnowledgeBase202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Response model for UpdateKnowledgeBase202Response operations + */ +interface UpdateKnowledgeBase202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Response model for KnowledgeBase operations + */ +interface KnowledgeBase_ResponseResource { + displayName: string; + description?: string; + id: string; + status: string; + createdAt: Date; + updatedAt: Date; + version: number; +} + +/** + * Union type for all possible response models + */ +type KnowledgeBasisResource = CreateKnowledgeBase202Response_ResponseResource | DeleteKnowledgeBase202Response_ResponseResource | UpdateKnowledgeBase202Response_ResponseResource | KnowledgeBase_ResponseResource; + +export class KnowledgeBasisInstance { + protected _solution: KnowledgeBasisContextSolution; + protected _context?: KnowledgeBasisContext; + + constructor(protected _version: V2, _payload: KnowledgeBasisResource, kbId?: string) { + const payload: any = _payload; + this.message = (payload.message); + this.statusUrl = (payload.statusUrl); + this.displayName = (payload.displayName); + this.description = (payload.description); + this.id = (payload.id); + this.status = (payload.status); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + this.version = deserialize.integer(payload.version); + + this._solution = { kbId: kbId, }; + } + + message?: string; + /** + * URI to check operation status. + */ + statusUrl?: string; + /** + * Provides a unique and addressable name to be assigned to this Knowledge Base. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + */ + displayName?: string; + /** + * A human readable description of this resource, up to 128 characters. + */ + description?: string; + /** + * The unique identifier for the Knowledge Base + */ + id?: string; + /** + * The provisioning status of the Knowledge Base + */ + status?: string; + /** + * The ISO 8601 timestamp when the Knowledge Base was created. + */ + createdAt?: Date; + /** + * The ISO 8601 timestamp when the Knowledge Base was last updated. + */ + updatedAt?: Date; + /** + * The current version number of the Knowledge Base. Incremented on each successful mutable update. + */ + version?: number; + + private get _proxy(): KnowledgeBasisContext { + this._context = this._context || new KnowledgeBasisContextImpl(this._version, this._solution.kbId); + return this._context; + } + + /** + * Remove a KnowledgeBasisInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance + */ + remove(callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a KnowledgeBasisInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a KnowledgeBasisInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance + */ + fetch(callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a KnowledgeBasisInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a KnowledgeBasisInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance + */ + update(params: UpdateKnowledgeBaseRequest, headers?: any, callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance>; + + update(params?: any, callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a KnowledgeBasisInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateKnowledgeBaseRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + statusUrl: this.statusUrl, + displayName: this.displayName, + description: this.description, + id: this.id, + status: this.status, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + version: this.version, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface KnowledgeBasisSolution { +} + +export interface KnowledgeBasisListInstance { + _version: V2; + _solution: KnowledgeBasisSolution; + _uri: string; + + (kbId: string, ): KnowledgeBasisContext; + get(kbId: string, ): KnowledgeBasisContext; + + + + + + + + + /** + * Create a KnowledgeBasisInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance + */ + create(params: KnowledgeBaseCore, headers?: any, callback?: (error: Error | null, item?: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance>; + + /** + * Create a KnowledgeBasisInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed KnowledgeBasisInstance with HTTP metadata + */ + createWithHttpInfo(params: KnowledgeBaseCore, headers?: any, callback?: (error: Error | null, item?: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>>; + + + + + /** + * Streams KnowledgeBasisInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeBasisListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: KnowledgeBasisInstance, done: (err?: Error) => void) => void): void; + each(params: KnowledgeBasisListInstanceEachOptions, callback?: (item: KnowledgeBasisInstance, done: (err?: Error) => void) => void): void; + /** + * Streams KnowledgeBasisInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeBasisListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: KnowledgeBasisInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: KnowledgeBasisListInstanceEachOptions, callback?: (item: KnowledgeBasisInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of KnowledgeBasisInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: KnowledgeBasisPage) => any): Promise<KnowledgeBasisPage>; + /** + * Retrieve a single target page of KnowledgeBasisInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<KnowledgeBasisPage>) => any): Promise<ApiResponse<KnowledgeBasisPage>>; + /** + * Lists KnowledgeBasisInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeBasisListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: KnowledgeBasisInstance[]) => any): Promise<KnowledgeBasisInstance[]>; + list(params: KnowledgeBasisListInstanceOptions, callback?: (error: Error | null, items: KnowledgeBasisInstance[]) => any): Promise<KnowledgeBasisInstance[]>; + /** + * Lists KnowledgeBasisInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeBasisListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<KnowledgeBasisInstance[]>) => any): Promise<ApiResponse<KnowledgeBasisInstance[]>>; + listWithHttpInfo(params: KnowledgeBasisListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<KnowledgeBasisInstance[]>) => any): Promise<ApiResponse<KnowledgeBasisInstance[]>>; + /** + * Retrieve a single page of KnowledgeBasisInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeBasisListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: KnowledgeBasisPage) => any): Promise<KnowledgeBasisPage>; + page(params: KnowledgeBasisListInstancePageOptions, callback?: (error: Error | null, items: KnowledgeBasisPage) => any): Promise<KnowledgeBasisPage>; + /** + * Retrieve a single page of KnowledgeBasisInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { KnowledgeBasisListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<KnowledgeBasisPage>) => any): Promise<ApiResponse<KnowledgeBasisPage>>; + pageWithHttpInfo(params: KnowledgeBasisListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<KnowledgeBasisPage>) => any): Promise<ApiResponse<KnowledgeBasisPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function KnowledgeBasisListInstance(version: V2): KnowledgeBasisListInstance { + const instance = ((kbId, ) => instance.get(kbId, )) as KnowledgeBasisListInstance; + + instance.get = function get(kbId, ): KnowledgeBasisContext { + return new KnowledgeBasisContextImpl(version, kbId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ControlPlane/KnowledgeBases`; + + instance.create = function create(params: KnowledgeBaseCore, headers?: any, callback?: (error: Error | null, items: KnowledgeBasisInstance) => any): Promise<KnowledgeBasisInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new KnowledgeBasisInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: KnowledgeBaseCore, headers?: any, callback?: (error: Error | null, items: ApiResponse<KnowledgeBasisInstance>) => any): Promise<ApiResponse<KnowledgeBasisInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<KnowledgeBasisResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<KnowledgeBasisInstance> => ({ + ...response, + body: new KnowledgeBasisInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: KnowledgeBasisListInstancePageOptions | ((error: Error | null, items: KnowledgeBasisPage) => any), callback?: (error: Error | null, items: KnowledgeBasisPage) => any): Promise<KnowledgeBasisPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new KnowledgeBasisPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: KnowledgeBasisPage) => any): Promise<KnowledgeBasisPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new KnowledgeBasisPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: KnowledgeBasisListInstancePageOptions | ((error: Error | null, items: ApiResponse<KnowledgeBasisPage>) => any), callback?: (error: Error | null, items: ApiResponse<KnowledgeBasisPage>) => any): Promise<ApiResponse<KnowledgeBasisPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<KnowledgeBasisPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new KnowledgeBasisPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<KnowledgeBasisPage>) => any): Promise<ApiResponse<KnowledgeBasisPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<KnowledgeBasisPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new KnowledgeBasisPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class KnowledgeBasisPage extends TokenPage<V2, KnowledgeBasisPayload, KnowledgeBasisResource, KnowledgeBasisInstance> { +/** +* Initialize the KnowledgeBasisPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, uri: string, params: any, solution: KnowledgeBasisSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of KnowledgeBasisInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: KnowledgeBasisResource): KnowledgeBasisInstance { + + return new KnowledgeBasisInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/knowledge/v2/operation.ts b/rest/knowledge/v2/operation.ts new file mode 100644 index 000000000..19b23ae57 --- /dev/null +++ b/rest/knowledge/v2/operation.ts @@ -0,0 +1,318 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Knowledge API + * APIs for managing knowledge bases and knowledge content for AI-powered applications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class OperationResultResourceId { + "type": string; + /** + * The identifier of the created or affected resource. + */ + "id": string; + + constructor(payload) { + this.type = payload["type"]; + this.id = payload["id"]; + } +} + + +export class OperationStatusError { + /** + * A URI reference identifying the problem type. + */ + "type"?: string; + /** + * A short, human-readable summary of the problem type. + */ + "title"?: string; + /** + * The numeric Twilio error code. + */ + "code"?: number; + /** + * A human-readable explanation specific to this occurrence of the problem. + */ + "detail"?: string; + + constructor(payload) { + this.type = payload["type"]; + this.title = payload["title"]; + this.code = payload["code"]; + this.detail = payload["detail"]; + } +} + + + + +export interface OperationContext { + + /** + * Fetch a OperationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance + */ + fetch(callback?: (error: Error | null, item?: OperationInstance) => any): Promise<OperationInstance> + + /** + * Fetch a OperationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OperationInstance>) => any): Promise<ApiResponse<OperationInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OperationContextSolution { + "operationId": string; +} + +export class OperationContextImpl implements OperationContext { + protected _solution: OperationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, operationId: string) { + if (!isValidPathParam(operationId)) { + throw new Error('Parameter \'operationId\' is not valid.'); + } + + this._solution = { operationId, }; + this._uri = `/ControlPlane/Operations/${operationId}`; + } + + fetch(callback?: (error: Error | null, item?: OperationInstance) => any): Promise<OperationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OperationInstance(operationVersion, payload, instance._solution.operationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OperationInstance>) => any): Promise<ApiResponse<OperationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<OperationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<OperationInstance> => ({ + ...response, + body: new OperationInstance(operationVersion, response.body, instance._solution.operationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + + +interface OperationResource { + operationId: string; + status: string; + createdAt: Date; + statusUrl: string; + completedAt: Date; + result: OperationResultResourceId; + error: OperationStatusError; + resultUrl: string; +} + +export class OperationInstance { + protected _solution: OperationContextSolution; + protected _context?: OperationContext; + + constructor(protected _version: V2, _payload: OperationResource, operationId?: string) { + const payload = _payload; + this.operationId = (payload.operationId); + this.status = (payload.status); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.statusUrl = (payload.statusUrl); + this.completedAt = deserialize.iso8601DateTime(payload.completedAt); + this.result = payload.result !== null && payload.result !== undefined ? new OperationResultResourceId(payload.result) : null; + this.error = payload.error !== null && payload.error !== undefined ? new OperationStatusError(payload.error) : null; + this.resultUrl = (payload.resultUrl); + + this._solution = { operationId: operationId, }; + } + + /** + * The unique identifier for this operation. + */ + operationId: string; + /** + * The current status of the operation. + */ + status: string; + /** + * When the operation was created. + */ + createdAt: Date; + /** + * URI to check operation status. + */ + statusUrl: string; + /** + * When the operation completed or failed. + */ + completedAt: Date; + result: OperationResultResourceId; + error: OperationStatusError; + /** + * URL to fetch the resulting resource. + */ + resultUrl: string; + + private get _proxy(): OperationContext { + this._context = this._context || new OperationContextImpl(this._version, this._solution.operationId); + return this._context; + } + + /** + * Fetch a OperationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance + */ + fetch(callback?: (error: Error | null, item?: OperationInstance) => any): Promise<OperationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a OperationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OperationInstance>) => any): Promise<ApiResponse<OperationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + operationId: this.operationId, + status: this.status, + createdAt: this.createdAt, + statusUrl: this.statusUrl, + completedAt: this.completedAt, + result: this.result, + error: this.error, + resultUrl: this.resultUrl, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OperationSolution { +} + +export interface OperationListInstance { + _version: V2; + _solution: OperationSolution; + _uri: string; + + (operationId: string, ): OperationContext; + get(operationId: string, ): OperationContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OperationListInstance(version: V2): OperationListInstance { + const instance = ((operationId, ) => instance.get(operationId, )) as OperationListInstance; + + instance.get = function get(operationId, ): OperationContext { + return new OperationContextImpl(version, operationId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/knowledge/v2/search.ts b/rest/knowledge/v2/search.ts new file mode 100644 index 000000000..e7eee33b3 --- /dev/null +++ b/rest/knowledge/v2/search.ts @@ -0,0 +1,287 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Knowledge API + * APIs for managing knowledge bases and knowledge content for AI-powered applications. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class KnowledgeChunkResult { + /** + * The chunk content. + */ + "content"?: string; + /** + * The date and time in GMT when the Chunk was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + "createdAt"?: Date; + /** + * 0-based position of this chunk within its source document for a single ingestion run. + */ + "chunkIndex"?: number; + /** + * Human-readable title of the source document. Web: HTML <title> from the crawled page. File: filename from Unstructured metadata. Text: knowledge name from the knowledge source. + */ + "documentTitle"?: string; + /** + * Specific page URL this chunk was crawled from. Web sources only; null for File and Text sources. + */ + "documentUrl"?: string; + /** + * Physical page number (1-based). PDF sources only; omitted for all other source types. + */ + "documentNumber"?: number; + /** + * The score associated with the chunk. + */ + "score"?: number; + /** + * The unique identifier of knowledge source. + */ + "knowledgeId"?: string; + + constructor(payload) { + this.content = payload["content"]; + this.createdAt = payload["createdAt"]; + this.chunkIndex = payload["chunkIndex"]; + this.documentTitle = payload["documentTitle"]; + this.documentUrl = payload["documentUrl"]; + this.documentNumber = payload["documentNumber"]; + this.score = payload["score"]; + this.knowledgeId = payload["knowledgeId"]; + } +} + + +/** + * Request payload for performing semantic search across knowledge sources within the knowledge base.. Allows querying with natural language text and filtering by specific knowledge sources to find the most relevant content chunks. + */ +export class KnowledgeSearch { + /** + * The query to search the knowledge source. + */ + "query": string; + /** + * The top K results to return. + */ + "top": number; + /** + * The list of knowledge IDs to search. + */ + "knowledgeIds"?: Array<string>; + + constructor(payload) { + this.query = payload["query"]; + this.top = payload["top"]; + this.knowledgeIds = payload["knowledgeIds"]; + } +} + + + +/** + * Options to pass to create a SearchInstance + */ +export interface SearchListInstanceCreateOptions { + /** */ + "knowledgeSearch"?: KnowledgeSearch; +} + + +export interface SearchSolution { + kbId: string; +} + +export interface SearchListInstance { + _version: V2; + _solution: SearchSolution; + _uri: string; + + + + /** + * Create a SearchInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SearchInstance + */ + create(callback?: (error: Error | null, item?: SearchInstance) => any): Promise<SearchInstance>; + /** + * Create a SearchInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SearchInstance + */ + create(params: KnowledgeSearch, headers?: any, callback?: (error: Error | null, item?: SearchInstance) => any): Promise<SearchInstance>; + + /** + * Create a SearchInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SearchInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SearchInstance>) => any): Promise<ApiResponse<SearchInstance>>; + /** + * Create a SearchInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SearchInstance with HTTP metadata + */ + createWithHttpInfo(params: KnowledgeSearch, headers?: any, callback?: (error: Error | null, item?: ApiResponse<SearchInstance>) => any): Promise<ApiResponse<SearchInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SearchListInstance(version: V2, kbId: string): SearchListInstance { + if (!isValidPathParam(kbId)) { + throw new Error('Parameter \'kbId\' is not valid.'); + } + + const instance = {} as SearchListInstance; + + instance._version = version; + instance._solution = { kbId, }; + instance._uri = `/KnowledgeBases/${kbId}/Search`; + + instance.create = function create(params?: KnowledgeSearch | ((error: Error | null, items: SearchInstance) => any), headers?: any, callback?: (error: Error | null, items: SearchInstance) => any): Promise<SearchInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<KnowledgeSearch> as KnowledgeSearch; + } else { + params = params || {} as Partial<KnowledgeSearch> as KnowledgeSearch; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SearchInstance(operationVersion, payload, instance._solution.kbId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: KnowledgeSearch | ((error: Error | null, items: ApiResponse<SearchInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<SearchInstance>) => any): Promise<ApiResponse<SearchInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<KnowledgeSearch> as KnowledgeSearch; + } else { + params = params || {} as Partial<KnowledgeSearch> as KnowledgeSearch; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SearchResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SearchInstance> => ({ + ...response, + body: new SearchInstance(operationVersion, response.body, instance._solution.kbId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + + +interface SearchResource { + chunks: Array<KnowledgeChunkResult>; +} + +export class SearchInstance { + + constructor(protected _version: V2, _payload: SearchResource, kbId: string) { + const payload = _payload; + this.chunks = payload.chunks !== null && payload.chunks !== undefined ? payload.chunks.map( + (payload: any) => new KnowledgeChunkResult(payload) + ) : null; + + } + + chunks: Array<KnowledgeChunkResult>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + chunks: this.chunks, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/lookups/V1.ts b/rest/lookups/V1.ts new file mode 100644 index 000000000..fad01fc04 --- /dev/null +++ b/rest/lookups/V1.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import LookupsBase from "../LookupsBase"; +import Version from "../../base/Version"; +import { PhoneNumberListInstance } from "./v1/phoneNumber"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Lookups + * + * @param domain - The Twilio (Twilio.Lookups) domain + */ + constructor(domain: LookupsBase) { + super(domain, "v1"); + } + + /** phoneNumbers - { Twilio.Lookups.V1.PhoneNumberListInstance } resource */ + protected _phoneNumbers?: PhoneNumberListInstance; + + /** Getter for phoneNumbers resource */ + get phoneNumbers(): PhoneNumberListInstance { + this._phoneNumbers = this._phoneNumbers || PhoneNumberListInstance(this); + return this._phoneNumbers; + } + +} diff --git a/rest/lookups/V2.ts b/rest/lookups/V2.ts new file mode 100644 index 000000000..d2661c669 --- /dev/null +++ b/rest/lookups/V2.ts @@ -0,0 +1,74 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import LookupsBase from "../LookupsBase"; +import Version from "../../base/Version"; +import { BucketListInstance } from "./v2/bucket"; +import { LookupOverrideListInstance } from "./v2/lookupOverride"; +import { PhoneNumberListInstance } from "./v2/phoneNumber"; +import { QueryListInstance } from "./v2/query"; +import { RateLimitListInstance } from "./v2/rateLimit"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Lookups + * + * @param domain - The Twilio (Twilio.Lookups) domain + */ + constructor(domain: LookupsBase) { + super(domain, "v2"); + } + + /** bucket - { Twilio.Lookups.V2.BucketListInstance } resource */ + protected _bucket?: BucketListInstance; + /** lookupOverrides - { Twilio.Lookups.V2.LookupOverrideListInstance } resource */ + protected _lookupOverrides?: LookupOverrideListInstance; + /** phoneNumbers - { Twilio.Lookups.V2.PhoneNumberListInstance } resource */ + protected _phoneNumbers?: PhoneNumberListInstance; + /** query - { Twilio.Lookups.V2.QueryListInstance } resource */ + protected _query?: QueryListInstance; + /** rateLimits - { Twilio.Lookups.V2.RateLimitListInstance } resource */ + protected _rateLimits?: RateLimitListInstance; + + /** Getter for bucket resource */ + get bucket(): BucketListInstance { + this._bucket = this._bucket || BucketListInstance(this); + return this._bucket; + } + + /** Getter for lookupOverrides resource */ + get lookupOverrides(): LookupOverrideListInstance { + this._lookupOverrides = this._lookupOverrides || LookupOverrideListInstance(this); + return this._lookupOverrides; + } + + /** Getter for phoneNumbers resource */ + get phoneNumbers(): PhoneNumberListInstance { + this._phoneNumbers = this._phoneNumbers || PhoneNumberListInstance(this); + return this._phoneNumbers; + } + + /** Getter for query resource */ + get query(): QueryListInstance { + this._query = this._query || QueryListInstance(this); + return this._query; + } + + /** Getter for rateLimits resource */ + get rateLimits(): RateLimitListInstance { + this._rateLimits = this._rateLimits || RateLimitListInstance(this); + return this._rateLimits; + } + +} diff --git a/rest/lookups/v1/phoneNumber.ts b/rest/lookups/v1/phoneNumber.ts new file mode 100644 index 000000000..aed668f9d --- /dev/null +++ b/rest/lookups/v1/phoneNumber.ts @@ -0,0 +1,371 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a PhoneNumberInstance + */ +export interface PhoneNumberContextFetchOptions { + /** The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. */ + "countryCode"?: string; + /** The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. */ + "type"?: Array<string>; + /** The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). */ + "addOns"?: Array<string>; + /** Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. */ + "addOnsData"?: Record<string, object>; +} + +export interface PhoneNumberContext { + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Fetch a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(params: PhoneNumberContextFetchOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PhoneNumberContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PhoneNumberContextSolution { + "phoneNumber": string; +} + +export class PhoneNumberContextImpl implements PhoneNumberContext { + protected _solution: PhoneNumberContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, phoneNumber: string) { + if (!isValidPathParam(phoneNumber)) { + throw new Error('Parameter \'phoneNumber\' is not valid.'); + } + + this._solution = { phoneNumber, }; + this._uri = `/PhoneNumbers/${phoneNumber}`; + } + + fetch(params?: PhoneNumberContextFetchOptions | ((error: Error | null, item?: PhoneNumberInstance) => any),callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["countryCode"] !== undefined) + data["CountryCode"] = params["countryCode"]; + if (params["type"] !== undefined) + data["Type"] = serialize.map(params["type"], (e: string) => (e)); + if (params["addOns"] !== undefined) + data["AddOns"] = serialize.map(params["addOns"], (e: string) => (e)); + if (params["addOnsData"] !== undefined) + data = {...data, ...serialize.prefixedCollapsibleMap(params["addOnsData"], "AddOns")}; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: PhoneNumberContextFetchOptions | ((error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["countryCode"] !== undefined) + data["CountryCode"] = params["countryCode"]; + if (params["type"] !== undefined) + data["Type"] = serialize.map(params["type"], (e: string) => (e)); + if (params["addOns"] !== undefined) + data["AddOns"] = serialize.map(params["addOns"], (e: string) => (e)); + if (params["addOnsData"] !== undefined) + data = {...data, ...serialize.prefixedCollapsibleMap(params["addOnsData"], "AddOns")}; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PhoneNumberPayload extends PhoneNumberResource {} + +interface PhoneNumberResource { + caller_name: any; + country_code: string; + phone_number: string; + national_format: string; + carrier: any; + add_ons: any; + url: string; +} + +export class PhoneNumberInstance { + protected _solution: PhoneNumberContextSolution; + protected _context?: PhoneNumberContext; + + constructor(protected _version: V1, payload: PhoneNumberResource, phoneNumber?: string) { + + this.callerName = (payload.caller_name); + this.countryCode = (payload.country_code); + this.phoneNumber = (payload.phone_number); + this.nationalFormat = (payload.national_format); + this.carrier = (payload.carrier); + this.addOns = (payload.add_ons); + this.url = (payload.url); + + this._solution = { phoneNumber: phoneNumber, }; + } + + /** + * The name of the phone number\'s owner. If `null`, that information was not available. + */ + callerName: any; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) for the phone number. + */ + countryCode: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The phone number, in national format. + */ + nationalFormat: string; + /** + * The telecom company that provides the phone number. + */ + carrier: any; + /** + * A JSON string with the results of the Add-ons you specified in the `add_ons` parameters. For the format of the object, see [Using Add-ons](https://www.twilio.com/docs/add-ons). + */ + addOns: any; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): PhoneNumberContext { + this._context = this._context || new PhoneNumberContextImpl(this._version, this._solution.phoneNumber); + return this._context; + } + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Fetch a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(params: PhoneNumberContextFetchOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PhoneNumberContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + callerName: this.callerName, + countryCode: this.countryCode, + phoneNumber: this.phoneNumber, + nationalFormat: this.nationalFormat, + carrier: this.carrier, + addOns: this.addOns, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PhoneNumberSolution { +} + +export interface PhoneNumberListInstance { + _version: V1; + _solution: PhoneNumberSolution; + _uri: string; + + (phoneNumber: string, ): PhoneNumberContext; + get(phoneNumber: string, ): PhoneNumberContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PhoneNumberListInstance(version: V1): PhoneNumberListInstance { + const instance = ((phoneNumber, ) => instance.get(phoneNumber, )) as PhoneNumberListInstance; + + instance.get = function get(phoneNumber, ): PhoneNumberContext { + return new PhoneNumberContextImpl(version, phoneNumber); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/lookups/v2/bucket.ts b/rest/lookups/v2/bucket.ts new file mode 100644 index 000000000..ab4484932 --- /dev/null +++ b/rest/lookups/v2/bucket.ts @@ -0,0 +1,558 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Rate limit request schema + */ +export class RateLimitRequest { + /** + * Limit of requests for the bucket + */ + "limit"?: number; + /** + * Time to live of the rule + */ + "ttl"?: number; + + constructor(payload) { + this.limit = payload["limit"]; + this.ttl = payload["ttl"]; + } +} + + + + + +/** + * Options to pass to update a BucketInstance + */ +export interface BucketContextUpdateOptions { + /** */ + "rateLimitRequest"?: RateLimitRequest; +} + +export interface BucketContext { + + /** + * Remove a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + fetch(callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance> + + /** + * Fetch a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> + + /** + * Update a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + update(callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance>; + /** + * Update a BucketInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + update(params: RateLimitRequest, headers?: any, callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance>; + + /** + * Update a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>>; + /** + * Update a BucketInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + updateWithHttpInfo(params: RateLimitRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BucketContextSolution { + "field": string; + "bucket": string; +} + +export class BucketContextImpl implements BucketContext { + protected _solution: BucketContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, field: string, bucket: string) { + if (!isValidPathParam(field)) { + throw new Error('Parameter \'field\' is not valid.'); + } + + if (!isValidPathParam(bucket)) { + throw new Error('Parameter \'bucket\' is not valid.'); + } + + this._solution = { field, bucket, }; + this._uri = `/RateLimits/Fields/${field}/Bucket/${bucket}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BucketInstance(operationVersion, payload, instance._solution.field, instance._solution.bucket)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<BucketResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<BucketInstance> => ({ + ...response, + body: new BucketInstance(operationVersion, response.body, instance._solution.field, instance._solution.bucket) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: RateLimitRequest | ((error: Error | null, item?: BucketInstance) => any), headers?: any,callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<RateLimitRequest> as RateLimitRequest; + } else { + params = params || {} as Partial<RateLimitRequest> as RateLimitRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new BucketInstance(operationVersion, payload, instance._solution.field, instance._solution.bucket)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: RateLimitRequest | ((error: Error | null, item?: ApiResponse<BucketInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<RateLimitRequest> as RateLimitRequest; + } else { + params = params || {} as Partial<RateLimitRequest> as RateLimitRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<BucketResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<BucketInstance> => ({ + ...response, + body: new BucketInstance(operationVersion, response.body, instance._solution.field, instance._solution.bucket) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BucketPayload extends BucketResource {} + +interface BucketResource { + code: number; + message: string; + more_info: string; + status: number; + field: string; + limit: number; + bucket: string; + owner: string; + ttl: number; +} + +export class BucketInstance { + protected _solution: BucketContextSolution; + protected _context?: BucketContext; + + constructor(protected _version: V2, payload: BucketResource, field?: string, bucket?: string) { + + this.code = (payload.code); + this.message = (payload.message); + this.moreInfo = (payload.more_info); + this.status = (payload.status); + this.field = (payload.field); + this.limit = (payload.limit); + this.bucket = (payload.bucket); + this.owner = (payload.owner); + this.ttl = (payload.ttl); + + this._solution = { field: field, bucket: bucket, }; + } + + /** + * Twilio-specific error code + */ + code: number; + /** + * Error message + */ + message: string; + /** + * Link to Error Code References + */ + moreInfo: string; + /** + * HTTP response status code + */ + status: number; + /** + * Limit of requests for the bucket + */ + field: string; + /** + * Limit of requests for the bucket + */ + limit: number; + /** + * Name of the bucket + */ + bucket: string; + /** + * Owner of the rule + */ + owner: string; + /** + * Time to live of the rule + */ + ttl: number; + + private get _proxy(): BucketContext { + this._context = this._context || new BucketContextImpl(this._version, this._solution.field, this._solution.bucket); + return this._context; + } + + /** + * Remove a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + fetch(callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + update(callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance>; + /** + * Update a BucketInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + update(params: RateLimitRequest, headers?: any, callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance>; + + update(params?: any, callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>>; + /** + * Update a BucketInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + updateWithHttpInfo(params: RateLimitRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + code: this.code, + message: this.message, + moreInfo: this.moreInfo, + status: this.status, + field: this.field, + limit: this.limit, + bucket: this.bucket, + owner: this.owner, + ttl: this.ttl, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BucketSolution { +} + +export interface BucketListInstance { + _version: V2; + _solution: BucketSolution; + _uri: string; + + (field: string, bucket: string, ): BucketContext; + get(field: string, bucket: string, ): BucketContext; + + + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BucketListInstance(version: V2): BucketListInstance { + const instance = ((field, bucket, ) => instance.get(field, bucket, )) as BucketListInstance; + + instance.get = function get(field, bucket, ): BucketContext { + return new BucketContextImpl(version, field, bucket); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/lookups/v2/lookupOverride.ts b/rest/lookups/v2/lookupOverride.ts new file mode 100644 index 000000000..c4d263469 --- /dev/null +++ b/rest/lookups/v2/lookupOverride.ts @@ -0,0 +1,759 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class OverridesRequest { + /** + * The new line type to override the original line type + */ + "lineType"?: string; + /** + * The reason for the override + */ + "reason"?: string; + + constructor(payload) { + this.lineType = payload["line_type"]; + this.reason = payload["reason"]; + } +} + + + +/** + * Options to pass to create a LookupOverrideInstance + */ +export interface LookupOverrideContextCreateOptions { + /** */ + "overridesRequest"?: OverridesRequest; +} + + + +/** + * Options to pass to update a LookupOverrideInstance + */ +export interface LookupOverrideContextUpdateOptions { + /** */ + "overridesRequest"?: OverridesRequest; +} + +export interface LookupOverrideContext { + + /** + * Create a LookupOverrideInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance + */ + create(callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance>; + /** + * Create a LookupOverrideInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance + */ + create(params: OverridesRequest, headers?: any, callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance>; + + /** + * Create a LookupOverrideInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>>; + /** + * Create a LookupOverrideInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance with HTTP metadata + */ + createWithHttpInfo(params: OverridesRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>>; + + /** + * Remove a LookupOverrideInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a LookupOverrideInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a LookupOverrideInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance + */ + fetch(callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance> + + /** + * Fetch a LookupOverrideInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>> + + /** + * Update a LookupOverrideInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance + */ + update(callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance>; + /** + * Update a LookupOverrideInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance + */ + update(params: OverridesRequest, headers?: any, callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance>; + + /** + * Update a LookupOverrideInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>>; + /** + * Update a LookupOverrideInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance with HTTP metadata + */ + updateWithHttpInfo(params: OverridesRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface LookupOverrideContextSolution { + "field": string; + "phoneNumber": string; +} + +export class LookupOverrideContextImpl implements LookupOverrideContext { + protected _solution: LookupOverrideContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, field: string, phoneNumber: string) { + if (!isValidPathParam(field)) { + throw new Error('Parameter \'field\' is not valid.'); + } + + if (!isValidPathParam(phoneNumber)) { + throw new Error('Parameter \'phoneNumber\' is not valid.'); + } + + this._solution = { field, phoneNumber, }; + this._uri = `/PhoneNumbers/${phoneNumber}/Overrides/${field}`; + } + + create(params?: OverridesRequest | ((error: Error | null, item?: LookupOverrideInstance) => any), headers?: any,callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<OverridesRequest> as OverridesRequest; + } else { + params = params || {} as Partial<OverridesRequest> as OverridesRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new LookupOverrideInstance(operationVersion, payload, instance._solution.field, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params?: OverridesRequest | ((error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<OverridesRequest> as OverridesRequest; + } else { + params = params || {} as Partial<OverridesRequest> as OverridesRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<LookupOverrideResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<LookupOverrideInstance> => ({ + ...response, + body: new LookupOverrideInstance(operationVersion, response.body, instance._solution.field, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new LookupOverrideInstance(operationVersion, payload, instance._solution.field, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<LookupOverrideResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<LookupOverrideInstance> => ({ + ...response, + body: new LookupOverrideInstance(operationVersion, response.body, instance._solution.field, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: OverridesRequest | ((error: Error | null, item?: LookupOverrideInstance) => any), headers?: any,callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<OverridesRequest> as OverridesRequest; + } else { + params = params || {} as Partial<OverridesRequest> as OverridesRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new LookupOverrideInstance(operationVersion, payload, instance._solution.field, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: OverridesRequest | ((error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<OverridesRequest> as OverridesRequest; + } else { + params = params || {} as Partial<OverridesRequest> as OverridesRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<LookupOverrideResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<LookupOverrideInstance> => ({ + ...response, + body: new LookupOverrideInstance(operationVersion, response.body, instance._solution.field, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface LookupOverridePayload extends LookupOverrideResource {} + +interface LookupOverrideResource { + phone_number: string; + original_line_type: string; + overridden_line_type: string; + override_reason: string; + override_timestamp: Date; + overridden_by_account_sid: string; + code: number; + message: string; + more_info: string; + status: number; + field: string; + limit: number; + bucket: string; + owner: string; + ttl: number; +} + +export class LookupOverrideInstance { + protected _solution: LookupOverrideContextSolution; + protected _context?: LookupOverrideContext; + + constructor(protected _version: V2, payload: LookupOverrideResource, field?: string, phoneNumber?: string) { + + this.phoneNumber = (payload.phone_number); + this.originalLineType = (payload.original_line_type); + this.overriddenLineType = (payload.overridden_line_type); + this.overrideReason = (payload.override_reason); + this.overrideTimestamp = deserialize.iso8601DateTime(payload.override_timestamp); + this.overriddenByAccountSid = (payload.overridden_by_account_sid); + this.code = (payload.code); + this.message = (payload.message); + this.moreInfo = (payload.more_info); + this.status = (payload.status); + this.field = (payload.field); + this.limit = (payload.limit); + this.bucket = (payload.bucket); + this.owner = (payload.owner); + this.ttl = (payload.ttl); + + this._solution = { field: field, phoneNumber: phoneNumber, }; + } + + /** + * The phone number for which the override was created + */ + phoneNumber: string; + /** + * The original line type + */ + originalLineType: string; + /** + * The new line type after the override + */ + overriddenLineType: string; + /** + * The reason for the override + */ + overrideReason: string; + overrideTimestamp: Date; + /** + * The Account SID for the user who made the override + */ + overriddenByAccountSid: string; + /** + * Twilio-specific error code + */ + code: number; + /** + * Error message + */ + message: string; + /** + * Link to Error Code References + */ + moreInfo: string; + /** + * HTTP response status code + */ + status: number; + /** + * Limit of requests for the bucket + */ + field: string; + /** + * Limit of requests for the bucket + */ + limit: number; + /** + * Name of the bucket + */ + bucket: string; + /** + * Owner of the rule + */ + owner: string; + /** + * Time to live of the rule + */ + ttl: number; + + private get _proxy(): LookupOverrideContext { + this._context = this._context || new LookupOverrideContextImpl(this._version, this._solution.field, this._solution.phoneNumber); + return this._context; + } + + /** + * Create a LookupOverrideInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance + */ + create(callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance>; + /** + * Create a LookupOverrideInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance + */ + create(params: OverridesRequest, headers?: any, callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance>; + + create(params?: any, callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance> + { + return this._proxy.create(params, callback); + } + + /** + * Create a LookupOverrideInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>>; + /** + * Create a LookupOverrideInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance with HTTP metadata + */ + createWithHttpInfo(params: OverridesRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Remove a LookupOverrideInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a LookupOverrideInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a LookupOverrideInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance + */ + fetch(callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a LookupOverrideInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a LookupOverrideInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance + */ + update(callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance>; + /** + * Update a LookupOverrideInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance + */ + update(params: OverridesRequest, headers?: any, callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance>; + + update(params?: any, callback?: (error: Error | null, item?: LookupOverrideInstance) => any): Promise<LookupOverrideInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a LookupOverrideInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>>; + /** + * Update a LookupOverrideInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupOverrideInstance with HTTP metadata + */ + updateWithHttpInfo(params: OverridesRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<LookupOverrideInstance>) => any): Promise<ApiResponse<LookupOverrideInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + phoneNumber: this.phoneNumber, + originalLineType: this.originalLineType, + overriddenLineType: this.overriddenLineType, + overrideReason: this.overrideReason, + overrideTimestamp: this.overrideTimestamp, + overriddenByAccountSid: this.overriddenByAccountSid, + code: this.code, + message: this.message, + moreInfo: this.moreInfo, + status: this.status, + field: this.field, + limit: this.limit, + bucket: this.bucket, + owner: this.owner, + ttl: this.ttl, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface LookupOverrideSolution { +} + +export interface LookupOverrideListInstance { + _version: V2; + _solution: LookupOverrideSolution; + _uri: string; + + (field: string, phoneNumber: string, ): LookupOverrideContext; + get(field: string, phoneNumber: string, ): LookupOverrideContext; + + + + + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function LookupOverrideListInstance(version: V2): LookupOverrideListInstance { + const instance = ((field, phoneNumber, ) => instance.get(field, phoneNumber, )) as LookupOverrideListInstance; + + instance.get = function get(field, phoneNumber, ): LookupOverrideContext { + return new LookupOverrideContextImpl(version, field, phoneNumber); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/lookups/v2/phoneNumber.ts b/rest/lookups/v2/phoneNumber.ts new file mode 100644 index 000000000..455b86189 --- /dev/null +++ b/rest/lookups/v2/phoneNumber.ts @@ -0,0 +1,633 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class CallForwardingInfo { + "callForwardingEnabled"?: boolean; + "errorCode"?: number; + + constructor(payload) { + this.callForwardingEnabled = payload["call_forwarding_enabled"]; + this.errorCode = payload["error_code"]; + } +} + + +export class CallerNameInfo { + "callerName"?: string; + "callerType"?: string; + "errorCode"?: number; + + constructor(payload) { + this.callerName = payload["caller_name"]; + this.callerType = payload["caller_type"]; + this.errorCode = payload["error_code"]; + } +} + + +export class IdentityMatchInfo { + "firstNameMatch"?: string; + "lastNameMatch"?: string; + "addressLinesMatch"?: string; + "cityMatch"?: string; + "stateMatch"?: string; + "postalCodeMatch"?: string; + "addressCountryMatch"?: string; + "nationalIdMatch"?: string; + "dateOfBirthMatch"?: string; + "summaryScore"?: number; + "errorCode"?: number; + "errorMessage"?: string; + + constructor(payload) { + this.firstNameMatch = payload["first_name_match"]; + this.lastNameMatch = payload["last_name_match"]; + this.addressLinesMatch = payload["address_lines_match"]; + this.cityMatch = payload["city_match"]; + this.stateMatch = payload["state_match"]; + this.postalCodeMatch = payload["postal_code_match"]; + this.addressCountryMatch = payload["address_country_match"]; + this.nationalIdMatch = payload["national_id_match"]; + this.dateOfBirthMatch = payload["date_of_birth_match"]; + this.summaryScore = payload["summary_score"]; + this.errorCode = payload["error_code"]; + this.errorMessage = payload["error_message"]; + } +} + + +export class LastSimSwapInfo { + "lastSimSwapDate"?: Date; + "swappedPeriod"?: string; + "swappedInPeriod"?: boolean; + + constructor(payload) { + this.lastSimSwapDate = payload["last_sim_swap_date"]; + this.swappedPeriod = payload["swapped_period"]; + this.swappedInPeriod = payload["swapped_in_period"]; + } +} + + +export class LineStatusInfo { + "status"?: string; + "errorCode"?: number; + + constructor(payload) { + this.status = payload["status"]; + this.errorCode = payload["error_code"]; + } +} + + +export class LineTypeIntelligenceInfo { + "mobileCountryCode"?: string; + "mobileNetworkCode"?: string; + "carrierName"?: string; + "type"?: string; + "errorCode"?: number; + + constructor(payload) { + this.mobileCountryCode = payload["mobile_country_code"]; + this.mobileNetworkCode = payload["mobile_network_code"]; + this.carrierName = payload["carrier_name"]; + this.type = payload["type"]; + this.errorCode = payload["error_code"]; + } +} + + +export class ReassignedNumberInfo { + "lastVerifiedDate"?: string; + "isNumberReassigned"?: string; + "errorCode"?: string; + + constructor(payload) { + this.lastVerifiedDate = payload["last_verified_date"]; + this.isNumberReassigned = payload["is_number_reassigned"]; + this.errorCode = payload["error_code"]; + } +} + + +export class SimSwapInfo { + "lastSimSwap"?: LastSimSwapInfo; + "carrierName"?: string; + "mobileCountryCode"?: string; + "mobileNetworkCode"?: string; + "errorCode"?: number; + + constructor(payload) { + this.lastSimSwap = payload["last_sim_swap"]; + this.carrierName = payload["carrier_name"]; + this.mobileCountryCode = payload["mobile_country_code"]; + this.mobileNetworkCode = payload["mobile_network_code"]; + this.errorCode = payload["error_code"]; + } +} + + +export class SmsPumpingRiskInfo { + "carrierRiskCategory"?: string; + "numberBlocked"?: boolean; + "numberBlockedDate"?: Date; + "numberBlockedLast3Months"?: boolean; + "smsPumpingRiskScore"?: number; + "errorCode"?: number; + + constructor(payload) { + this.carrierRiskCategory = payload["carrier_risk_category"]; + this.numberBlocked = payload["number_blocked"]; + this.numberBlockedDate = payload["number_blocked_date"]; + this.numberBlockedLast3Months = payload["number_blocked_last_3_months"]; + this.smsPumpingRiskScore = payload["sms_pumping_risk_score"]; + this.errorCode = payload["error_code"]; + } +} + + +/** + * Contains reasons why a phone number is invalid. Possible values: TOO_SHORT, TOO_LONG, INVALID_BUT_POSSIBLE, INVALID_COUNTRY_CODE, INVALID_LENGTH, NOT_A_NUMBER. + */ +export type ValidationError = 'TOO_SHORT'|'TOO_LONG'|'INVALID_BUT_POSSIBLE'|'INVALID_COUNTRY_CODE'|'INVALID_LENGTH'|'NOT_A_NUMBER'; + + +/** + * Options to pass to fetch a PhoneNumberInstance + */ +export interface PhoneNumberContextFetchOptions { + /** A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. */ + "fields"?: string; + /** The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. */ + "countryCode"?: string; + /** User’s first name. This query parameter is only used (optionally) for identity_match package requests. */ + "firstName"?: string; + /** User’s last name. This query parameter is only used (optionally) for identity_match package requests. */ + "lastName"?: string; + /** User’s first address line. This query parameter is only used (optionally) for identity_match package requests. */ + "addressLine1"?: string; + /** User’s second address line. This query parameter is only used (optionally) for identity_match package requests. */ + "addressLine2"?: string; + /** User’s city. This query parameter is only used (optionally) for identity_match package requests. */ + "city"?: string; + /** User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. */ + "state"?: string; + /** User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. */ + "postalCode"?: string; + /** User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. */ + "addressCountryCode"?: string; + /** User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. */ + "nationalId"?: string; + /** User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. */ + "dateOfBirth"?: string; + /** The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. */ + "lastVerifiedDate"?: string; + /** The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. */ + "verificationSid"?: string; + /** The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. */ + "partnerSubId"?: string; +} + +export interface PhoneNumberContext { + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Fetch a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(params: PhoneNumberContextFetchOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PhoneNumberContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PhoneNumberContextSolution { + "phoneNumber": string; +} + +export class PhoneNumberContextImpl implements PhoneNumberContext { + protected _solution: PhoneNumberContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, phoneNumber: string) { + if (!isValidPathParam(phoneNumber)) { + throw new Error('Parameter \'phoneNumber\' is not valid.'); + } + + this._solution = { phoneNumber, }; + this._uri = `/PhoneNumbers/${phoneNumber}`; + } + + fetch(params?: PhoneNumberContextFetchOptions | ((error: Error | null, item?: PhoneNumberInstance) => any),callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["fields"] !== undefined) + data["Fields"] = params["fields"]; + if (params["countryCode"] !== undefined) + data["CountryCode"] = params["countryCode"]; + if (params["firstName"] !== undefined) + data["FirstName"] = params["firstName"]; + if (params["lastName"] !== undefined) + data["LastName"] = params["lastName"]; + if (params["addressLine1"] !== undefined) + data["AddressLine1"] = params["addressLine1"]; + if (params["addressLine2"] !== undefined) + data["AddressLine2"] = params["addressLine2"]; + if (params["city"] !== undefined) + data["City"] = params["city"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["postalCode"] !== undefined) + data["PostalCode"] = params["postalCode"]; + if (params["addressCountryCode"] !== undefined) + data["AddressCountryCode"] = params["addressCountryCode"]; + if (params["nationalId"] !== undefined) + data["NationalId"] = params["nationalId"]; + if (params["dateOfBirth"] !== undefined) + data["DateOfBirth"] = params["dateOfBirth"]; + if (params["lastVerifiedDate"] !== undefined) + data["LastVerifiedDate"] = params["lastVerifiedDate"]; + if (params["verificationSid"] !== undefined) + data["VerificationSid"] = params["verificationSid"]; + if (params["partnerSubId"] !== undefined) + data["PartnerSubId"] = params["partnerSubId"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: PhoneNumberContextFetchOptions | ((error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["fields"] !== undefined) + data["Fields"] = params["fields"]; + if (params["countryCode"] !== undefined) + data["CountryCode"] = params["countryCode"]; + if (params["firstName"] !== undefined) + data["FirstName"] = params["firstName"]; + if (params["lastName"] !== undefined) + data["LastName"] = params["lastName"]; + if (params["addressLine1"] !== undefined) + data["AddressLine1"] = params["addressLine1"]; + if (params["addressLine2"] !== undefined) + data["AddressLine2"] = params["addressLine2"]; + if (params["city"] !== undefined) + data["City"] = params["city"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + if (params["postalCode"] !== undefined) + data["PostalCode"] = params["postalCode"]; + if (params["addressCountryCode"] !== undefined) + data["AddressCountryCode"] = params["addressCountryCode"]; + if (params["nationalId"] !== undefined) + data["NationalId"] = params["nationalId"]; + if (params["dateOfBirth"] !== undefined) + data["DateOfBirth"] = params["dateOfBirth"]; + if (params["lastVerifiedDate"] !== undefined) + data["LastVerifiedDate"] = params["lastVerifiedDate"]; + if (params["verificationSid"] !== undefined) + data["VerificationSid"] = params["verificationSid"]; + if (params["partnerSubId"] !== undefined) + data["PartnerSubId"] = params["partnerSubId"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PhoneNumberPayload extends PhoneNumberResource {} + +interface PhoneNumberResource { + calling_country_code: string; + country_code: string; + phone_number: string; + national_format: string; + valid: boolean; + validation_errors: Array<ValidationError>; + caller_name: CallerNameInfo; + sim_swap: SimSwapInfo; + call_forwarding: CallForwardingInfo; + line_type_intelligence: LineTypeIntelligenceInfo; + line_status: LineStatusInfo; + identity_match: IdentityMatchInfo; + reassigned_number: ReassignedNumberInfo; + sms_pumping_risk: SmsPumpingRiskInfo; + phone_number_quality_score: any; + pre_fill: any; + url: string; +} + +export class PhoneNumberInstance { + protected _solution: PhoneNumberContextSolution; + protected _context?: PhoneNumberContext; + + constructor(protected _version: V2, payload: PhoneNumberResource, phoneNumber?: string) { + + this.callingCountryCode = (payload.calling_country_code); + this.countryCode = (payload.country_code); + this.phoneNumber = (payload.phone_number); + this.nationalFormat = (payload.national_format); + this.valid = (payload.valid); + this.validationErrors = (payload.validation_errors); + this.callerName = payload.caller_name !== null && payload.caller_name !== undefined ? new CallerNameInfo(payload.caller_name) : null; + this.simSwap = payload.sim_swap !== null && payload.sim_swap !== undefined ? new SimSwapInfo(payload.sim_swap) : null; + this.callForwarding = payload.call_forwarding !== null && payload.call_forwarding !== undefined ? new CallForwardingInfo(payload.call_forwarding) : null; + this.lineTypeIntelligence = payload.line_type_intelligence !== null && payload.line_type_intelligence !== undefined ? new LineTypeIntelligenceInfo(payload.line_type_intelligence) : null; + this.lineStatus = payload.line_status !== null && payload.line_status !== undefined ? new LineStatusInfo(payload.line_status) : null; + this.identityMatch = payload.identity_match !== null && payload.identity_match !== undefined ? new IdentityMatchInfo(payload.identity_match) : null; + this.reassignedNumber = payload.reassigned_number !== null && payload.reassigned_number !== undefined ? new ReassignedNumberInfo(payload.reassigned_number) : null; + this.smsPumpingRisk = payload.sms_pumping_risk !== null && payload.sms_pumping_risk !== undefined ? new SmsPumpingRiskInfo(payload.sms_pumping_risk) : null; + this.phoneNumberQualityScore = (payload.phone_number_quality_score); + this.preFill = (payload.pre_fill); + this.url = (payload.url); + + this._solution = { phoneNumber: phoneNumber, }; + } + + /** + * International dialing prefix of the phone number defined in the E.164 standard. + */ + callingCountryCode: string; + /** + * The phone number\'s [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + */ + countryCode: string; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The phone number in [national format](https://en.wikipedia.org/wiki/National_conventions_for_writing_telephone_numbers). + */ + nationalFormat: string; + /** + * Boolean which indicates if the phone number is in a valid range that can be freely assigned by a carrier to a user. + */ + valid: boolean; + /** + * Contains reasons why a phone number is invalid. Possible values: TOO_SHORT, TOO_LONG, INVALID_BUT_POSSIBLE, INVALID_COUNTRY_CODE, INVALID_LENGTH, NOT_A_NUMBER. + */ + validationErrors: Array<ValidationError>; + callerName: CallerNameInfo; + simSwap: SimSwapInfo; + callForwarding: CallForwardingInfo; + lineTypeIntelligence: LineTypeIntelligenceInfo; + lineStatus: LineStatusInfo; + identityMatch: IdentityMatchInfo; + reassignedNumber: ReassignedNumberInfo; + smsPumpingRisk: SmsPumpingRiskInfo; + /** + * An object that contains information of a mobile phone number quality score. Quality score will return a risk score about the phone number. + */ + phoneNumberQualityScore: any; + /** + * An object that contains pre fill information. pre_fill will return PII information associated with the phone number like first name, last name, address line, country code, state and postal code. + */ + preFill: any; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): PhoneNumberContext { + this._context = this._context || new PhoneNumberContextImpl(this._version, this._solution.phoneNumber); + return this._context; + } + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Fetch a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(params: PhoneNumberContextFetchOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PhoneNumberContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + callingCountryCode: this.callingCountryCode, + countryCode: this.countryCode, + phoneNumber: this.phoneNumber, + nationalFormat: this.nationalFormat, + valid: this.valid, + validationErrors: this.validationErrors, + callerName: this.callerName, + simSwap: this.simSwap, + callForwarding: this.callForwarding, + lineTypeIntelligence: this.lineTypeIntelligence, + lineStatus: this.lineStatus, + identityMatch: this.identityMatch, + reassignedNumber: this.reassignedNumber, + smsPumpingRisk: this.smsPumpingRisk, + phoneNumberQualityScore: this.phoneNumberQualityScore, + preFill: this.preFill, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PhoneNumberSolution { +} + +export interface PhoneNumberListInstance { + _version: V2; + _solution: PhoneNumberSolution; + _uri: string; + + (phoneNumber: string, ): PhoneNumberContext; + get(phoneNumber: string, ): PhoneNumberContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PhoneNumberListInstance(version: V2): PhoneNumberListInstance { + const instance = ((phoneNumber, ) => instance.get(phoneNumber, )) as PhoneNumberListInstance; + + instance.get = function get(phoneNumber, ): PhoneNumberContext { + return new PhoneNumberContextImpl(version, phoneNumber); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/lookups/v2/query.ts b/rest/lookups/v2/query.ts new file mode 100644 index 000000000..63d97220f --- /dev/null +++ b/rest/lookups/v2/query.ts @@ -0,0 +1,482 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class CallForwardingInfo { + "callForwardingEnabled"?: boolean; + "errorCode"?: number; + + constructor(payload) { + this.callForwardingEnabled = payload["call_forwarding_enabled"]; + this.errorCode = payload["error_code"]; + } +} + + +export class CallerNameInfo { + "callerName"?: string; + "callerType"?: string; + "errorCode"?: number; + + constructor(payload) { + this.callerName = payload["caller_name"]; + this.callerType = payload["caller_type"]; + this.errorCode = payload["error_code"]; + } +} + + +export class IdentityMatchInfo { + "firstNameMatch"?: string; + "lastNameMatch"?: string; + "addressLinesMatch"?: string; + "cityMatch"?: string; + "stateMatch"?: string; + "postalCodeMatch"?: string; + "addressCountryMatch"?: string; + "nationalIdMatch"?: string; + "dateOfBirthMatch"?: string; + "summaryScore"?: number; + "errorCode"?: number; + "errorMessage"?: string; + + constructor(payload) { + this.firstNameMatch = payload["first_name_match"]; + this.lastNameMatch = payload["last_name_match"]; + this.addressLinesMatch = payload["address_lines_match"]; + this.cityMatch = payload["city_match"]; + this.stateMatch = payload["state_match"]; + this.postalCodeMatch = payload["postal_code_match"]; + this.addressCountryMatch = payload["address_country_match"]; + this.nationalIdMatch = payload["national_id_match"]; + this.dateOfBirthMatch = payload["date_of_birth_match"]; + this.summaryScore = payload["summary_score"]; + this.errorCode = payload["error_code"]; + this.errorMessage = payload["error_message"]; + } +} + + +export class IdentityMatchParameters { + "firstName"?: string; + "lastName"?: string; + "addressLine1"?: string; + "addressLine2"?: string; + "city"?: string; + "state"?: string; + "postalCode"?: string; + "addressCountryCode"?: string; + "nationalId"?: string; + "dateOfBirth"?: string; + + constructor(payload) { + this.firstName = payload["first_name"]; + this.lastName = payload["last_name"]; + this.addressLine1 = payload["address_line1"]; + this.addressLine2 = payload["address_line2"]; + this.city = payload["city"]; + this.state = payload["state"]; + this.postalCode = payload["postal_code"]; + this.addressCountryCode = payload["address_country_code"]; + this.nationalId = payload["national_id"]; + this.dateOfBirth = payload["date_of_birth"]; + } +} + + +export class LastSimSwapInfo { + "lastSimSwapDate"?: Date; + "swappedPeriod"?: string; + "swappedInPeriod"?: boolean; + + constructor(payload) { + this.lastSimSwapDate = payload["last_sim_swap_date"]; + this.swappedPeriod = payload["swapped_period"]; + this.swappedInPeriod = payload["swapped_in_period"]; + } +} + + +export class LineStatusInfo { + "status"?: string; + "errorCode"?: number; + + constructor(payload) { + this.status = payload["status"]; + this.errorCode = payload["error_code"]; + } +} + + +export class LineTypeIntelligenceInfo { + "mobileCountryCode"?: string; + "mobileNetworkCode"?: string; + "carrierName"?: string; + "type"?: string; + "errorCode"?: number; + + constructor(payload) { + this.mobileCountryCode = payload["mobile_country_code"]; + this.mobileNetworkCode = payload["mobile_network_code"]; + this.carrierName = payload["carrier_name"]; + this.type = payload["type"]; + this.errorCode = payload["error_code"]; + } +} + + +export class LookupBatchRequest { + /** + * Unique identifier used to match request with response + */ + "correlationId"?: string; + "phoneNumber": string; + "fields"?: Array<string>; + "countryCode"?: string; + "identityMatch"?: IdentityMatchParameters; + "reassignedNumber"?: ReassignedNumberParameters; + "smsPumpingRisk"?: RiskParameters; + + constructor(payload) { + this.correlationId = payload["correlation_id"]; + this.phoneNumber = payload["phone_number"]; + this.fields = payload["fields"]; + this.countryCode = payload["country_code"]; + this.identityMatch = payload["identity_match"]; + this.reassignedNumber = payload["reassigned_number"]; + this.smsPumpingRisk = payload["sms_pumping_risk"]; + } +} + + +export class LookupBatchResponse { + /** + * Unique identifier used to match request with response + */ + "correlationId"?: string; + /** + * Twilio error code in case that the request to downstream fails + */ + "twilioErrorCode"?: number; + "callingCountryCode"?: string; + "countryCode"?: string; + "phoneNumber"?: string; + "nationalFormat"?: string; + "valid"?: boolean; + "validationErrors"?: Array<string>; + "callerName"?: CallerNameInfo; + "simSwap"?: SimSwapInfo; + "callForwarding"?: CallForwardingInfo; + "lineTypeIntelligence"?: LineTypeIntelligenceInfo; + "lineStatus"?: LineStatusInfo; + "identityMatch"?: IdentityMatchInfo; + "reassignedNumber"?: ReassignedNumberInfo; + "smsPumpingRisk"?: SmsPumpingRiskInfo; + "phoneNumberQualityScore"?: any | null; + "preFill"?: any | null; + + constructor(payload) { + this.correlationId = payload["correlation_id"]; + this.twilioErrorCode = payload["twilio_error_code"]; + this.callingCountryCode = payload["calling_country_code"]; + this.countryCode = payload["country_code"]; + this.phoneNumber = payload["phone_number"]; + this.nationalFormat = payload["national_format"]; + this.valid = payload["valid"]; + this.validationErrors = payload["validation_errors"]; + this.callerName = payload["caller_name"]; + this.simSwap = payload["sim_swap"]; + this.callForwarding = payload["call_forwarding"]; + this.lineTypeIntelligence = payload["line_type_intelligence"]; + this.lineStatus = payload["line_status"]; + this.identityMatch = payload["identity_match"]; + this.reassignedNumber = payload["reassigned_number"]; + this.smsPumpingRisk = payload["sms_pumping_risk"]; + this.phoneNumberQualityScore = payload["phone_number_quality_score"]; + this.preFill = payload["pre_fill"]; + } +} + + +export class LookupRequest { + "phoneNumbers"?: Array<LookupBatchRequest>; + + constructor(payload) { + this.phoneNumbers = payload["phone_numbers"]; + } +} + + +export class ReassignedNumberInfo { + "lastVerifiedDate"?: string; + "isNumberReassigned"?: string; + "errorCode"?: string; + + constructor(payload) { + this.lastVerifiedDate = payload["last_verified_date"]; + this.isNumberReassigned = payload["is_number_reassigned"]; + this.errorCode = payload["error_code"]; + } +} + + +export class ReassignedNumberParameters { + "lastVerifiedDate"?: string; + + constructor(payload) { + this.lastVerifiedDate = payload["last_verified_date"]; + } +} + + +export class RiskParameters { + "partnerSubId"?: string; + + constructor(payload) { + this.partnerSubId = payload["partner_sub_id"]; + } +} + + +export class SimSwapInfo { + "lastSimSwap"?: LastSimSwapInfo; + "carrierName"?: string; + "mobileCountryCode"?: string; + "mobileNetworkCode"?: string; + "errorCode"?: number; + + constructor(payload) { + this.lastSimSwap = payload["last_sim_swap"]; + this.carrierName = payload["carrier_name"]; + this.mobileCountryCode = payload["mobile_country_code"]; + this.mobileNetworkCode = payload["mobile_network_code"]; + this.errorCode = payload["error_code"]; + } +} + + +export class SmsPumpingRiskInfo { + "carrierRiskCategory"?: string; + "numberBlocked"?: boolean; + "numberBlockedDate"?: Date; + "numberBlockedLast3Months"?: boolean; + "smsPumpingRiskScore"?: number; + "errorCode"?: number; + + constructor(payload) { + this.carrierRiskCategory = payload["carrier_risk_category"]; + this.numberBlocked = payload["number_blocked"]; + this.numberBlockedDate = payload["number_blocked_date"]; + this.numberBlockedLast3Months = payload["number_blocked_last_3_months"]; + this.smsPumpingRiskScore = payload["sms_pumping_risk_score"]; + this.errorCode = payload["error_code"]; + } +} + + + +/** + * Options to pass to create a QueryInstance + */ +export interface QueryListInstanceCreateOptions { + /** */ + "lookupRequest"?: LookupRequest; +} + + +export interface QuerySolution { +} + +export interface QueryListInstance { + _version: V2; + _solution: QuerySolution; + _uri: string; + + + + /** + * Create a QueryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryInstance + */ + create(callback?: (error: Error | null, item?: QueryInstance) => any): Promise<QueryInstance>; + /** + * Create a QueryInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryInstance + */ + create(params: LookupRequest, headers?: any, callback?: (error: Error | null, item?: QueryInstance) => any): Promise<QueryInstance>; + + /** + * Create a QueryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<QueryInstance>) => any): Promise<ApiResponse<QueryInstance>>; + /** + * Create a QueryInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed QueryInstance with HTTP metadata + */ + createWithHttpInfo(params: LookupRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<QueryInstance>) => any): Promise<ApiResponse<QueryInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function QueryListInstance(version: V2): QueryListInstance { + const instance = {} as QueryListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/batch/query`; + + instance.create = function create(params?: LookupRequest | ((error: Error | null, items: QueryInstance) => any), headers?: any, callback?: (error: Error | null, items: QueryInstance) => any): Promise<QueryInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<LookupRequest> as LookupRequest; + } else { + params = params || {} as Partial<LookupRequest> as LookupRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new QueryInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: LookupRequest | ((error: Error | null, items: ApiResponse<QueryInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<QueryInstance>) => any): Promise<ApiResponse<QueryInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<LookupRequest> as LookupRequest; + } else { + params = params || {} as Partial<LookupRequest> as LookupRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<QueryResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<QueryInstance> => ({ + ...response, + body: new QueryInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface QueryPayload extends QueryResource {} + +interface QueryResource { + phone_numbers: Array<LookupBatchResponse>; +} + +export class QueryInstance { + + constructor(protected _version: V2, payload: QueryResource) { + + this.phoneNumbers = payload.phone_numbers !== null && payload.phone_numbers !== undefined ? payload.phone_numbers.map( + (payload: any) => new LookupBatchResponse(payload) + ) : null; + + } + + phoneNumbers: Array<LookupBatchResponse>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + phoneNumbers: this.phoneNumbers, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/lookups/v2/rateLimit.ts b/rest/lookups/v2/rateLimit.ts new file mode 100644 index 000000000..95c4b1a79 --- /dev/null +++ b/rest/lookups/v2/rateLimit.ts @@ -0,0 +1,241 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Rate limit response schema + */ +export class RateLimitResponse { + /** + * Limit of requests for the bucket + */ + "field"?: string; + /** + * Limit of requests for the bucket + */ + "limit"?: number; + /** + * Name of the bucket + */ + "bucket"?: string; + /** + * Owner of the rule + */ + "owner"?: string; + /** + * Time to live of the rule + */ + "ttl"?: number; + + constructor(payload) { + this.field = payload["field"]; + this.limit = payload["limit"]; + this.bucket = payload["bucket"]; + this.owner = payload["owner"]; + this.ttl = payload["ttl"]; + } +} + + + +/** + * Options to pass to fetch a RateLimitInstance + */ +export interface RateLimitListInstanceFetchOptions { + /** */ + "fields"?: Array<string>; +} + + +export interface RateLimitSolution { +} + +export interface RateLimitListInstance { + _version: V2; + _solution: RateLimitSolution; + _uri: string; + + + + /** + * Fetch a RateLimitInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance + */ + fetch(callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance>; + /** + * Fetch a RateLimitInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance + */ + fetch(params: RateLimitListInstanceFetchOptions, callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance>; + + /** + * Fetch a RateLimitInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>>; + /** + * Fetch a RateLimitInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance with HTTP metadata + */ + fetchWithHttpInfo(params: RateLimitListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RateLimitListInstance(version: V2): RateLimitListInstance { + const instance = {} as RateLimitListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/RateLimits`; + + instance.fetch = function fetch(params?: RateLimitListInstanceFetchOptions | ((error: Error | null, items: RateLimitInstance) => any), callback?: (error: Error | null, items: RateLimitInstance) => any): Promise<RateLimitInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["fields"] !== undefined) + data["Fields"] = serialize.map(params["fields"], (e: string) => (e)); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new RateLimitInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params?: RateLimitListInstanceFetchOptions | ((error: Error | null, items: ApiResponse<RateLimitInstance>) => any), callback?: (error: Error | null, items: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["fields"] !== undefined) + data["Fields"] = serialize.map(params["fields"], (e: string) => (e)); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RateLimitResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RateLimitInstance> => ({ + ...response, + body: new RateLimitInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface RateLimitPayload extends RateLimitResource {} + +interface RateLimitResource { + rate_limits: Array<RateLimitResponse>; +} + +export class RateLimitInstance { + + constructor(protected _version: V2, payload: RateLimitResource) { + + this.rateLimits = payload.rate_limits !== null && payload.rate_limits !== undefined ? payload.rate_limits.map( + (payload: any) => new RateLimitResponse(payload) + ) : null; + + } + + rateLimits: Array<RateLimitResponse>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + rateLimits: this.rateLimits, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/marketplace/V1.ts b/rest/marketplace/V1.ts new file mode 100644 index 000000000..8acd88afc --- /dev/null +++ b/rest/marketplace/V1.ts @@ -0,0 +1,74 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Marketplace + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import MarketplaceBase from "../MarketplaceBase"; +import Version from "../../base/Version"; +import { AvailableAddOnListInstance } from "./v1/availableAddOn"; +import { InstalledAddOnListInstance } from "./v1/installedAddOn"; +import { ModuleDataListInstance } from "./v1/moduleData"; +import { ModuleDataManagementListInstance } from "./v1/moduleDataManagement"; +import { ReferralConversionListInstance } from "./v1/referralConversion"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Marketplace + * + * @param domain - The Twilio (Twilio.Marketplace) domain + */ + constructor(domain: MarketplaceBase) { + super(domain, "v1"); + } + + /** availableAddOns - { Twilio.Marketplace.V1.AvailableAddOnListInstance } resource */ + protected _availableAddOns?: AvailableAddOnListInstance; + /** installedAddOns - { Twilio.Marketplace.V1.InstalledAddOnListInstance } resource */ + protected _installedAddOns?: InstalledAddOnListInstance; + /** moduleData - { Twilio.Marketplace.V1.ModuleDataListInstance } resource */ + protected _moduleData?: ModuleDataListInstance; + /** moduleDataManagement - { Twilio.Marketplace.V1.ModuleDataManagementListInstance } resource */ + protected _moduleDataManagement?: ModuleDataManagementListInstance; + /** referralConversion - { Twilio.Marketplace.V1.ReferralConversionListInstance } resource */ + protected _referralConversion?: ReferralConversionListInstance; + + /** Getter for availableAddOns resource */ + get availableAddOns(): AvailableAddOnListInstance { + this._availableAddOns = this._availableAddOns || AvailableAddOnListInstance(this); + return this._availableAddOns; + } + + /** Getter for installedAddOns resource */ + get installedAddOns(): InstalledAddOnListInstance { + this._installedAddOns = this._installedAddOns || InstalledAddOnListInstance(this); + return this._installedAddOns; + } + + /** Getter for moduleData resource */ + get moduleData(): ModuleDataListInstance { + this._moduleData = this._moduleData || ModuleDataListInstance(this); + return this._moduleData; + } + + /** Getter for moduleDataManagement resource */ + get moduleDataManagement(): ModuleDataManagementListInstance { + this._moduleDataManagement = this._moduleDataManagement || ModuleDataManagementListInstance(this); + return this._moduleDataManagement; + } + + /** Getter for referralConversion resource */ + get referralConversion(): ReferralConversionListInstance { + this._referralConversion = this._referralConversion || ReferralConversionListInstance(this); + return this._referralConversion; + } + +} diff --git a/rest/marketplace/v1/availableAddOn.ts b/rest/marketplace/v1/availableAddOn.ts new file mode 100644 index 000000000..0ab1d6523 --- /dev/null +++ b/rest/marketplace/v1/availableAddOn.ts @@ -0,0 +1,573 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Marketplace + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { AvailableAddOnExtensionListInstance } from "./availableAddOn/availableAddOnExtension"; + + + + +/** + * Options to pass to each + */ +export interface AvailableAddOnListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AvailableAddOnInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AvailableAddOnListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AvailableAddOnListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AvailableAddOnContext { + extensions: AvailableAddOnExtensionListInstance; + + /** + * Fetch a AvailableAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnInstance + */ + fetch(callback?: (error: Error | null, item?: AvailableAddOnInstance) => any): Promise<AvailableAddOnInstance> + + /** + * Fetch a AvailableAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnInstance>) => any): Promise<ApiResponse<AvailableAddOnInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AvailableAddOnContextSolution { + "sid": string; +} + +export class AvailableAddOnContextImpl implements AvailableAddOnContext { + protected _solution: AvailableAddOnContextSolution; + protected _uri: string; + + protected _extensions?: AvailableAddOnExtensionListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/AvailableAddOns/${sid}`; + } + + get extensions(): AvailableAddOnExtensionListInstance { + this._extensions = this._extensions || AvailableAddOnExtensionListInstance(this._version, this._solution.sid); + return this._extensions; + } + + fetch(callback?: (error: Error | null, item?: AvailableAddOnInstance) => any): Promise<AvailableAddOnInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AvailableAddOnInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnInstance>) => any): Promise<ApiResponse<AvailableAddOnInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AvailableAddOnResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AvailableAddOnInstance> => ({ + ...response, + body: new AvailableAddOnInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AvailableAddOnPayload extends TwilioResponsePayload { + available_add_ons: AvailableAddOnResource[]; +} + +interface AvailableAddOnResource { + sid: string; + friendly_name: string; + description: string; + pricing_type: string; + configuration_schema: Record<string, object>; + url: string; + links: Record<string, string>; +} + +export class AvailableAddOnInstance { + protected _solution: AvailableAddOnContextSolution; + protected _context?: AvailableAddOnContext; + + constructor(protected _version: V1, payload: AvailableAddOnResource, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.pricingType = (payload.pricing_type); + this.configurationSchema = (payload.configuration_schema); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the AvailableAddOn resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * A short description of the Add-on\'s functionality. + */ + description: string; + /** + * How customers are charged for using this Add-on. + */ + pricingType: string; + /** + * The JSON object with the configuration that must be provided when installing a given Add-on. + */ + configurationSchema: Record<string, object>; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): AvailableAddOnContext { + this._context = this._context || new AvailableAddOnContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a AvailableAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnInstance + */ + fetch(callback?: (error: Error | null, item?: AvailableAddOnInstance) => any): Promise<AvailableAddOnInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AvailableAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnInstance>) => any): Promise<ApiResponse<AvailableAddOnInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the extensions. + */ + extensions(): AvailableAddOnExtensionListInstance { + return this._proxy.extensions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + description: this.description, + pricingType: this.pricingType, + configurationSchema: this.configurationSchema, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AvailableAddOnSolution { +} + +export interface AvailableAddOnListInstance { + _version: V1; + _solution: AvailableAddOnSolution; + _uri: string; + + (sid: string, ): AvailableAddOnContext; + get(sid: string, ): AvailableAddOnContext; + + + + + + /** + * Streams AvailableAddOnInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AvailableAddOnInstance, done: (err?: Error) => void) => void): void; + each(params: AvailableAddOnListInstanceEachOptions, callback?: (item: AvailableAddOnInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AvailableAddOnInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AvailableAddOnInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AvailableAddOnListInstanceEachOptions, callback?: (item: AvailableAddOnInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AvailableAddOnInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AvailableAddOnPage) => any): Promise<AvailableAddOnPage>; + /** + * Retrieve a single target page of AvailableAddOnInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnPage>) => any): Promise<ApiResponse<AvailableAddOnPage>>; + /** + * Lists AvailableAddOnInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AvailableAddOnInstance[]) => any): Promise<AvailableAddOnInstance[]>; + list(params: AvailableAddOnListInstanceOptions, callback?: (error: Error | null, items: AvailableAddOnInstance[]) => any): Promise<AvailableAddOnInstance[]>; + /** + * Lists AvailableAddOnInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AvailableAddOnInstance[]>) => any): Promise<ApiResponse<AvailableAddOnInstance[]>>; + listWithHttpInfo(params: AvailableAddOnListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnInstance[]>) => any): Promise<ApiResponse<AvailableAddOnInstance[]>>; + /** + * Retrieve a single page of AvailableAddOnInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AvailableAddOnPage) => any): Promise<AvailableAddOnPage>; + page(params: AvailableAddOnListInstancePageOptions, callback?: (error: Error | null, items: AvailableAddOnPage) => any): Promise<AvailableAddOnPage>; + /** + * Retrieve a single page of AvailableAddOnInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AvailableAddOnPage>) => any): Promise<ApiResponse<AvailableAddOnPage>>; + pageWithHttpInfo(params: AvailableAddOnListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnPage>) => any): Promise<ApiResponse<AvailableAddOnPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AvailableAddOnListInstance(version: V1): AvailableAddOnListInstance { + const instance = ((sid, ) => instance.get(sid, )) as AvailableAddOnListInstance; + + instance.get = function get(sid, ): AvailableAddOnContext { + return new AvailableAddOnContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/AvailableAddOns`; + + instance.page = function page(params?: AvailableAddOnListInstancePageOptions | ((error: Error | null, items: AvailableAddOnPage) => any), callback?: (error: Error | null, items: AvailableAddOnPage) => any): Promise<AvailableAddOnPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AvailableAddOnPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AvailableAddOnPage) => any): Promise<AvailableAddOnPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AvailableAddOnPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AvailableAddOnListInstancePageOptions | ((error: Error | null, items: ApiResponse<AvailableAddOnPage>) => any), callback?: (error: Error | null, items: ApiResponse<AvailableAddOnPage>) => any): Promise<ApiResponse<AvailableAddOnPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AvailableAddOnPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AvailableAddOnPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AvailableAddOnPage>) => any): Promise<ApiResponse<AvailableAddOnPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AvailableAddOnPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AvailableAddOnPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AvailableAddOnPage extends Page<V1, AvailableAddOnPayload, AvailableAddOnResource, AvailableAddOnInstance> { +/** +* Initialize the AvailableAddOnPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: AvailableAddOnSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AvailableAddOnInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AvailableAddOnResource): AvailableAddOnInstance { + + return new AvailableAddOnInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/marketplace/v1/availableAddOn/availableAddOnExtension.ts b/rest/marketplace/v1/availableAddOn/availableAddOnExtension.ts new file mode 100644 index 000000000..b9a2de8dc --- /dev/null +++ b/rest/marketplace/v1/availableAddOn/availableAddOnExtension.ts @@ -0,0 +1,562 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Marketplace + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface AvailableAddOnExtensionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AvailableAddOnExtensionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AvailableAddOnExtensionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AvailableAddOnExtensionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AvailableAddOnExtensionContext { + + /** + * Fetch a AvailableAddOnExtensionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnExtensionInstance + */ + fetch(callback?: (error: Error | null, item?: AvailableAddOnExtensionInstance) => any): Promise<AvailableAddOnExtensionInstance> + + /** + * Fetch a AvailableAddOnExtensionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnExtensionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnExtensionInstance>) => any): Promise<ApiResponse<AvailableAddOnExtensionInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AvailableAddOnExtensionContextSolution { + "availableAddOnSid": string; + "sid": string; +} + +export class AvailableAddOnExtensionContextImpl implements AvailableAddOnExtensionContext { + protected _solution: AvailableAddOnExtensionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, availableAddOnSid: string, sid: string) { + if (!isValidPathParam(availableAddOnSid)) { + throw new Error('Parameter \'availableAddOnSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { availableAddOnSid, sid, }; + this._uri = `/AvailableAddOns/${availableAddOnSid}/Extensions/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: AvailableAddOnExtensionInstance) => any): Promise<AvailableAddOnExtensionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AvailableAddOnExtensionInstance(operationVersion, payload, instance._solution.availableAddOnSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnExtensionInstance>) => any): Promise<ApiResponse<AvailableAddOnExtensionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AvailableAddOnExtensionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AvailableAddOnExtensionInstance> => ({ + ...response, + body: new AvailableAddOnExtensionInstance(operationVersion, response.body, instance._solution.availableAddOnSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AvailableAddOnExtensionPayload extends TwilioResponsePayload { + extensions: AvailableAddOnExtensionResource[]; +} + +interface AvailableAddOnExtensionResource { + sid: string; + available_add_on_sid: string; + friendly_name: string; + product_name: string; + unique_name: string; + url: string; +} + +export class AvailableAddOnExtensionInstance { + protected _solution: AvailableAddOnExtensionContextSolution; + protected _context?: AvailableAddOnExtensionContext; + + constructor(protected _version: V1, payload: AvailableAddOnExtensionResource, availableAddOnSid: string, sid?: string) { + + this.sid = (payload.sid); + this.availableAddOnSid = (payload.available_add_on_sid); + this.friendlyName = (payload.friendly_name); + this.productName = (payload.product_name); + this.uniqueName = (payload.unique_name); + this.url = (payload.url); + + this._solution = { availableAddOnSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the AvailableAddOnExtension resource. + */ + sid: string; + /** + * The SID of the AvailableAddOn resource to which this extension applies. + */ + availableAddOnSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The name of the Product this Extension is used within. + */ + productName: string; + /** + * An application-defined string that uniquely identifies the resource. + */ + uniqueName: string; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): AvailableAddOnExtensionContext { + this._context = this._context || new AvailableAddOnExtensionContextImpl(this._version, this._solution.availableAddOnSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a AvailableAddOnExtensionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnExtensionInstance + */ + fetch(callback?: (error: Error | null, item?: AvailableAddOnExtensionInstance) => any): Promise<AvailableAddOnExtensionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AvailableAddOnExtensionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnExtensionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnExtensionInstance>) => any): Promise<ApiResponse<AvailableAddOnExtensionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + availableAddOnSid: this.availableAddOnSid, + friendlyName: this.friendlyName, + productName: this.productName, + uniqueName: this.uniqueName, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AvailableAddOnExtensionSolution { + availableAddOnSid: string; +} + +export interface AvailableAddOnExtensionListInstance { + _version: V1; + _solution: AvailableAddOnExtensionSolution; + _uri: string; + + (sid: string, ): AvailableAddOnExtensionContext; + get(sid: string, ): AvailableAddOnExtensionContext; + + + + + + /** + * Streams AvailableAddOnExtensionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AvailableAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + each(params: AvailableAddOnExtensionListInstanceEachOptions, callback?: (item: AvailableAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AvailableAddOnExtensionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AvailableAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AvailableAddOnExtensionListInstanceEachOptions, callback?: (item: AvailableAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AvailableAddOnExtensionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AvailableAddOnExtensionPage) => any): Promise<AvailableAddOnExtensionPage>; + /** + * Retrieve a single target page of AvailableAddOnExtensionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionPage>) => any): Promise<ApiResponse<AvailableAddOnExtensionPage>>; + /** + * Lists AvailableAddOnExtensionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AvailableAddOnExtensionInstance[]) => any): Promise<AvailableAddOnExtensionInstance[]>; + list(params: AvailableAddOnExtensionListInstanceOptions, callback?: (error: Error | null, items: AvailableAddOnExtensionInstance[]) => any): Promise<AvailableAddOnExtensionInstance[]>; + /** + * Lists AvailableAddOnExtensionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionInstance[]>) => any): Promise<ApiResponse<AvailableAddOnExtensionInstance[]>>; + listWithHttpInfo(params: AvailableAddOnExtensionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionInstance[]>) => any): Promise<ApiResponse<AvailableAddOnExtensionInstance[]>>; + /** + * Retrieve a single page of AvailableAddOnExtensionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AvailableAddOnExtensionPage) => any): Promise<AvailableAddOnExtensionPage>; + page(params: AvailableAddOnExtensionListInstancePageOptions, callback?: (error: Error | null, items: AvailableAddOnExtensionPage) => any): Promise<AvailableAddOnExtensionPage>; + /** + * Retrieve a single page of AvailableAddOnExtensionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionPage>) => any): Promise<ApiResponse<AvailableAddOnExtensionPage>>; + pageWithHttpInfo(params: AvailableAddOnExtensionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionPage>) => any): Promise<ApiResponse<AvailableAddOnExtensionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AvailableAddOnExtensionListInstance(version: V1, availableAddOnSid: string): AvailableAddOnExtensionListInstance { + if (!isValidPathParam(availableAddOnSid)) { + throw new Error('Parameter \'availableAddOnSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as AvailableAddOnExtensionListInstance; + + instance.get = function get(sid, ): AvailableAddOnExtensionContext { + return new AvailableAddOnExtensionContextImpl(version, availableAddOnSid, sid); + } + + instance._version = version; + instance._solution = { availableAddOnSid, }; + instance._uri = `/AvailableAddOns/${availableAddOnSid}/Extensions`; + + instance.page = function page(params?: AvailableAddOnExtensionListInstancePageOptions | ((error: Error | null, items: AvailableAddOnExtensionPage) => any), callback?: (error: Error | null, items: AvailableAddOnExtensionPage) => any): Promise<AvailableAddOnExtensionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AvailableAddOnExtensionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AvailableAddOnExtensionPage) => any): Promise<AvailableAddOnExtensionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AvailableAddOnExtensionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AvailableAddOnExtensionListInstancePageOptions | ((error: Error | null, items: ApiResponse<AvailableAddOnExtensionPage>) => any), callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionPage>) => any): Promise<ApiResponse<AvailableAddOnExtensionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AvailableAddOnExtensionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AvailableAddOnExtensionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AvailableAddOnExtensionPage>) => any): Promise<ApiResponse<AvailableAddOnExtensionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AvailableAddOnExtensionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AvailableAddOnExtensionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AvailableAddOnExtensionPage extends Page<V1, AvailableAddOnExtensionPayload, AvailableAddOnExtensionResource, AvailableAddOnExtensionInstance> { +/** +* Initialize the AvailableAddOnExtensionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: AvailableAddOnExtensionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AvailableAddOnExtensionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AvailableAddOnExtensionResource): AvailableAddOnExtensionInstance { + + return new AvailableAddOnExtensionInstance( + this._version, + payload, + this._solution.availableAddOnSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/marketplace/v1/installedAddOn.ts b/rest/marketplace/v1/installedAddOn.ts new file mode 100644 index 000000000..40d1d4061 --- /dev/null +++ b/rest/marketplace/v1/installedAddOn.ts @@ -0,0 +1,979 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Marketplace + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { InstalledAddOnExtensionListInstance } from "./installedAddOn/installedAddOnExtension"; +import { InstalledAddOnUsageListInstance } from "./installedAddOn/installedAddOnUsage"; + + + + + +/** + * Options to pass to update a InstalledAddOnInstance + */ +export interface InstalledAddOnContextUpdateOptions { + /** Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured */ + "configuration"?: any; + /** An application-defined string that uniquely identifies the resource. This value must be unique within the Account. */ + "uniqueName"?: string; +} + +/** + * Options to pass to create a InstalledAddOnInstance + */ +export interface InstalledAddOnListInstanceCreateOptions { + /** The SID of the AvaliableAddOn to install. */ + "availableAddOnSid": string; + /** Whether the Terms of Service were accepted. */ + "acceptTermsOfService": boolean; + /** The JSON object that represents the configuration of the new Add-on being installed. */ + "configuration"?: any; + /** An application-defined string that uniquely identifies the resource. This value must be unique within the Account. */ + "uniqueName"?: string; +} + +/** + * Options to pass to each + */ +export interface InstalledAddOnListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InstalledAddOnListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InstalledAddOnListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InstalledAddOnContext { + extensions: InstalledAddOnExtensionListInstance; + usage: InstalledAddOnUsageListInstance; + + /** + * Remove a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + fetch(callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> + + /** + * Fetch a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> + + /** + * Update a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + update(callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; + /** + * Update a InstalledAddOnInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + update(params: InstalledAddOnContextUpdateOptions, callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; + + /** + * Update a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>>; + /** + * Update a InstalledAddOnInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + updateWithHttpInfo(params: InstalledAddOnContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InstalledAddOnContextSolution { + "sid": string; +} + +export class InstalledAddOnContextImpl implements InstalledAddOnContext { + protected _solution: InstalledAddOnContextSolution; + protected _uri: string; + + protected _extensions?: InstalledAddOnExtensionListInstance; + protected _usage?: InstalledAddOnUsageListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/InstalledAddOns/${sid}`; + } + + get extensions(): InstalledAddOnExtensionListInstance { + this._extensions = this._extensions || InstalledAddOnExtensionListInstance(this._version, this._solution.sid); + return this._extensions; + } + + get usage(): InstalledAddOnUsageListInstance { + this._usage = this._usage || InstalledAddOnUsageListInstance(this._version, this._solution.sid); + return this._usage; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<InstalledAddOnResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<InstalledAddOnInstance> => ({ + ...response, + body: new InstalledAddOnInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: InstalledAddOnContextUpdateOptions | ((error: Error | null, item?: InstalledAddOnInstance) => any),callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: InstalledAddOnContextUpdateOptions | ((error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<InstalledAddOnResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<InstalledAddOnInstance> => ({ + ...response, + body: new InstalledAddOnInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InstalledAddOnPayload extends TwilioResponsePayload { + installed_add_ons: InstalledAddOnResource[]; +} + +interface InstalledAddOnResource { + sid: string; + account_sid: string; + friendly_name: string; + description: string; + configuration: Record<string, object>; + unique_name: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class InstalledAddOnInstance { + protected _solution: InstalledAddOnContextSolution; + protected _context?: InstalledAddOnContext; + + constructor(protected _version: V1, payload: InstalledAddOnResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.configuration = (payload.configuration); + this.uniqueName = (payload.unique_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the InstalledAddOn resource. This Sid can also be found in the Console on that specific Add-ons page as the \'Available Add-on Sid\'. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the InstalledAddOn resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * A short description of the Add-on\'s functionality. + */ + description: string; + /** + * The JSON object that represents the current configuration of installed Add-on. + */ + configuration: Record<string, object>; + /** + * An application-defined string that uniquely identifies the resource. + */ + uniqueName: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): InstalledAddOnContext { + this._context = this._context || new InstalledAddOnContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + fetch(callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + update(callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; + /** + * Update a InstalledAddOnInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + update(params: InstalledAddOnContextUpdateOptions, callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; + + update(params?: any, callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>>; + /** + * Update a InstalledAddOnInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + updateWithHttpInfo(params: InstalledAddOnContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the extensions. + */ + extensions(): InstalledAddOnExtensionListInstance { + return this._proxy.extensions; + } + + /** + * Access the usage. + */ + usage(): InstalledAddOnUsageListInstance { + return this._proxy.usage; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + description: this.description, + configuration: this.configuration, + uniqueName: this.uniqueName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InstalledAddOnSolution { +} + +export interface InstalledAddOnListInstance { + _version: V1; + _solution: InstalledAddOnSolution; + _uri: string; + + (sid: string, ): InstalledAddOnContext; + get(sid: string, ): InstalledAddOnContext; + + + + + + + + + /** + * Create a InstalledAddOnInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + create(params: InstalledAddOnListInstanceCreateOptions, callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; + + /** + * Create a InstalledAddOnInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + createWithHttpInfo(params: InstalledAddOnListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>>; + + + + + /** + * Streams InstalledAddOnInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void): void; + each(params: InstalledAddOnListInstanceEachOptions, callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InstalledAddOnInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InstalledAddOnListInstanceEachOptions, callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InstalledAddOnInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage>; + /** + * Retrieve a single target page of InstalledAddOnInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnPage>) => any): Promise<ApiResponse<InstalledAddOnPage>>; + /** + * Lists InstalledAddOnInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InstalledAddOnInstance[]) => any): Promise<InstalledAddOnInstance[]>; + list(params: InstalledAddOnListInstanceOptions, callback?: (error: Error | null, items: InstalledAddOnInstance[]) => any): Promise<InstalledAddOnInstance[]>; + /** + * Lists InstalledAddOnInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<InstalledAddOnInstance[]>) => any): Promise<ApiResponse<InstalledAddOnInstance[]>>; + listWithHttpInfo(params: InstalledAddOnListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnInstance[]>) => any): Promise<ApiResponse<InstalledAddOnInstance[]>>; + /** + * Retrieve a single page of InstalledAddOnInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage>; + page(params: InstalledAddOnListInstancePageOptions, callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage>; + /** + * Retrieve a single page of InstalledAddOnInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<InstalledAddOnPage>) => any): Promise<ApiResponse<InstalledAddOnPage>>; + pageWithHttpInfo(params: InstalledAddOnListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnPage>) => any): Promise<ApiResponse<InstalledAddOnPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InstalledAddOnListInstance(version: V1): InstalledAddOnListInstance { + const instance = ((sid, ) => instance.get(sid, )) as InstalledAddOnListInstance; + + instance.get = function get(sid, ): InstalledAddOnContext { + return new InstalledAddOnContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/InstalledAddOns`; + + instance.create = function create(params: InstalledAddOnListInstanceCreateOptions, callback?: (error: Error | null, items: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["availableAddOnSid"] === null || params["availableAddOnSid"] === undefined) { + throw new Error('Required parameter "params[\'availableAddOnSid\']" missing.'); + } + + if (params["acceptTermsOfService"] === null || params["acceptTermsOfService"] === undefined) { + throw new Error('Required parameter "params[\'acceptTermsOfService\']" missing.'); + } + + let data: any = {}; + + + + data["AvailableAddOnSid"] = params["availableAddOnSid"]; + + data["AcceptTermsOfService"] = serialize.bool(params["acceptTermsOfService"]); + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InstalledAddOnListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["availableAddOnSid"] === null || params["availableAddOnSid"] === undefined) { + throw new Error('Required parameter "params[\'availableAddOnSid\']" missing.'); + } + + if (params["acceptTermsOfService"] === null || params["acceptTermsOfService"] === undefined) { + throw new Error('Required parameter "params[\'acceptTermsOfService\']" missing.'); + } + + let data: any = {}; + + + + data["AvailableAddOnSid"] = params["availableAddOnSid"]; + + data["AcceptTermsOfService"] = serialize.bool(params["acceptTermsOfService"]); + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<InstalledAddOnResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<InstalledAddOnInstance> => ({ + ...response, + body: new InstalledAddOnInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InstalledAddOnListInstancePageOptions | ((error: Error | null, items: InstalledAddOnPage) => any), callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InstalledAddOnPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InstalledAddOnPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InstalledAddOnListInstancePageOptions | ((error: Error | null, items: ApiResponse<InstalledAddOnPage>) => any), callback?: (error: Error | null, items: ApiResponse<InstalledAddOnPage>) => any): Promise<ApiResponse<InstalledAddOnPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<InstalledAddOnPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InstalledAddOnPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<InstalledAddOnPage>) => any): Promise<ApiResponse<InstalledAddOnPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<InstalledAddOnPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InstalledAddOnPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InstalledAddOnPage extends Page<V1, InstalledAddOnPayload, InstalledAddOnResource, InstalledAddOnInstance> { +/** +* Initialize the InstalledAddOnPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: InstalledAddOnSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InstalledAddOnInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InstalledAddOnResource): InstalledAddOnInstance { + + return new InstalledAddOnInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/marketplace/v1/installedAddOn/installedAddOnExtension.ts b/rest/marketplace/v1/installedAddOn/installedAddOnExtension.ts new file mode 100644 index 000000000..d7d7d18d3 --- /dev/null +++ b/rest/marketplace/v1/installedAddOn/installedAddOnExtension.ts @@ -0,0 +1,700 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Marketplace + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a InstalledAddOnExtensionInstance + */ +export interface InstalledAddOnExtensionContextUpdateOptions { + /** Whether the Extension should be invoked. */ + "enabled": boolean; +} + +/** + * Options to pass to each + */ +export interface InstalledAddOnExtensionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InstalledAddOnExtensionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InstalledAddOnExtensionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InstalledAddOnExtensionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InstalledAddOnExtensionContext { + + /** + * Fetch a InstalledAddOnExtensionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance + */ + fetch(callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance> + + /** + * Fetch a InstalledAddOnExtensionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>> + + /** + * Update a InstalledAddOnExtensionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance + */ + update(params: InstalledAddOnExtensionContextUpdateOptions, callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance>; + + /** + * Update a InstalledAddOnExtensionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance with HTTP metadata + */ + updateWithHttpInfo(params: InstalledAddOnExtensionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InstalledAddOnExtensionContextSolution { + "installedAddOnSid": string; + "sid": string; +} + +export class InstalledAddOnExtensionContextImpl implements InstalledAddOnExtensionContext { + protected _solution: InstalledAddOnExtensionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, installedAddOnSid: string, sid: string) { + if (!isValidPathParam(installedAddOnSid)) { + throw new Error('Parameter \'installedAddOnSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { installedAddOnSid, sid, }; + this._uri = `/InstalledAddOns/${installedAddOnSid}/Extensions/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnExtensionInstance(operationVersion, payload, instance._solution.installedAddOnSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<InstalledAddOnExtensionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<InstalledAddOnExtensionInstance> => ({ + ...response, + body: new InstalledAddOnExtensionInstance(operationVersion, response.body, instance._solution.installedAddOnSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: InstalledAddOnExtensionContextUpdateOptions,callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["enabled"] === null || params["enabled"] === undefined) { + throw new Error('Required parameter "params[\'enabled\']" missing.'); + } + + let data: any = {}; + + + + data["Enabled"] = serialize.bool(params["enabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnExtensionInstance(operationVersion, payload, instance._solution.installedAddOnSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: InstalledAddOnExtensionContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["enabled"] === null || params["enabled"] === undefined) { + throw new Error('Required parameter "params[\'enabled\']" missing.'); + } + + let data: any = {}; + + + + data["Enabled"] = serialize.bool(params["enabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<InstalledAddOnExtensionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<InstalledAddOnExtensionInstance> => ({ + ...response, + body: new InstalledAddOnExtensionInstance(operationVersion, response.body, instance._solution.installedAddOnSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InstalledAddOnExtensionPayload extends TwilioResponsePayload { + extensions: InstalledAddOnExtensionResource[]; +} + +interface InstalledAddOnExtensionResource { + sid: string; + installed_add_on_sid: string; + friendly_name: string; + product_name: string; + unique_name: string; + enabled: boolean; + url: string; +} + +export class InstalledAddOnExtensionInstance { + protected _solution: InstalledAddOnExtensionContextSolution; + protected _context?: InstalledAddOnExtensionContext; + + constructor(protected _version: V1, payload: InstalledAddOnExtensionResource, installedAddOnSid: string, sid?: string) { + + this.sid = (payload.sid); + this.installedAddOnSid = (payload.installed_add_on_sid); + this.friendlyName = (payload.friendly_name); + this.productName = (payload.product_name); + this.uniqueName = (payload.unique_name); + this.enabled = (payload.enabled); + this.url = (payload.url); + + this._solution = { installedAddOnSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the InstalledAddOn Extension resource. + */ + sid: string; + /** + * The SID of the InstalledAddOn resource to which this extension applies. + */ + installedAddOnSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The name of the Product this Extension is used within. + */ + productName: string; + /** + * An application-defined string that uniquely identifies the resource. + */ + uniqueName: string; + /** + * Whether the Extension will be invoked. + */ + enabled: boolean; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): InstalledAddOnExtensionContext { + this._context = this._context || new InstalledAddOnExtensionContextImpl(this._version, this._solution.installedAddOnSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a InstalledAddOnExtensionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance + */ + fetch(callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InstalledAddOnExtensionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a InstalledAddOnExtensionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance + */ + update(params: InstalledAddOnExtensionContextUpdateOptions, callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance>; + + update(params?: any, callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a InstalledAddOnExtensionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance with HTTP metadata + */ + updateWithHttpInfo(params: InstalledAddOnExtensionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + installedAddOnSid: this.installedAddOnSid, + friendlyName: this.friendlyName, + productName: this.productName, + uniqueName: this.uniqueName, + enabled: this.enabled, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InstalledAddOnExtensionSolution { + installedAddOnSid: string; +} + +export interface InstalledAddOnExtensionListInstance { + _version: V1; + _solution: InstalledAddOnExtensionSolution; + _uri: string; + + (sid: string, ): InstalledAddOnExtensionContext; + get(sid: string, ): InstalledAddOnExtensionContext; + + + + + + + + /** + * Streams InstalledAddOnExtensionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InstalledAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + each(params: InstalledAddOnExtensionListInstanceEachOptions, callback?: (item: InstalledAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InstalledAddOnExtensionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InstalledAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InstalledAddOnExtensionListInstanceEachOptions, callback?: (item: InstalledAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InstalledAddOnExtensionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InstalledAddOnExtensionPage) => any): Promise<InstalledAddOnExtensionPage>; + /** + * Retrieve a single target page of InstalledAddOnExtensionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionPage>) => any): Promise<ApiResponse<InstalledAddOnExtensionPage>>; + /** + * Lists InstalledAddOnExtensionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InstalledAddOnExtensionInstance[]) => any): Promise<InstalledAddOnExtensionInstance[]>; + list(params: InstalledAddOnExtensionListInstanceOptions, callback?: (error: Error | null, items: InstalledAddOnExtensionInstance[]) => any): Promise<InstalledAddOnExtensionInstance[]>; + /** + * Lists InstalledAddOnExtensionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionInstance[]>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance[]>>; + listWithHttpInfo(params: InstalledAddOnExtensionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionInstance[]>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance[]>>; + /** + * Retrieve a single page of InstalledAddOnExtensionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InstalledAddOnExtensionPage) => any): Promise<InstalledAddOnExtensionPage>; + page(params: InstalledAddOnExtensionListInstancePageOptions, callback?: (error: Error | null, items: InstalledAddOnExtensionPage) => any): Promise<InstalledAddOnExtensionPage>; + /** + * Retrieve a single page of InstalledAddOnExtensionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionPage>) => any): Promise<ApiResponse<InstalledAddOnExtensionPage>>; + pageWithHttpInfo(params: InstalledAddOnExtensionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionPage>) => any): Promise<ApiResponse<InstalledAddOnExtensionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InstalledAddOnExtensionListInstance(version: V1, installedAddOnSid: string): InstalledAddOnExtensionListInstance { + if (!isValidPathParam(installedAddOnSid)) { + throw new Error('Parameter \'installedAddOnSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as InstalledAddOnExtensionListInstance; + + instance.get = function get(sid, ): InstalledAddOnExtensionContext { + return new InstalledAddOnExtensionContextImpl(version, installedAddOnSid, sid); + } + + instance._version = version; + instance._solution = { installedAddOnSid, }; + instance._uri = `/InstalledAddOns/${installedAddOnSid}/Extensions`; + + instance.page = function page(params?: InstalledAddOnExtensionListInstancePageOptions | ((error: Error | null, items: InstalledAddOnExtensionPage) => any), callback?: (error: Error | null, items: InstalledAddOnExtensionPage) => any): Promise<InstalledAddOnExtensionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InstalledAddOnExtensionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InstalledAddOnExtensionPage) => any): Promise<InstalledAddOnExtensionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InstalledAddOnExtensionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InstalledAddOnExtensionListInstancePageOptions | ((error: Error | null, items: ApiResponse<InstalledAddOnExtensionPage>) => any), callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionPage>) => any): Promise<ApiResponse<InstalledAddOnExtensionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<InstalledAddOnExtensionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InstalledAddOnExtensionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<InstalledAddOnExtensionPage>) => any): Promise<ApiResponse<InstalledAddOnExtensionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<InstalledAddOnExtensionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InstalledAddOnExtensionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InstalledAddOnExtensionPage extends Page<V1, InstalledAddOnExtensionPayload, InstalledAddOnExtensionResource, InstalledAddOnExtensionInstance> { +/** +* Initialize the InstalledAddOnExtensionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: InstalledAddOnExtensionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InstalledAddOnExtensionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InstalledAddOnExtensionResource): InstalledAddOnExtensionInstance { + + return new InstalledAddOnExtensionInstance( + this._version, + payload, + this._solution.installedAddOnSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/marketplace/v1/installedAddOn/installedAddOnUsage.ts b/rest/marketplace/v1/installedAddOn/installedAddOnUsage.ts new file mode 100644 index 000000000..a0100fbed --- /dev/null +++ b/rest/marketplace/v1/installedAddOn/installedAddOnUsage.ts @@ -0,0 +1,236 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Marketplace + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class MarketplaceV1InstalledAddOnInstalledAddOnUsage { + /** + * Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + */ + "totalSubmitted"?: number; + "billableItems": Array<MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems>; + + constructor(payload) { + this.totalSubmitted = payload["total_submitted"]; + this.billableItems = payload["billable_items"]; + } +} + + +export class MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems { + /** + * Total amount in local currency that was billed for this Billing Item. Can be any floating number greater than 0. + */ + "quantity": number; + /** + * BillingSid to use for billing. + */ + "sid": string; + /** + * Whether the billing event was successfully generated for this Billable Item. + */ + "submitted"?: boolean; + + constructor(payload) { + this.quantity = payload["quantity"]; + this.sid = payload["sid"]; + this.submitted = payload["submitted"]; + } +} + + + +/** + * Options to pass to create a InstalledAddOnUsageInstance + */ +export interface InstalledAddOnUsageListInstanceCreateOptions { + /** */ + "marketplaceV1InstalledAddOnInstalledAddOnUsage": MarketplaceV1InstalledAddOnInstalledAddOnUsage; +} + + +export interface InstalledAddOnUsageSolution { + installedAddOnSid: string; +} + +export interface InstalledAddOnUsageListInstance { + _version: V1; + _solution: InstalledAddOnUsageSolution; + _uri: string; + + + + /** + * Create a InstalledAddOnUsageInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnUsageInstance + */ + create(params: MarketplaceV1InstalledAddOnInstalledAddOnUsage, headers?: any, callback?: (error: Error | null, item?: InstalledAddOnUsageInstance) => any): Promise<InstalledAddOnUsageInstance>; + + /** + * Create a InstalledAddOnUsageInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnUsageInstance with HTTP metadata + */ + createWithHttpInfo(params: MarketplaceV1InstalledAddOnInstalledAddOnUsage, headers?: any, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnUsageInstance>) => any): Promise<ApiResponse<InstalledAddOnUsageInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InstalledAddOnUsageListInstance(version: V1, installedAddOnSid: string): InstalledAddOnUsageListInstance { + if (!isValidPathParam(installedAddOnSid)) { + throw new Error('Parameter \'installedAddOnSid\' is not valid.'); + } + + const instance = {} as InstalledAddOnUsageListInstance; + + instance._version = version; + instance._solution = { installedAddOnSid, }; + instance._uri = `/InstalledAddOns/${installedAddOnSid}/Usage`; + + instance.create = function create(params: MarketplaceV1InstalledAddOnInstalledAddOnUsage, headers?: any, callback?: (error: Error | null, items: InstalledAddOnUsageInstance) => any): Promise<InstalledAddOnUsageInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnUsageInstance(operationVersion, payload, instance._solution.installedAddOnSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MarketplaceV1InstalledAddOnInstalledAddOnUsage, headers?: any, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnUsageInstance>) => any): Promise<ApiResponse<InstalledAddOnUsageInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<InstalledAddOnUsageResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<InstalledAddOnUsageInstance> => ({ + ...response, + body: new InstalledAddOnUsageInstance(operationVersion, response.body, instance._solution.installedAddOnSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface InstalledAddOnUsagePayload extends InstalledAddOnUsageResource {} + +interface InstalledAddOnUsageResource { + total_submitted: number; + billable_items: Array<MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems>; +} + +export class InstalledAddOnUsageInstance { + + constructor(protected _version: V1, payload: InstalledAddOnUsageResource, installedAddOnSid: string) { + + this.totalSubmitted = (payload.total_submitted); + this.billableItems = payload.billable_items !== null && payload.billable_items !== undefined ? payload.billable_items.map( + (payload: any) => new MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems(payload) + ) : null; + + } + + /** + * Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + */ + totalSubmitted: number; + billableItems: Array<MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + totalSubmitted: this.totalSubmitted, + billableItems: this.billableItems, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/marketplace/v1/moduleData.ts b/rest/marketplace/v1/moduleData.ts new file mode 100644 index 000000000..f1f75547b --- /dev/null +++ b/rest/marketplace/v1/moduleData.ts @@ -0,0 +1,332 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Marketplace + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a ModuleDataInstance + */ +export interface ModuleDataListInstanceCreateOptions { + /** A JSON object containing essential attributes that define a Listing. */ + "moduleInfo"?: string; + /** A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. */ + "configuration"?: string; +} + + + +export interface ModuleDataSolution { +} + +export interface ModuleDataListInstance { + _version: V1; + _solution: ModuleDataSolution; + _uri: string; + + + + /** + * Create a ModuleDataInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataInstance + */ + create(callback?: (error: Error | null, item?: ModuleDataInstance) => any): Promise<ModuleDataInstance>; + /** + * Create a ModuleDataInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataInstance + */ + create(params: ModuleDataListInstanceCreateOptions, callback?: (error: Error | null, item?: ModuleDataInstance) => any): Promise<ModuleDataInstance>; + + /** + * Create a ModuleDataInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ModuleDataInstance>) => any): Promise<ApiResponse<ModuleDataInstance>>; + /** + * Create a ModuleDataInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataInstance with HTTP metadata + */ + createWithHttpInfo(params: ModuleDataListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ModuleDataInstance>) => any): Promise<ApiResponse<ModuleDataInstance>>; + + + + /** + * Fetch a ModuleDataInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataInstance + */ + fetch(callback?: (error: Error | null, item?: ModuleDataInstance) => any): Promise<ModuleDataInstance> + + /** + * Fetch a ModuleDataInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ModuleDataInstance>) => any): Promise<ApiResponse<ModuleDataInstance>> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ModuleDataListInstance(version: V1): ModuleDataListInstance { + const instance = {} as ModuleDataListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Listings`; + + instance.create = function create(params?: ModuleDataListInstanceCreateOptions | ((error: Error | null, items: ModuleDataInstance) => any), callback?: (error: Error | null, items: ModuleDataInstance) => any): Promise<ModuleDataInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["moduleInfo"] !== undefined) + data["ModuleInfo"] = params["moduleInfo"]; + if (params["configuration"] !== undefined) + data["Configuration"] = params["configuration"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ModuleDataInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ModuleDataListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<ModuleDataInstance>) => any), callback?: (error: Error | null, items: ApiResponse<ModuleDataInstance>) => any): Promise<ApiResponse<ModuleDataInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["moduleInfo"] !== undefined) + data["ModuleInfo"] = params["moduleInfo"]; + if (params["configuration"] !== undefined) + data["Configuration"] = params["configuration"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ModuleDataResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ModuleDataInstance> => ({ + ...response, + body: new ModuleDataInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetch = function fetch( callback?: (error: Error | null, items: ModuleDataInstance) => any): Promise<ModuleDataInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ModuleDataInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<ModuleDataInstance>) => any): Promise<ApiResponse<ModuleDataInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ModuleDataResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ModuleDataInstance> => ({ + ...response, + body: new ModuleDataInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ModuleDataPayload extends ModuleDataResource {} + +interface ModuleDataResource { + url: string; + sid: string; + description: Record<string, object>; + support: Record<string, object>; + policies: Record<string, object>; + module_info: Record<string, object>; + documentation: Record<string, object>; + configuration: Record<string, object>; + pricing: Record<string, object>; + listings: Array<Record<string, object>>; +} + +export class ModuleDataInstance { + + constructor(protected _version: V1, payload: ModuleDataResource) { + + this.url = (payload.url); + this.sid = (payload.sid); + this.description = (payload.description); + this.support = (payload.support); + this.policies = (payload.policies); + this.moduleInfo = (payload.module_info); + this.documentation = (payload.documentation); + this.configuration = (payload.configuration); + this.pricing = (payload.pricing); + this.listings = (payload.listings); + + } + + /** + * URL to query the subresource. + */ + url: string; + /** + * ModuleSid that identifies this Listing. + */ + sid: string; + /** + * A JSON object describing the module and is displayed under the Description tab of the Module detail page. You can define the main body of the description, highlight key features or aspects of the module and if applicable, provide code samples for developers + */ + description: Record<string, object>; + /** + * A JSON object containing information on how customers can obtain support for the module. Use this parameter to provide details such as contact information and support description. + */ + support: Record<string, object>; + /** + * A JSON object describing the module\'s privacy and legal policies and is displayed under the Policies tab of the Module detail page. The maximum file size for Policies is 5MB + */ + policies: Record<string, object>; + /** + * A JSON object containing essential attributes that define a module. This information is presented on the Module detail page in the Twilio Marketplace Catalog. You can pass the following attributes in the JSON object + */ + moduleInfo: Record<string, object>; + /** + * A JSON object for providing comprehensive information, instructions, and resources related to the module + */ + documentation: Record<string, object>; + /** + * A JSON object for providing listing specific configuration. Contains button setup, notification url, among others. + */ + configuration: Record<string, object>; + /** + * A JSON object for providing Listing specific pricing information. + */ + pricing: Record<string, object>; + /** + * + */ + listings: Array<Record<string, object>>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + url: this.url, + sid: this.sid, + description: this.description, + support: this.support, + policies: this.policies, + moduleInfo: this.moduleInfo, + documentation: this.documentation, + configuration: this.configuration, + pricing: this.pricing, + listings: this.listings, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/marketplace/v1/moduleDataManagement.ts b/rest/marketplace/v1/moduleDataManagement.ts new file mode 100644 index 000000000..ec2d15198 --- /dev/null +++ b/rest/marketplace/v1/moduleDataManagement.ts @@ -0,0 +1,494 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Marketplace + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a ModuleDataManagementInstance + */ +export interface ModuleDataManagementContextUpdateOptions { + /** A JSON object containing essential attributes that define a Listing. */ + "moduleInfo"?: string; + /** A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. */ + "description"?: string; + /** A JSON object for providing comprehensive information, instructions, and resources related to the Listing. */ + "documentation"?: string; + /** A JSON object describing the Listing\\\'s privacy and legal policies. The maximum file size for Policies is 5MB. */ + "policies"?: string; + /** A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. */ + "support"?: string; + /** A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. */ + "configuration"?: string; + /** A JSON object for providing Listing\\\'s purchase options. */ + "pricing"?: string; +} + +export interface ModuleDataManagementContext { + + /** + * Fetch a ModuleDataManagementInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance + */ + fetch(callback?: (error: Error | null, item?: ModuleDataManagementInstance) => any): Promise<ModuleDataManagementInstance> + + /** + * Fetch a ModuleDataManagementInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ModuleDataManagementInstance>) => any): Promise<ApiResponse<ModuleDataManagementInstance>> + + /** + * Update a ModuleDataManagementInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance + */ + update(callback?: (error: Error | null, item?: ModuleDataManagementInstance) => any): Promise<ModuleDataManagementInstance>; + /** + * Update a ModuleDataManagementInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance + */ + update(params: ModuleDataManagementContextUpdateOptions, callback?: (error: Error | null, item?: ModuleDataManagementInstance) => any): Promise<ModuleDataManagementInstance>; + + /** + * Update a ModuleDataManagementInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ModuleDataManagementInstance>) => any): Promise<ApiResponse<ModuleDataManagementInstance>>; + /** + * Update a ModuleDataManagementInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance with HTTP metadata + */ + updateWithHttpInfo(params: ModuleDataManagementContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ModuleDataManagementInstance>) => any): Promise<ApiResponse<ModuleDataManagementInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ModuleDataManagementContextSolution { + "sid": string; +} + +export class ModuleDataManagementContextImpl implements ModuleDataManagementContext { + protected _solution: ModuleDataManagementContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Listing/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: ModuleDataManagementInstance) => any): Promise<ModuleDataManagementInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ModuleDataManagementInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ModuleDataManagementInstance>) => any): Promise<ApiResponse<ModuleDataManagementInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ModuleDataManagementResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ModuleDataManagementInstance> => ({ + ...response, + body: new ModuleDataManagementInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ModuleDataManagementContextUpdateOptions | ((error: Error | null, item?: ModuleDataManagementInstance) => any),callback?: (error: Error | null, item?: ModuleDataManagementInstance) => any): Promise<ModuleDataManagementInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["moduleInfo"] !== undefined) + data["ModuleInfo"] = params["moduleInfo"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["documentation"] !== undefined) + data["Documentation"] = params["documentation"]; + if (params["policies"] !== undefined) + data["Policies"] = params["policies"]; + if (params["support"] !== undefined) + data["Support"] = params["support"]; + if (params["configuration"] !== undefined) + data["Configuration"] = params["configuration"]; + if (params["pricing"] !== undefined) + data["Pricing"] = params["pricing"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ModuleDataManagementInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ModuleDataManagementContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ModuleDataManagementInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ModuleDataManagementInstance>) => any): Promise<ApiResponse<ModuleDataManagementInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["moduleInfo"] !== undefined) + data["ModuleInfo"] = params["moduleInfo"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + if (params["documentation"] !== undefined) + data["Documentation"] = params["documentation"]; + if (params["policies"] !== undefined) + data["Policies"] = params["policies"]; + if (params["support"] !== undefined) + data["Support"] = params["support"]; + if (params["configuration"] !== undefined) + data["Configuration"] = params["configuration"]; + if (params["pricing"] !== undefined) + data["Pricing"] = params["pricing"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ModuleDataManagementResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ModuleDataManagementInstance> => ({ + ...response, + body: new ModuleDataManagementInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ModuleDataManagementPayload extends ModuleDataManagementResource {} + +interface ModuleDataManagementResource { + url: string; + sid: string; + description: Record<string, object>; + support: Record<string, object>; + policies: Record<string, object>; + module_info: Record<string, object>; + documentation: Record<string, object>; + configuration: Record<string, object>; + pricing: Record<string, object>; + listings: Array<Record<string, object>>; +} + +export class ModuleDataManagementInstance { + protected _solution: ModuleDataManagementContextSolution; + protected _context?: ModuleDataManagementContext; + + constructor(protected _version: V1, payload: ModuleDataManagementResource, sid?: string) { + + this.url = (payload.url); + this.sid = (payload.sid); + this.description = (payload.description); + this.support = (payload.support); + this.policies = (payload.policies); + this.moduleInfo = (payload.module_info); + this.documentation = (payload.documentation); + this.configuration = (payload.configuration); + this.pricing = (payload.pricing); + this.listings = (payload.listings); + + this._solution = { sid: sid, }; + } + + /** + * URL to query the subresource. + */ + url: string; + /** + * ModuleSid that identifies this Listing. + */ + sid: string; + /** + * A JSON object describing the module and is displayed under the Description tab of the Module detail page. You can define the main body of the description, highlight key features or aspects of the module and if applicable, provide code samples for developers + */ + description: Record<string, object>; + /** + * A JSON object containing information on how customers can obtain support for the module. Use this parameter to provide details such as contact information and support description. + */ + support: Record<string, object>; + /** + * A JSON object describing the module\'s privacy and legal policies and is displayed under the Policies tab of the Module detail page. The maximum file size for Policies is 5MB + */ + policies: Record<string, object>; + /** + * A JSON object containing essential attributes that define a module. This information is presented on the Module detail page in the Twilio Marketplace Catalog. You can pass the following attributes in the JSON object + */ + moduleInfo: Record<string, object>; + /** + * A JSON object for providing comprehensive information, instructions, and resources related to the module + */ + documentation: Record<string, object>; + /** + * A JSON object for providing listing specific configuration. Contains button setup, notification url, among others. + */ + configuration: Record<string, object>; + /** + * A JSON object for providing Listing specific pricing information. + */ + pricing: Record<string, object>; + /** + * + */ + listings: Array<Record<string, object>>; + + private get _proxy(): ModuleDataManagementContext { + this._context = this._context || new ModuleDataManagementContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a ModuleDataManagementInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance + */ + fetch(callback?: (error: Error | null, item?: ModuleDataManagementInstance) => any): Promise<ModuleDataManagementInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ModuleDataManagementInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ModuleDataManagementInstance>) => any): Promise<ApiResponse<ModuleDataManagementInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ModuleDataManagementInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance + */ + update(callback?: (error: Error | null, item?: ModuleDataManagementInstance) => any): Promise<ModuleDataManagementInstance>; + /** + * Update a ModuleDataManagementInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance + */ + update(params: ModuleDataManagementContextUpdateOptions, callback?: (error: Error | null, item?: ModuleDataManagementInstance) => any): Promise<ModuleDataManagementInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ModuleDataManagementInstance) => any): Promise<ModuleDataManagementInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ModuleDataManagementInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ModuleDataManagementInstance>) => any): Promise<ApiResponse<ModuleDataManagementInstance>>; + /** + * Update a ModuleDataManagementInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ModuleDataManagementInstance with HTTP metadata + */ + updateWithHttpInfo(params: ModuleDataManagementContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ModuleDataManagementInstance>) => any): Promise<ApiResponse<ModuleDataManagementInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ModuleDataManagementInstance>) => any): Promise<ApiResponse<ModuleDataManagementInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + url: this.url, + sid: this.sid, + description: this.description, + support: this.support, + policies: this.policies, + moduleInfo: this.moduleInfo, + documentation: this.documentation, + configuration: this.configuration, + pricing: this.pricing, + listings: this.listings, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ModuleDataManagementSolution { +} + +export interface ModuleDataManagementListInstance { + _version: V1; + _solution: ModuleDataManagementSolution; + _uri: string; + + (sid: string, ): ModuleDataManagementContext; + get(sid: string, ): ModuleDataManagementContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ModuleDataManagementListInstance(version: V1): ModuleDataManagementListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ModuleDataManagementListInstance; + + instance.get = function get(sid, ): ModuleDataManagementContext { + return new ModuleDataManagementContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/marketplace/v1/referralConversion.ts b/rest/marketplace/v1/referralConversion.ts new file mode 100644 index 000000000..d021efa75 --- /dev/null +++ b/rest/marketplace/v1/referralConversion.ts @@ -0,0 +1,195 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Marketplace + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class CreateReferralConversionRequest { + "referralAccountSid"?: string; + + constructor(payload) { + this.referralAccountSid = payload["referral_account_sid"]; + } +} + + + +/** + * Options to pass to create a ReferralConversionInstance + */ +export interface ReferralConversionListInstanceCreateOptions { + /** */ + "createReferralConversionRequest": CreateReferralConversionRequest; +} + + +export interface ReferralConversionSolution { +} + +export interface ReferralConversionListInstance { + _version: V1; + _solution: ReferralConversionSolution; + _uri: string; + + + + /** + * Create a ReferralConversionInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReferralConversionInstance + */ + create(params: CreateReferralConversionRequest, headers?: any, callback?: (error: Error | null, item?: ReferralConversionInstance) => any): Promise<ReferralConversionInstance>; + + /** + * Create a ReferralConversionInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReferralConversionInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateReferralConversionRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ReferralConversionInstance>) => any): Promise<ApiResponse<ReferralConversionInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ReferralConversionListInstance(version: V1): ReferralConversionListInstance { + const instance = {} as ReferralConversionListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/ReferralConversion`; + + instance.create = function create(params: CreateReferralConversionRequest, headers?: any, callback?: (error: Error | null, items: ReferralConversionInstance) => any): Promise<ReferralConversionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ReferralConversionInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateReferralConversionRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<ReferralConversionInstance>) => any): Promise<ApiResponse<ReferralConversionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ReferralConversionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ReferralConversionInstance> => ({ + ...response, + body: new ReferralConversionInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ReferralConversionPayload extends ReferralConversionResource {} + +interface ReferralConversionResource { + converted_account_sid: string; +} + +export class ReferralConversionInstance { + + constructor(protected _version: V1, payload: ReferralConversionResource) { + + this.convertedAccountSid = (payload.converted_account_sid); + + } + + convertedAccountSid: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + convertedAccountSid: this.convertedAccountSid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/memory/V1.ts b/rest/memory/V1.ts new file mode 100644 index 000000000..91b0d8ff5 --- /dev/null +++ b/rest/memory/V1.ts @@ -0,0 +1,181 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import MemoryBase from "../MemoryBase"; +import Version from "../../base/Version"; +import { BulkListInstance } from "./v1/bulk"; +import { ConversationSummaryListInstance, ConversationSummaryContext } from "./v1/conversationSummary"; +import { DataMappingListInstance, DataMappingContext } from "./v1/dataMapping"; +import { IdentifierListInstance, IdentifierContext } from "./v1/identifier"; +import { IdentityResolutionSettingListInstance } from "./v1/identityResolutionSetting"; +import { ImportListInstance, ImportContext } from "./v1/import"; +import { LookupListInstance } from "./v1/lookup"; +import { ObservationListInstance, ObservationContext } from "./v1/observation"; +import { OperationListInstance } from "./v1/operation"; +import { ProfileListInstance, ProfileContext } from "./v1/profile"; +import { RecallListInstance } from "./v1/recall"; +import { RevisionListInstance } from "./v1/revision"; +import { StoreListInstance } from "./v1/store"; +import { TraitListInstance } from "./v1/trait"; +import { TraitGroupListInstance, TraitGroupContext } from "./v1/traitGroup"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Memory + * + * @param domain - The Twilio (Twilio.Memory) domain + */ + constructor(domain: MemoryBase) { + super(domain, "v1"); + } + + /** operations - { Twilio.Memory.V1.OperationListInstance } resource */ + protected _operations?: OperationListInstance; + /** stores - { Twilio.Memory.V1.StoreListInstance } resource */ + protected _stores?: StoreListInstance; + + /** Accessor for bulk resource */ + bulk(storeId: string): BulkListInstance { + return BulkListInstance(this, storeId); + } + + /** Accessor for conversationSummaries resource - list operations */ + conversationSummaries(storeId: string, profileId: string): ConversationSummaryListInstance; + /** Accessor for conversationSummaries resource - instance operations */ + conversationSummaries(storeId: string, profileId: string, summaryId: string): ConversationSummaryContext; + /** Implementation */ + conversationSummaries(storeId: string, profileId: string, summaryId?: string): ConversationSummaryListInstance | ConversationSummaryContext { + const listInstance = ConversationSummaryListInstance(this, storeId, profileId); + if (summaryId !== undefined) { + return listInstance.get(summaryId); + } + return listInstance; + } + + /** Accessor for dataMappings resource - list operations */ + dataMappings(storeId: string): DataMappingListInstance; + /** Accessor for dataMappings resource - instance operations */ + dataMappings(storeId: string, dataMappingId: string): DataMappingContext; + /** Implementation */ + dataMappings(storeId: string, dataMappingId?: string): DataMappingListInstance | DataMappingContext { + const listInstance = DataMappingListInstance(this, storeId); + if (dataMappingId !== undefined) { + return listInstance.get(dataMappingId); + } + return listInstance; + } + + /** Accessor for identifiers resource - list operations */ + identifiers(storeId: string, profileId: string): IdentifierListInstance; + /** Accessor for identifiers resource - instance operations */ + identifiers(storeId: string, profileId: string, idType: string): IdentifierContext; + /** Implementation */ + identifiers(storeId: string, profileId: string, idType?: string): IdentifierListInstance | IdentifierContext { + const listInstance = IdentifierListInstance(this, storeId, profileId); + if (idType !== undefined) { + return listInstance.get(idType); + } + return listInstance; + } + + /** Accessor for identityResolutionSettings resource */ + identityResolutionSettings(storeId: string): IdentityResolutionSettingListInstance { + return IdentityResolutionSettingListInstance(this, storeId); + } + + /** Accessor for imports resource - list operations */ + imports(storeId: string): ImportListInstance; + /** Accessor for imports resource - instance operations */ + imports(storeId: string, importId: string): ImportContext; + /** Implementation */ + imports(storeId: string, importId?: string): ImportListInstance | ImportContext { + const listInstance = ImportListInstance(this, storeId); + if (importId !== undefined) { + return listInstance.get(importId); + } + return listInstance; + } + + /** Accessor for lookup resource */ + lookup(storeId: string): LookupListInstance { + return LookupListInstance(this, storeId); + } + + /** Accessor for observations resource - list operations */ + observations(storeId: string, profileId: string): ObservationListInstance; + /** Accessor for observations resource - instance operations */ + observations(storeId: string, profileId: string, observationId: string): ObservationContext; + /** Implementation */ + observations(storeId: string, profileId: string, observationId?: string): ObservationListInstance | ObservationContext { + const listInstance = ObservationListInstance(this, storeId, profileId); + if (observationId !== undefined) { + return listInstance.get(observationId); + } + return listInstance; + } + + /** Getter for operations resource */ + get operations(): OperationListInstance { + this._operations = this._operations || OperationListInstance(this); + return this._operations; + } + + /** Accessor for profiles resource - list operations */ + profiles(storeId: string): ProfileListInstance; + /** Accessor for profiles resource - instance operations */ + profiles(storeId: string, profileId: string): ProfileContext; + /** Implementation */ + profiles(storeId: string, profileId?: string): ProfileListInstance | ProfileContext { + const listInstance = ProfileListInstance(this, storeId); + if (profileId !== undefined) { + return listInstance.get(profileId); + } + return listInstance; + } + + /** Accessor for recall resource */ + recall(storeId: string, profileId: string): RecallListInstance { + return RecallListInstance(this, storeId, profileId); + } + + /** Accessor for revisions resource */ + revisions(storeId: string, profileId: string, observationId: string): RevisionListInstance { + return RevisionListInstance(this, storeId, profileId, observationId); + } + + /** Getter for stores resource */ + get stores(): StoreListInstance { + this._stores = this._stores || StoreListInstance(this); + return this._stores; + } + + /** Accessor for traits resource */ + traits(storeId: string, profileId: string): TraitListInstance { + return TraitListInstance(this, storeId, profileId); + } + + /** Accessor for traitGroups resource - list operations */ + traitGroups(storeId: string): TraitGroupListInstance; + /** Accessor for traitGroups resource - instance operations */ + traitGroups(storeId: string, traitGroupName: string): TraitGroupContext; + /** Implementation */ + traitGroups(storeId: string, traitGroupName?: string): TraitGroupListInstance | TraitGroupContext { + const listInstance = TraitGroupListInstance(this, storeId); + if (traitGroupName !== undefined) { + return listInstance.get(traitGroupName); + } + return listInstance; + } + +} diff --git a/rest/memory/v1/bulk.ts b/rest/memory/v1/bulk.ts new file mode 100644 index 000000000..c2ae4162e --- /dev/null +++ b/rest/memory/v1/bulk.ts @@ -0,0 +1,215 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Data for creating or updating a profile, including traits. + */ +export class ProfileData { + /** + * Multiple trait groups. + */ + "traits"?: { [key: string]: { [key: string]: any; }; }; + + constructor(payload) { + this.traits = payload["traits"]; + } +} + + +export class UpdateProfilesBulkRequest { + "profiles"?: Array<ProfileData>; + + constructor(payload) { + this.profiles = payload["profiles"]; + } +} + + + +/** + * Options to pass to update a BulkInstance + */ +export interface BulkListInstanceUpdateOptions { + /** */ + "updateProfilesBulkRequest": UpdateProfilesBulkRequest; +} + + +export interface BulkSolution { + storeId: string; +} + +export interface BulkListInstance { + _version: V1; + _solution: BulkSolution; + _uri: string; + + + + /** + * Update a BulkInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkInstance + */ + update(params: UpdateProfilesBulkRequest, headers?: any, callback?: (error: Error | null, item?: BulkInstance) => any): Promise<BulkInstance>; + + /** + * Update a BulkInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkInstance with HTTP metadata + */ + updateWithHttpInfo(params: UpdateProfilesBulkRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<BulkInstance>) => any): Promise<ApiResponse<BulkInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BulkListInstance(version: V1, storeId: string): BulkListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + const instance = {} as BulkListInstance; + + instance._version = version; + instance._solution = { storeId, }; + instance._uri = `/Stores/${storeId}/Profiles/Bulk`; + + instance.update = function update(params: UpdateProfilesBulkRequest, headers?: any, callback?: (error: Error | null, items: BulkInstance) => any): Promise<BulkInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new BulkInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.updateWithHttpInfo = function updateWithHttpInfo(params: UpdateProfilesBulkRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<BulkInstance>) => any): Promise<ApiResponse<BulkInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<BulkResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<BulkInstance> => ({ + ...response, + body: new BulkInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + + +interface BulkResource { + message: string; +} + +export class BulkInstance { + + constructor(protected _version: V1, _payload: BulkResource, storeId: string) { + const payload = _payload; + this.message = (payload.message); + + } + + message: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/memory/v1/conversationSummary.ts b/rest/memory/v1/conversationSummary.ts new file mode 100644 index 000000000..b3808eb69 --- /dev/null +++ b/rest/memory/v1/conversationSummary.ts @@ -0,0 +1,1047 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Request payload for creating one or more conversation summaries. Supports creation of up to 10 summaries. + */ +export class CreateSummariesRequest { + /** + * Array of summaries to create in a single batch operation. + */ + "summaries": Array<SummaryCore>; + + constructor(payload) { + this.summaries = payload["summaries"]; + } +} + + +/** + * Core mutable properties for creating summary objects. + */ +export class SummaryCore { + /** + * The source system that generated the summary. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + */ + "source"?: string; + /** + * The main content of the summary. + */ + "content": string; + /** + * The timestamp when the summary was originally created. + */ + "occurredAt": Date; + /** + * A unique identifier for the conversation using Twilio Type ID (TTID) format. + */ + "conversationId": string; + + constructor(payload) { + this.source = payload["source"]; + this.content = payload["content"]; + this.occurredAt = payload["occurredAt"]; + this.conversationId = payload["conversationId"]; + } +} + + +/** + * Core mutable properties for updating summary objects. All fields are optional for PATCH operations. + */ +export class SummaryCorePatch { + /** + * The source system that generated the summary. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + */ + "source"?: string; + /** + * The main content of the summary. + */ + "content"?: string; + /** + * The timestamp when the summary was originally created. If not provided, defaults to the time the summary was received. + */ + "occurredAt"?: Date; + /** + * A unique identifier for the conversation using Twilio Type ID (TTID) format. + */ + "conversationId"?: string; + + constructor(payload) { + this.source = payload["source"]; + this.content = payload["content"]; + this.occurredAt = payload["occurredAt"]; + this.conversationId = payload["conversationId"]; + } +} + + + + + +/** + * Options to pass to patch a ConversationSummaryInstance + */ +export interface ConversationSummaryContextPatchOptions { + /** */ + "summaryCorePatch": SummaryCorePatch; +} + +/** + * Options to pass to create a ConversationSummaryInstance + */ +export interface ConversationSummaryListInstanceCreateOptions { + /** */ + "createSummariesRequest": CreateSummariesRequest; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; + /** Compression algorithm used for the request body (e.g., gzip, deflate, br) */ + "contentEncoding"?: 'gzip' | 'deflate' | 'br' | 'compress'; +} + +/** + * Options to pass to each + */ +export interface ConversationSummaryListInstanceEachOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Filter by conversation ID. Returns only items associated with the specified conversation. */ + "conversationId"?: string; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConversationSummaryInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConversationSummaryListInstanceOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Filter by conversation ID. Returns only items associated with the specified conversation. */ + "conversationId"?: string; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConversationSummaryListInstancePageOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Filter by conversation ID. Returns only items associated with the specified conversation. */ + "conversationId"?: string; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; +} + + +export interface ConversationSummaryContext { + + /** + * Remove a ConversationSummaryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance + */ + remove(callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance> + + /** + * Remove a ConversationSummaryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>> + + /** + * Fetch a ConversationSummaryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance + */ + fetch(callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance> + + /** + * Fetch a ConversationSummaryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>> + + /** + * Patch a ConversationSummaryInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance + */ + patch(params: SummaryCorePatch, headers?: any, callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance>; + + /** + * Patch a ConversationSummaryInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance with HTTP metadata + */ + patchWithHttpInfo(params: SummaryCorePatch, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConversationSummaryContextSolution { + "storeId": string; + "profileId": string; + "summaryId": string; +} + +export class ConversationSummaryContextImpl implements ConversationSummaryContext { + protected _solution: ConversationSummaryContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, storeId: string, profileId: string, summaryId: string) { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(profileId)) { + throw new Error('Parameter \'profileId\' is not valid.'); + } + + if (!isValidPathParam(summaryId)) { + throw new Error('Parameter \'summaryId\' is not valid.'); + } + + this._solution = { storeId, profileId, summaryId, }; + this._uri = `/Stores/${storeId}/Profiles/${profileId}/ConversationSummaries/${summaryId}`; + } + + remove(callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "delete", headers}); + + operationPromise = operationPromise.then(payload => new ConversationSummaryInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId, instance._solution.summaryId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // DELETE operation that returns a response model + let operationPromise = operationVersion.fetchWithResponseInfo<ConversationSummaryResource>({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<ConversationSummaryInstance> => ({ + ...response, + body: new ConversationSummaryInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId, instance._solution.summaryId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConversationSummaryInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId, instance._solution.summaryId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ConversationSummaryResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ConversationSummaryInstance> => ({ + ...response, + body: new ConversationSummaryInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId, instance._solution.summaryId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patch(params: SummaryCorePatch, headers?: any,callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.patch({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationSummaryInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId, instance._solution.summaryId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patchWithHttpInfo(params: SummaryCorePatch, headers?: any,callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.patchWithResponseInfo<ConversationSummaryResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<ConversationSummaryInstance> => ({ + ...response, + body: new ConversationSummaryInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId, instance._solution.summaryId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for CreateSummariesRequest + */ +export interface CreateSummariesRequest { + summaries: Array<SummaryCore>; +} + +/** + * Nested model for SummaryCore + */ +export interface SummaryCore { + source?: string; + content: string; + occurredAt: Date; + conversationId: string; +} + +/** + * Nested model for SummaryCorePatch + */ +export interface SummaryCorePatch { + source?: string; + content?: string; + occurredAt?: Date; + conversationId?: string; +} + + + + interface ConversationSummaryPayload extends TokenPaginationPayload { + summaries: ConversationSummaryResource[]; +} + +/** + * Response model for SummariesCreatedResponse operations + */ +interface SummariesCreatedResponse_ResponseResource { + message: string; +} + +/** + * Response model for PatchProfileConversationSummary202Response operations + */ +interface PatchProfileConversationSummary202Response_ResponseResource { + message: string; +} + +/** + * Response model for DeleteProfileConversationSummary202Response operations + */ +interface DeleteProfileConversationSummary202Response_ResponseResource { + message: string; +} + +/** + * Response model for SummaryInfo operations + */ +interface SummaryInfo_ResponseResource { + source?: string; + content: string; + occurredAt: Date; + conversationId: string; + id: string; + createdAt: Date; + updatedAt: Date; +} + +/** + * Union type for all possible response models + */ +type ConversationSummaryResource = SummariesCreatedResponse_ResponseResource | PatchProfileConversationSummary202Response_ResponseResource | DeleteProfileConversationSummary202Response_ResponseResource | SummaryInfo_ResponseResource; + +/** + * Response for batch summary creation. + */ +export class ConversationSummaryInstance { + protected _solution: ConversationSummaryContextSolution; + protected _context?: ConversationSummaryContext; + + constructor(protected _version: V1, _payload: ConversationSummaryResource, storeId: string, profileId: string, summaryId?: string) { + const payload: any = _payload; + this.message = (payload.message); + this.source = (payload.source); + this.content = (payload.content); + this.occurredAt = deserialize.iso8601DateTime(payload.occurredAt); + this.conversationId = (payload.conversationId); + this.id = (payload.id); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + + this._solution = { storeId, profileId, summaryId: summaryId, }; + } + + /** + * Confirmation message for the operation. + */ + message?: string; + /** + * The source system that generated the summary. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + */ + source?: string; + /** + * The main content of the summary. + */ + content?: string; + /** + * The timestamp when the summary was originally created. + */ + occurredAt?: Date; + /** + * A unique identifier for the conversation using Twilio Type ID (TTID) format. + */ + conversationId?: string; + /** + * A unique identifier for the summary using Twilio Type ID (TTID) format. + */ + id?: string; + /** + * The timestamp when the summary was created. + */ + createdAt?: Date; + /** + * The timestamp when the summary was last updated. + */ + updatedAt?: Date; + + private get _proxy(): ConversationSummaryContext { + this._context = this._context || new ConversationSummaryContextImpl(this._version, this._solution.storeId, this._solution.profileId, this._solution.summaryId); + return this._context; + } + + /** + * Remove a ConversationSummaryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance + */ + remove(callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ConversationSummaryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ConversationSummaryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance + */ + fetch(callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConversationSummaryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Patch a ConversationSummaryInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance + */ + patch(params: SummaryCorePatch, headers?: any, callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance>; + + patch(params?: any, callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance> + { + return this._proxy.patch(params, callback); + } + + /** + * Patch a ConversationSummaryInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance with HTTP metadata + */ + patchWithHttpInfo(params: SummaryCorePatch, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>>; + + patchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>> + { + return this._proxy.patchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + source: this.source, + content: this.content, + occurredAt: this.occurredAt, + conversationId: this.conversationId, + id: this.id, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConversationSummarySolution { + storeId: string; + profileId: string; +} + +export interface ConversationSummaryListInstance { + _version: V1; + _solution: ConversationSummarySolution; + _uri: string; + + (summaryId: string, ): ConversationSummaryContext; + get(summaryId: string, ): ConversationSummaryContext; + + + + + + + + + /** + * Create a ConversationSummaryInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance + */ + create(params: CreateSummariesRequest, headers?: any, callback?: (error: Error | null, item?: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance>; + + /** + * Create a ConversationSummaryInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConversationSummaryInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateSummariesRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>>; + + + + + /** + * Streams ConversationSummaryInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationSummaryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConversationSummaryInstance, done: (err?: Error) => void) => void): void; + each(params: ConversationSummaryListInstanceEachOptions, callback?: (item: ConversationSummaryInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConversationSummaryInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationSummaryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConversationSummaryInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConversationSummaryListInstanceEachOptions, callback?: (item: ConversationSummaryInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConversationSummaryInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConversationSummaryPage) => any): Promise<ConversationSummaryPage>; + /** + * Retrieve a single target page of ConversationSummaryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ConversationSummaryPage>) => any): Promise<ApiResponse<ConversationSummaryPage>>; + /** + * Lists ConversationSummaryInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationSummaryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConversationSummaryInstance[]) => any): Promise<ConversationSummaryInstance[]>; + list(params: ConversationSummaryListInstanceOptions, callback?: (error: Error | null, items: ConversationSummaryInstance[]) => any): Promise<ConversationSummaryInstance[]>; + /** + * Lists ConversationSummaryInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationSummaryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ConversationSummaryInstance[]>) => any): Promise<ApiResponse<ConversationSummaryInstance[]>>; + listWithHttpInfo(params: ConversationSummaryListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ConversationSummaryInstance[]>) => any): Promise<ApiResponse<ConversationSummaryInstance[]>>; + /** + * Retrieve a single page of ConversationSummaryInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationSummaryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConversationSummaryPage) => any): Promise<ConversationSummaryPage>; + page(params: ConversationSummaryListInstancePageOptions, callback?: (error: Error | null, items: ConversationSummaryPage) => any): Promise<ConversationSummaryPage>; + /** + * Retrieve a single page of ConversationSummaryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConversationSummaryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ConversationSummaryPage>) => any): Promise<ApiResponse<ConversationSummaryPage>>; + pageWithHttpInfo(params: ConversationSummaryListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ConversationSummaryPage>) => any): Promise<ApiResponse<ConversationSummaryPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConversationSummaryListInstance(version: V1, storeId: string, profileId: string): ConversationSummaryListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(profileId)) { + throw new Error('Parameter \'profileId\' is not valid.'); + } + + const instance = ((summaryId, ) => instance.get(summaryId, )) as ConversationSummaryListInstance; + + instance.get = function get(summaryId, ): ConversationSummaryContext { + return new ConversationSummaryContextImpl(version, storeId, profileId, summaryId); + } + + instance._version = version; + instance._solution = { storeId, profileId, }; + instance._uri = `/Stores/${storeId}/Profiles/${profileId}/ConversationSummaries`; + + instance.create = function create(params: CreateSummariesRequest, headers?: any, callback?: (error: Error | null, items: ConversationSummaryInstance) => any): Promise<ConversationSummaryInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConversationSummaryInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateSummariesRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<ConversationSummaryInstance>) => any): Promise<ApiResponse<ConversationSummaryInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ConversationSummaryResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ConversationSummaryInstance> => ({ + ...response, + body: new ConversationSummaryInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ConversationSummaryListInstancePageOptions | ((error: Error | null, items: ConversationSummaryPage) => any), callback?: (error: Error | null, items: ConversationSummaryPage) => any): Promise<ConversationSummaryPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["conversationId"] !== undefined) + data["conversationId"] = params["conversationId"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["acceptEncoding"] !== undefined) headers["Accept-Encoding"] = params["acceptEncoding"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConversationSummaryPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConversationSummaryPage) => any): Promise<ConversationSummaryPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConversationSummaryPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConversationSummaryListInstancePageOptions | ((error: Error | null, items: ApiResponse<ConversationSummaryPage>) => any), callback?: (error: Error | null, items: ApiResponse<ConversationSummaryPage>) => any): Promise<ApiResponse<ConversationSummaryPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["conversationId"] !== undefined) + data["conversationId"] = params["conversationId"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["acceptEncoding"] !== undefined) headers["Accept-Encoding"] = params["acceptEncoding"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ConversationSummaryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConversationSummaryPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ConversationSummaryPage>) => any): Promise<ApiResponse<ConversationSummaryPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ConversationSummaryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConversationSummaryPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConversationSummaryPage extends TokenPage<V1, ConversationSummaryPayload, ConversationSummaryResource, ConversationSummaryInstance> { +/** +* Initialize the ConversationSummaryPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, uri: string, params: any, solution: ConversationSummarySolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of ConversationSummaryInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConversationSummaryResource): ConversationSummaryInstance { + + return new ConversationSummaryInstance( + this._version, + payload, + this._solution.storeId, + this._solution.profileId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/memory/v1/dataMapping.ts b/rest/memory/v1/dataMapping.ts new file mode 100644 index 000000000..84657cfe6 --- /dev/null +++ b/rest/memory/v1/dataMapping.ts @@ -0,0 +1,1161 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * A data mapping connects external data sources to a Memory Store, enabling automatic ingestion and mapping of data to profile traits. + */ +export class CreateDataMappingInput { + /** + * Name of the data mapping. + */ + "displayName": string; + /** + * A human readable description of this resource, up to 512 characters. + */ + "description"?: string; + /** + * Flag indicating whether the data mapping is active. When true, data will be ingested and mapped according to the configuration. When false, the data mapping will be inactive and no data will be ingested into the Memory Store. + */ + "isEnabled"?: boolean; + "mappingTo": DataMappingToTraits; + "mappingFrom": DataMappingFromTypes; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + this.isEnabled = payload["isEnabled"]; + this.mappingTo = payload["mappingTo"]; + this.mappingFrom = payload["mappingFrom"]; + } +} + + +/** + * Writable fields of a data mapping. Used directly as the PATCH request body (all fields optional). Composed into CreateDataMappingInput via allOf. + */ +export class DataMappingCore { + /** + * Name of the data mapping. + */ + "displayName"?: string; + /** + * A human readable description of this resource, up to 512 characters. + */ + "description"?: string; + /** + * Flag indicating whether the data mapping is active. When true, data will be ingested and mapped according to the configuration. When false, the data mapping will be inactive and no data will be ingested into the Memory Store. + */ + "isEnabled"?: boolean; + "mappingTo"?: DataMappingToTraits; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + this.isEnabled = payload["isEnabled"]; + this.mappingTo = payload["mappingTo"]; + } +} + + +/** + * Details of where to map data items from. Each data mapping from type has its own set of configuration parameters and source specific properties. + */ +export class DataMappingFromTypes { + /** + * The source data type, which determines the source of the data and the required configuration parameters. + */ + "type": string; + /** + * The list of CSV column names that serve as the source fields. + */ + "columns": Array<string>; + /** + * The unique identifier of the TDI dataset to connect. + */ + "datasetId": string; + + constructor(payload) { + this.type = payload["type"]; + this.columns = payload["columns"]; + this.datasetId = payload["datasetId"]; + } +} + + +/** + * Configuration for mapping data to traits in a Memory Store. + */ +export class DataMappingToTraits { + /** + * The destination data type, which determines where to write the data and the required configuration parameters. + */ + "type": string; + /** + * The list of field to trait mappings. + */ + "mappings": Array<MappingTraitItem>; + + constructor(payload) { + this.type = payload["type"]; + this.mappings = payload["mappings"]; + } +} + + +/** + * The type of data mapping defining how data flows into the Memory Store. + */ +export type DataMappingType = 'CSV'|'DATASET'; + +/** + * Maps a field from a source to a Trait in the Memory Store. + */ +export class MappingTraitItem { + /** + * The expression identifying the field/column in the source. + */ + "expression": string; + /** + * The name of the Trait Group to map to. + */ + "traitGroup": string; + /** + * The name of the trait within the Trait Group to map to. + */ + "traitName": string; + + constructor(payload) { + this.expression = payload["expression"]; + this.traitGroup = payload["traitGroup"]; + this.traitName = payload["traitName"]; + } +} + + + + + +/** + * Options to pass to patch a DataMappingInstance + */ +export interface DataMappingContextPatchOptions { + /** Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource\'s current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. */ + "ifMatch"?: string; + /** */ + "dataMappingCore"?: DataMappingCore; +} + +/** + * Options to pass to create a DataMappingInstance + */ +export interface DataMappingListInstanceCreateOptions { + /** */ + "createDataMappingInput": CreateDataMappingInput; +} + +/** + * Options to pass to each + */ +export interface DataMappingListInstanceEachOptions { + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Filter data mappings by type. */ + "type"?: DataMappingType; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DataMappingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DataMappingListInstanceOptions { + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Filter data mappings by type. */ + "type"?: DataMappingType; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DataMappingListInstancePageOptions { + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Filter data mappings by type. */ + "type"?: DataMappingType; +} + + +export interface DataMappingContext { + + /** + * Remove a DataMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance + */ + remove(callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance> + + /** + * Remove a DataMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>> + + /** + * Fetch a DataMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance + */ + fetch(callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance> + + /** + * Fetch a DataMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>> + + /** + * Patch a DataMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance + */ + patch(callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance>; + /** + * Patch a DataMappingInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance + */ + patch(params: DataMappingCore, headers?: any, callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance>; + + /** + * Patch a DataMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance with HTTP metadata + */ + patchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>>; + /** + * Patch a DataMappingInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance with HTTP metadata + */ + patchWithHttpInfo(params: DataMappingCore, headers?: any, callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DataMappingContextSolution { + "storeId": string; + "dataMappingId": string; +} + +export class DataMappingContextImpl implements DataMappingContext { + protected _solution: DataMappingContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, storeId: string, dataMappingId: string) { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(dataMappingId)) { + throw new Error('Parameter \'dataMappingId\' is not valid.'); + } + + this._solution = { storeId, dataMappingId, }; + this._uri = `/ControlPlane/Stores/${storeId}/DataMappings/${dataMappingId}`; + } + + remove(callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "delete", headers}); + + operationPromise = operationPromise.then(payload => new DataMappingInstance(operationVersion, payload, instance._solution.storeId, instance._solution.dataMappingId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // DELETE operation that returns a response model + let operationPromise = operationVersion.fetchWithResponseInfo<DataMappingResource>({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<DataMappingInstance> => ({ + ...response, + body: new DataMappingInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.dataMappingId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DataMappingInstance(operationVersion, payload, instance._solution.storeId, instance._solution.dataMappingId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DataMappingResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DataMappingInstance> => ({ + ...response, + body: new DataMappingInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.dataMappingId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patch(params?: DataMappingCore | ((error: Error | null, item?: DataMappingInstance) => any), headers?: any,callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<DataMappingCore> as DataMappingCore; + } else { + params = params || {} as Partial<DataMappingCore> as DataMappingCore; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.patch({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new DataMappingInstance(operationVersion, payload, instance._solution.storeId, instance._solution.dataMappingId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patchWithHttpInfo(params?: DataMappingCore | ((error: Error | null, item?: ApiResponse<DataMappingInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<DataMappingCore> as DataMappingCore; + } else { + params = params || {} as Partial<DataMappingCore> as DataMappingCore; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.patchWithResponseInfo<DataMappingResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<DataMappingInstance> => ({ + ...response, + body: new DataMappingInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.dataMappingId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for CreateDataMappingInput + */ +export interface CreateDataMappingInput { + displayName: string; + description?: string; + isEnabled?: boolean; + mappingTo: DataMappingToTraits; + mappingFrom: DataMappingFromTypes; +} + +/** + * Nested model for DataMappingCore + */ +export interface DataMappingCore { + displayName?: string; + description?: string; + isEnabled?: boolean; + mappingTo?: DataMappingToTraits; +} + +/** + * Nested model for DataMappingFromTypes + */ +export interface DataMappingFromTypes { + type: string; + columns: Array<string>; + datasetId: string; +} + +/** + * Nested model for DataMappingToTraits + */ +export interface DataMappingToTraits { + type: string; + mappings: Array<MappingTraitItem>; +} + +/** + * Nested model for MappingTraitItem + */ +export interface MappingTraitItem { + expression: string; + traitGroup: string; + traitName: string; +} + + + + interface DataMappingPayload extends TokenPaginationPayload { + dataMappings: DataMappingResource[]; +} + +/** + * Response model for CreateDataMapping202Response operations + */ +interface CreateDataMapping202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Response model for PatchDataMapping202Response operations + */ +interface PatchDataMapping202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Response model for DataMapping operations + */ +interface DataMapping_ResponseResource { + displayName: string; + description?: string; + isEnabled?: boolean; + mappingTo: DataMappingToTraits; + mappingFrom: DataMappingFromTypes; + id: string; + createdAt: Date; + updatedAt: Date; + version: number; +} + +/** + * Response model for DeleteDataMapping202Response operations + */ +interface DeleteDataMapping202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Union type for all possible response models + */ +type DataMappingResource = CreateDataMapping202Response_ResponseResource | PatchDataMapping202Response_ResponseResource | DataMapping_ResponseResource | DeleteDataMapping202Response_ResponseResource; + +export class DataMappingInstance { + protected _solution: DataMappingContextSolution; + protected _context?: DataMappingContext; + + constructor(protected _version: V1, _payload: DataMappingResource, storeId: string, dataMappingId?: string) { + const payload: any = _payload; + this.message = (payload.message); + this.statusUrl = (payload.statusUrl); + this.displayName = (payload.displayName); + this.description = (payload.description); + this.isEnabled = (payload.isEnabled); + this.mappingTo = payload.mappingTo !== null && payload.mappingTo !== undefined ? new DataMappingToTraits(payload.mappingTo) : null; + this.mappingFrom = payload.mappingFrom !== null && payload.mappingFrom !== undefined ? new DataMappingFromTypes(payload.mappingFrom) : null; + this.id = (payload.id); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + this.version = deserialize.integer(payload.version); + + this._solution = { storeId, dataMappingId: dataMappingId, }; + } + + message?: string; + /** + * URI to check operation status. + */ + statusUrl?: string; + /** + * Name of the data mapping. + */ + displayName?: string; + /** + * A human readable description of this resource, up to 512 characters. + */ + description?: string; + /** + * Flag indicating whether the data mapping is active. When true, data will be ingested and mapped according to the configuration. When false, the data mapping will be inactive and no data will be ingested into the Memory Store. + */ + isEnabled?: boolean; + mappingTo?: DataMappingToTraits; + mappingFrom?: DataMappingFromTypes; + /** + * The unique identifier for the data mapping. + */ + id?: string; + /** + * The ISO 8601 timestamp when the data mapping was created. + */ + createdAt?: Date; + /** + * The ISO 8601 timestamp when the data mapping was last updated. + */ + updatedAt?: Date; + /** + * The current version number of the DataMapping. Incremented on each successful update. + */ + version?: number; + + private get _proxy(): DataMappingContext { + this._context = this._context || new DataMappingContextImpl(this._version, this._solution.storeId, this._solution.dataMappingId); + return this._context; + } + + /** + * Remove a DataMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance + */ + remove(callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a DataMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a DataMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance + */ + fetch(callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DataMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Patch a DataMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance + */ + patch(callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance>; + /** + * Patch a DataMappingInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance + */ + patch(params: DataMappingCore, headers?: any, callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance>; + + patch(params?: any, callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance> + { + return this._proxy.patch(params, callback); + } + + /** + * Patch a DataMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance with HTTP metadata + */ + patchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>>; + /** + * Patch a DataMappingInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance with HTTP metadata + */ + patchWithHttpInfo(params: DataMappingCore, headers?: any, callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>>; + + patchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>> + { + return this._proxy.patchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + statusUrl: this.statusUrl, + displayName: this.displayName, + description: this.description, + isEnabled: this.isEnabled, + mappingTo: this.mappingTo, + mappingFrom: this.mappingFrom, + id: this.id, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + version: this.version, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DataMappingSolution { + storeId: string; +} + +export interface DataMappingListInstance { + _version: V1; + _solution: DataMappingSolution; + _uri: string; + + (dataMappingId: string, ): DataMappingContext; + get(dataMappingId: string, ): DataMappingContext; + + + + + + + + + /** + * Create a DataMappingInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance + */ + create(params: CreateDataMappingInput, headers?: any, callback?: (error: Error | null, item?: DataMappingInstance) => any): Promise<DataMappingInstance>; + + /** + * Create a DataMappingInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DataMappingInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateDataMappingInput, headers?: any, callback?: (error: Error | null, item?: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>>; + + + + + /** + * Streams DataMappingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DataMappingInstance, done: (err?: Error) => void) => void): void; + each(params: DataMappingListInstanceEachOptions, callback?: (item: DataMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DataMappingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DataMappingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DataMappingListInstanceEachOptions, callback?: (item: DataMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DataMappingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DataMappingPage) => any): Promise<DataMappingPage>; + /** + * Retrieve a single target page of DataMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<DataMappingPage>) => any): Promise<ApiResponse<DataMappingPage>>; + /** + * Lists DataMappingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DataMappingInstance[]) => any): Promise<DataMappingInstance[]>; + list(params: DataMappingListInstanceOptions, callback?: (error: Error | null, items: DataMappingInstance[]) => any): Promise<DataMappingInstance[]>; + /** + * Lists DataMappingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DataMappingInstance[]>) => any): Promise<ApiResponse<DataMappingInstance[]>>; + listWithHttpInfo(params: DataMappingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<DataMappingInstance[]>) => any): Promise<ApiResponse<DataMappingInstance[]>>; + /** + * Retrieve a single page of DataMappingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DataMappingPage) => any): Promise<DataMappingPage>; + page(params: DataMappingListInstancePageOptions, callback?: (error: Error | null, items: DataMappingPage) => any): Promise<DataMappingPage>; + /** + * Retrieve a single page of DataMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DataMappingPage>) => any): Promise<ApiResponse<DataMappingPage>>; + pageWithHttpInfo(params: DataMappingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<DataMappingPage>) => any): Promise<ApiResponse<DataMappingPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DataMappingListInstance(version: V1, storeId: string): DataMappingListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + const instance = ((dataMappingId, ) => instance.get(dataMappingId, )) as DataMappingListInstance; + + instance.get = function get(dataMappingId, ): DataMappingContext { + return new DataMappingContextImpl(version, storeId, dataMappingId); + } + + instance._version = version; + instance._solution = { storeId, }; + instance._uri = `/ControlPlane/Stores/${storeId}/DataMappings`; + + instance.create = function create(params: CreateDataMappingInput, headers?: any, callback?: (error: Error | null, items: DataMappingInstance) => any): Promise<DataMappingInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DataMappingInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateDataMappingInput, headers?: any, callback?: (error: Error | null, items: ApiResponse<DataMappingInstance>) => any): Promise<ApiResponse<DataMappingInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<DataMappingResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<DataMappingInstance> => ({ + ...response, + body: new DataMappingInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: DataMappingListInstancePageOptions | ((error: Error | null, items: DataMappingPage) => any), callback?: (error: Error | null, items: DataMappingPage) => any): Promise<DataMappingPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + if (params["type"] !== undefined) + data["type"] = params["type"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DataMappingPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DataMappingPage) => any): Promise<DataMappingPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DataMappingPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DataMappingListInstancePageOptions | ((error: Error | null, items: ApiResponse<DataMappingPage>) => any), callback?: (error: Error | null, items: ApiResponse<DataMappingPage>) => any): Promise<ApiResponse<DataMappingPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + if (params["type"] !== undefined) + data["type"] = params["type"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<DataMappingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DataMappingPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<DataMappingPage>) => any): Promise<ApiResponse<DataMappingPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<DataMappingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DataMappingPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class DataMappingPage extends TokenPage<V1, DataMappingPayload, DataMappingResource, DataMappingInstance> { +/** +* Initialize the DataMappingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, uri: string, params: any, solution: DataMappingSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of DataMappingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DataMappingResource): DataMappingInstance { + + return new DataMappingInstance( + this._version, + payload, + this._solution.storeId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/memory/v1/identifier.ts b/rest/memory/v1/identifier.ts new file mode 100644 index 000000000..de996e230 --- /dev/null +++ b/rest/memory/v1/identifier.ts @@ -0,0 +1,812 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Represents a single identifier value paired with its `idType`. Write operations obey limits, uniqueness, and normalization rules configured via identifier settings. + */ +export class Identifier { + /** + * Identifier type as configured in the service\'s Identity Resolution Settings. + */ + "idType": string; + /** + * Raw value captured for the identifier. The service may normalize this value according to the `normalization` rule defined in the identifier settings before storage or matching (for example E.164 formatting for phone numbers). + */ + "value": string; + + constructor(payload) { + this.idType = payload["idType"]; + this.value = payload["value"]; + } +} + + +export class IdentifierUpdate { + /** + * The identifier type to update (e.g., email, phone). + */ + "idType": string; + /** + * Existing stored value to replace. + */ + "oldValue": string; + /** + * New value to store for the identifier. Normalization rules from the corresponding identifier settings apply. + */ + "newValue": string; + + constructor(payload) { + this.idType = payload["idType"]; + this.oldValue = payload["oldValue"]; + this.newValue = payload["newValue"]; + } +} + + + +/** + * Options to pass to remove a IdentifierInstance + */ +export interface IdentifierContextRemoveOptions { + /** When true, removes every stored value for the identifier type in a single operation. Defaults to false. */ + "removeAll"?: boolean; +} + + +/** + * Options to pass to patch a IdentifierInstance + */ +export interface IdentifierContextPatchOptions { + /** */ + "identifierUpdate": IdentifierUpdate; +} + +/** + * Options to pass to create a IdentifierInstance + */ +export interface IdentifierListInstanceCreateOptions { + /** */ + "identifier": Identifier; +} + +/** + * Options to pass to list + */ +export interface IdentifierListInstanceOptions { + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + + +export interface IdentifierContext { + + /** + * Remove a IdentifierInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance + */ + remove(callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance>; + /** + * Remove a IdentifierInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance + */ + remove(params: IdentifierContextRemoveOptions, callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance>; + + /** + * Remove a IdentifierInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>>; + /** + * Remove a IdentifierInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance with HTTP metadata + */ + removeWithHttpInfo(params: IdentifierContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>>; + + /** + * Fetch a IdentifierInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance + */ + fetch(callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance> + + /** + * Fetch a IdentifierInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>> + + /** + * Patch a IdentifierInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance + */ + patch(params: IdentifierUpdate, headers?: any, callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance>; + + /** + * Patch a IdentifierInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance with HTTP metadata + */ + patchWithHttpInfo(params: IdentifierUpdate, headers?: any, callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface IdentifierContextSolution { + "storeId": string; + "profileId": string; + "idType": string; +} + +export class IdentifierContextImpl implements IdentifierContext { + protected _solution: IdentifierContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, storeId: string, profileId: string, idType: string) { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(profileId)) { + throw new Error('Parameter \'profileId\' is not valid.'); + } + + if (!isValidPathParam(idType)) { + throw new Error('Parameter \'idType\' is not valid.'); + } + + this._solution = { storeId, profileId, idType, }; + this._uri = `/Stores/${storeId}/Profiles/${profileId}/Identifiers/${idType}`; + } + + remove(params?: IdentifierContextRemoveOptions | ((error: Error | null, item?: IdentifierInstance) => any),callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["removeAll"] !== undefined) + data["removeAll"] = serialize.bool(params["removeAll"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "delete", params: data, headers}); + + operationPromise = operationPromise.then(payload => new IdentifierInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId, instance._solution.idType)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: IdentifierContextRemoveOptions | ((error: Error | null, item?: ApiResponse<IdentifierInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["removeAll"] !== undefined) + data["removeAll"] = serialize.bool(params["removeAll"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // DELETE operation that returns a response model + let operationPromise = operationVersion.fetchWithResponseInfo<IdentifierResource>({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse<IdentifierInstance> => ({ + ...response, + body: new IdentifierInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId, instance._solution.idType) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new IdentifierInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId, instance._solution.idType)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<IdentifierResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<IdentifierInstance> => ({ + ...response, + body: new IdentifierInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId, instance._solution.idType) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patch(params: IdentifierUpdate, headers?: any,callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.patch({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new IdentifierInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId, instance._solution.idType)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patchWithHttpInfo(params: IdentifierUpdate, headers?: any,callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.patchWithResponseInfo<IdentifierResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<IdentifierInstance> => ({ + ...response, + body: new IdentifierInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId, instance._solution.idType) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for Identifier + */ +export interface Identifier { + idType: string; + value: string; +} + +/** + * Nested model for IdentifierUpdate + */ +export interface IdentifierUpdate { + idType: string; + oldValue: string; + newValue: string; +} + + + + + +/** + * Response model for CreateProfileIdentifier202Response operations + */ +interface CreateProfileIdentifier202Response_ResponseResource { + message: string; +} + +/** + * Response model for IdentifierSet operations + */ +interface IdentifierSet_ResponseResource { + idType: string; + values: Array<string>; +} + +/** + * Response model for DeleteProfileIdentifier202Response operations + */ +interface DeleteProfileIdentifier202Response_ResponseResource { + message: string; +} + +/** + * Response model for PatchProfileIdentifier202Response operations + */ +interface PatchProfileIdentifier202Response_ResponseResource { + message: string; +} + +/** + * Union type for all possible response models + */ +type IdentifierResource = CreateProfileIdentifier202Response_ResponseResource | IdentifierSet_ResponseResource | DeleteProfileIdentifier202Response_ResponseResource | PatchProfileIdentifier202Response_ResponseResource; + +export class IdentifierInstance { + protected _solution: IdentifierContextSolution; + protected _context?: IdentifierContext; + + constructor(protected _version: V1, _payload: IdentifierResource, storeId: string, profileId: string, idType?: string) { + const payload: any = _payload; + this.message = (payload.message); + this.idType = (payload.idType); + this.values = (payload.values); + + this._solution = { storeId, profileId, idType: idType, }; + } + + message?: string; + /** + * Identifier type defined in Identity Resolution Settings. + */ + idType?: string; + /** + * Server managed collection of stored values for the identifier type. Identifier values are normalized according to the corresponding identifier settings and ordered chronologically. + */ + values?: Array<string>; + + private get _proxy(): IdentifierContext { + this._context = this._context || new IdentifierContextImpl(this._version, this._solution.storeId, this._solution.profileId, this._solution.idType); + return this._context; + } + + /** + * Remove a IdentifierInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance + */ + remove(callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance>; + /** + * Remove a IdentifierInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance + */ + remove(params: IdentifierContextRemoveOptions, callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance>; + + remove(params?: any, callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance> + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a IdentifierInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>>; + /** + * Remove a IdentifierInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance with HTTP metadata + */ + removeWithHttpInfo(params: IdentifierContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a IdentifierInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance + */ + fetch(callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a IdentifierInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Patch a IdentifierInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance + */ + patch(params: IdentifierUpdate, headers?: any, callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance>; + + patch(params?: any, callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance> + { + return this._proxy.patch(params, callback); + } + + /** + * Patch a IdentifierInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance with HTTP metadata + */ + patchWithHttpInfo(params: IdentifierUpdate, headers?: any, callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>>; + + patchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>> + { + return this._proxy.patchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + idType: this.idType, + values: this.values, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface IdentifierSolution { + storeId: string; + profileId: string; +} + +export interface IdentifierListInstance { + _version: V1; + _solution: IdentifierSolution; + _uri: string; + + (idType: string, ): IdentifierContext; + get(idType: string, ): IdentifierContext; + + + + + + + + + /** + * Create a IdentifierInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance + */ + create(params: Identifier, headers?: any, callback?: (error: Error | null, item?: IdentifierInstance) => any): Promise<IdentifierInstance>; + + /** + * Create a IdentifierInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentifierInstance with HTTP metadata + */ + createWithHttpInfo(params: Identifier, headers?: any, callback?: (error: Error | null, item?: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>>; + + + + + /** + * Lists IdentifierInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IdentifierListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: IdentifierInstance[]) => any): Promise<IdentifierInstance[]>; + + /** + * Lists IdentifierInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IdentifierListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<IdentifierInstance[]>) => any): Promise<ApiResponse<IdentifierInstance[]>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function IdentifierListInstance(version: V1, storeId: string, profileId: string): IdentifierListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(profileId)) { + throw new Error('Parameter \'profileId\' is not valid.'); + } + + const instance = ((idType, ) => instance.get(idType, )) as IdentifierListInstance; + + instance.get = function get(idType, ): IdentifierContext { + return new IdentifierContextImpl(version, storeId, profileId, idType); + } + + instance._version = version; + instance._solution = { storeId, profileId, }; + instance._uri = `/Stores/${storeId}/Profiles/${profileId}/Identifiers`; + + instance.create = function create(params: Identifier, headers?: any, callback?: (error: Error | null, items: IdentifierInstance) => any): Promise<IdentifierInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IdentifierInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: Identifier, headers?: any, callback?: (error: Error | null, items: ApiResponse<IdentifierInstance>) => any): Promise<ApiResponse<IdentifierInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<IdentifierResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<IdentifierInstance> => ({ + ...response, + body: new IdentifierInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.list = function list( callback?: (error: Error | null, items: IdentifierInstance[]) => any): Promise<IdentifierInstance[]> { + const headers: any = {}; + const data: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + + + operationPromise = operationPromise.then((payload: any) => (payload["identifiers"] || []).map( + (item: any) => new IdentifierInstance(operationVersion, item, instance._solution.storeId, instance._solution.profileId) + )); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + + + + instance.listWithHttpInfo = function listWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<IdentifierInstance[]>) => any): Promise<ApiResponse<IdentifierInstance[]>> { + const headers: any = {}; + const data: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + + let operationPromise = operationVersion.fetchWithResponseInfo<IdentifierResource>({ uri: instance._uri, method: "get", headers}).then((response): ApiResponse<IdentifierInstance[]> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: ((response.body as any)["identifiers"] || []).map( + (item: any) => new IdentifierInstance(operationVersion, item, instance._solution.storeId, instance._solution.profileId) + ) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/memory/v1/identityResolutionSetting.ts b/rest/memory/v1/identityResolutionSetting.ts new file mode 100644 index 000000000..fbbff7ab8 --- /dev/null +++ b/rest/memory/v1/identityResolutionSetting.ts @@ -0,0 +1,353 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class IdentifierConfig { + /** + * Name of the identifier type. Usual values are email, phone, external_id etc. + */ + "idType": string; + /** + * The algorithm to use for matching identifier values. - `exact`, exact string match. - `fuzzy`, low precision match allowing for some variations. + */ + "matchingAlgo"?: string; + /** + * The `fuzzy` matching threshold percentage. + */ + "matchingThreshold"?: number; + /** + * Maximum number of historical values to retain. + */ + "limit"?: number; + /** + * Removal policy to apply when the number of values exceeds the limit and is based on the timestamp of the request when the identifier was added. - `fifo`: First In First Out, removes the oldest values first. - `lifo`: Last In First Out, removes the most recent values first. + */ + "limitPolicy"?: string; + /** + * When enabled, more than one profile may not share the same identifier value. Adding a shared identifier to a second profile may trigger a merge. Disabling creates a compound identifier where merges are only triggered if two or more identifiers satisfy a matching rule. + */ + "enforceUnique"?: boolean; + /** + * Normalization to apply to the identifier value before storing and matching. - `phone`: Normalize phone numbers to E.164 format. - `email`: Normalize email addresses by coverting to lowercase and removing spaces. - `trim`: Removes spaces from both ends of the string. - `none`: No normalization. **Important Note for Phone Number Normalization:** When using the `phone` normalization option, please adhere to the following guidelines to ensure proper formatting: - All US numbers must be at least valid 10 digit phone numbers with area code. They may also include or omit the \"+1\" prefix. - Non-US numbers must include a 1-3 digit country code (a \"+\" prefix is optional). Non-US national formats are not supported and will be interpreted as US numbers. + */ + "normalization"?: string; + + constructor(payload) { + this.idType = payload["idType"]; + this.matchingAlgo = payload["matchingAlgo"]; + this.matchingThreshold = payload["matchingThreshold"]; + this.limit = payload["limit"]; + this.limitPolicy = payload["limitPolicy"]; + this.enforceUnique = payload["enforceUnique"]; + this.normalization = payload["normalization"]; + } +} + + +/** + * Identity Resolution settings help determine if a new profile should be created, or if the incoming conversation should be added to an existing profile. These settings resolve how profiles are looked up and which profiles should merge together. + */ +export class IdentityResolutionSettingsCore { + /** + * List of identifier types and their resolution settings. + */ + "identifierConfigs": Array<IdentifierConfig>; + /** + * Priority list of identifiers to locate profiles to apply new data to, or for determining if two existing profiles should merge. Individual rules are evaluated with `OR` logic between them, meaning that satisfying any single rule will trigger a match. A compound identifier rule can be created with `AND` logic by combining multiple identifier types within the same rule definition such as \"email AND phone\", which requires all specified identifiers to be satisfied for a match. Rules are evaluated in order. - If no rule matches against existing profiles, a new profile will be created. - If a rule matches to a single existing profile, the profile will be updated. - If a rule matches to multiple existing profiles, those existing profiles will be merged. + */ + "matchingRules": Array<string>; + + constructor(payload) { + this.identifierConfigs = payload["identifierConfigs"]; + this.matchingRules = payload["matchingRules"]; + } +} + + + + +/** + * Options to pass to update a IdentityResolutionSettingInstance + */ +export interface IdentityResolutionSettingListInstanceUpdateOptions { + /** */ + "identityResolutionSettingsCore": IdentityResolutionSettingsCore; + /** Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource\'s current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. */ + "ifMatch"?: string; +} + + +export interface IdentityResolutionSettingSolution { + storeId: string; +} + +export interface IdentityResolutionSettingListInstance { + _version: V1; + _solution: IdentityResolutionSettingSolution; + _uri: string; + + + + /** + * Fetch a IdentityResolutionSettingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentityResolutionSettingInstance + */ + fetch(callback?: (error: Error | null, item?: IdentityResolutionSettingInstance) => any): Promise<IdentityResolutionSettingInstance> + + /** + * Fetch a IdentityResolutionSettingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentityResolutionSettingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IdentityResolutionSettingInstance>) => any): Promise<ApiResponse<IdentityResolutionSettingInstance>> + + + + /** + * Update a IdentityResolutionSettingInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentityResolutionSettingInstance + */ + update(params: IdentityResolutionSettingsCore, headers?: any, callback?: (error: Error | null, item?: IdentityResolutionSettingInstance) => any): Promise<IdentityResolutionSettingInstance>; + + /** + * Update a IdentityResolutionSettingInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IdentityResolutionSettingInstance with HTTP metadata + */ + updateWithHttpInfo(params: IdentityResolutionSettingsCore, headers?: any, callback?: (error: Error | null, item?: ApiResponse<IdentityResolutionSettingInstance>) => any): Promise<ApiResponse<IdentityResolutionSettingInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function IdentityResolutionSettingListInstance(version: V1, storeId: string): IdentityResolutionSettingListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + const instance = {} as IdentityResolutionSettingListInstance; + + instance._version = version; + instance._solution = { storeId, }; + instance._uri = `/ControlPlane/Stores/${storeId}/IdentityResolutionSettings`; + + instance.fetch = function fetch( callback?: (error: Error | null, items: IdentityResolutionSettingInstance) => any): Promise<IdentityResolutionSettingInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new IdentityResolutionSettingInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<IdentityResolutionSettingInstance>) => any): Promise<ApiResponse<IdentityResolutionSettingInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<IdentityResolutionSettingResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<IdentityResolutionSettingInstance> => ({ + ...response, + body: new IdentityResolutionSettingInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.update = function update(params: IdentityResolutionSettingsCore, headers?: any, callback?: (error: Error | null, items: IdentityResolutionSettingInstance) => any): Promise<IdentityResolutionSettingInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new IdentityResolutionSettingInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.updateWithHttpInfo = function updateWithHttpInfo(params: IdentityResolutionSettingsCore, headers?: any, callback?: (error: Error | null, items: ApiResponse<IdentityResolutionSettingInstance>) => any): Promise<ApiResponse<IdentityResolutionSettingInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<IdentityResolutionSettingResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<IdentityResolutionSettingInstance> => ({ + ...response, + body: new IdentityResolutionSettingInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + + +/** + * Response model for IdentityResolutionSettings operations + */ +interface IdentityResolutionSettings_ResponseResource { + identifierConfigs: Array<IdentifierConfig>; + matchingRules: Array<string>; + version: number; +} + +/** + * Response model for UpdateIdentityResolutionSettings202Response operations + */ +interface UpdateIdentityResolutionSettings202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Union type for all possible response models + */ +type IdentityResolutionSettingResource = IdentityResolutionSettings_ResponseResource | UpdateIdentityResolutionSettings202Response_ResponseResource; + +export class IdentityResolutionSettingInstance { + + constructor(protected _version: V1, _payload: IdentityResolutionSettingResource, storeId: string) { + const payload: any = _payload; + this.identifierConfigs = payload.identifierConfigs !== null && payload.identifierConfigs !== undefined ? payload.identifierConfigs.map( + (payload: any) => new IdentifierConfig(payload) + ) : null; + this.matchingRules = (payload.matchingRules); + this.version = deserialize.integer(payload.version); + this.message = (payload.message); + this.statusUrl = (payload.statusUrl); + + } + + /** + * List of identifier types and their resolution settings. + */ + identifierConfigs?: Array<IdentifierConfig>; + /** + * Priority list of identifiers to locate profiles to apply new data to, or for determining if two existing profiles should merge. Individual rules are evaluated with `OR` logic between them, meaning that satisfying any single rule will trigger a match. A compound identifier rule can be created with `AND` logic by combining multiple identifier types within the same rule definition such as \"email AND phone\", which requires all specified identifiers to be satisfied for a match. Rules are evaluated in order. - If no rule matches against existing profiles, a new profile will be created. - If a rule matches to a single existing profile, the profile will be updated. - If a rule matches to multiple existing profiles, those existing profiles will be merged. + */ + matchingRules?: Array<string>; + /** + * The current version number of the Identity Resolution Settings. Incremented on each successful update. + */ + version?: number; + message?: string; + /** + * URI to check operation status. + */ + statusUrl?: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + identifierConfigs: this.identifierConfigs, + matchingRules: this.matchingRules, + version: this.version, + message: this.message, + statusUrl: this.statusUrl, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/memory/v1/import.ts b/rest/memory/v1/import.ts new file mode 100644 index 000000000..92f107b21 --- /dev/null +++ b/rest/memory/v1/import.ts @@ -0,0 +1,586 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Mapping of a CSV header column to the trait fields + */ +export class ColumnMappingItem { + /** + * The name of the column in the CSV header + */ + "columnName": string; + /** + * The trait group to which this trait belongs + */ + "traitGroup": string; + /** + * The name of the trait in the trait group + */ + "traitName": string; + + constructor(payload) { + this.columnName = payload["columnName"]; + this.traitGroup = payload["traitGroup"]; + this.traitName = payload["traitName"]; + } +} + + +export class CreateProfilesImportV2Request { + /** + * The name of the file to generate a presigned URL + */ + "filename": string; + /** + * The size of the file in bytes (1 byte to 100 MiB) + */ + "fileSize": number; + /** + * Mappings of CSV header columns to traits\' fields + */ + "columnMappings": Array<ColumnMappingItem>; + + constructor(payload) { + this.filename = payload["filename"]; + this.fileSize = payload["fileSize"]; + this.columnMappings = payload["columnMappings"]; + } +} + + +/** + * Summary statistics of the import operation + */ +export class FetchProfileImportV2200ResponseSummary { + /** + * Total count of errors encountered during import + */ + "errors"?: number; + /** + * Total count of warnings encountered during import + */ + "warnings"?: number; + + constructor(payload) { + this.errors = payload["errors"]; + this.warnings = payload["warnings"]; + } +} + + + + +/** + * Options to pass to create a ImportInstance + */ +export interface ImportListInstanceCreateOptions { + /** */ + "createProfilesImportV2Request": CreateProfilesImportV2Request; +} + +/** + * Options to pass to list + */ +export interface ImportListInstanceOptions { + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + + +export interface ImportContext { + + /** + * Fetch a ImportInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ImportInstance + */ + fetch(callback?: (error: Error | null, item?: ImportInstance) => any): Promise<ImportInstance> + + /** + * Fetch a ImportInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ImportInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ImportInstance>) => any): Promise<ApiResponse<ImportInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ImportContextSolution { + "storeId": string; + "importId": string; +} + +export class ImportContextImpl implements ImportContext { + protected _solution: ImportContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, storeId: string, importId: string) { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(importId)) { + throw new Error('Parameter \'importId\' is not valid.'); + } + + this._solution = { storeId, importId, }; + this._uri = `/Stores/${storeId}/Profiles/Imports/${importId}`; + } + + fetch(callback?: (error: Error | null, item?: ImportInstance) => any): Promise<ImportInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ImportInstance(operationVersion, payload, instance._solution.storeId, instance._solution.importId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ImportInstance>) => any): Promise<ApiResponse<ImportInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ImportResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ImportInstance> => ({ + ...response, + body: new ImportInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.importId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for ColumnMappingItem + */ +export interface ColumnMappingItem { + columnName: string; + traitGroup: string; + traitName: string; +} + +/** + * Nested model for CreateProfilesImportV2Request + */ +export interface CreateProfilesImportV2Request { + filename: string; + fileSize: number; + columnMappings: Array<ColumnMappingItem>; +} + +/** + * Nested model for FetchProfileImportV2200ResponseSummary + */ +export interface FetchProfileImportV2200ResponseSummary { + errors?: number; + warnings?: number; +} + + + + + +/** + * Response model for FetchProfileImportV2200Response operations + */ +interface FetchProfileImportV2200Response_ResponseResource { + status: string; + filename: string; + createdAt: Date; + updatedAt?: Date; + fileSize?: number; + columnMappings?: Array<ColumnMappingItem>; + summary?: FetchProfileImportV2200ResponseSummary; +} + +/** + * Response model for CreateProfilesImportV2201Response operations + */ +interface CreateProfilesImportV2201Response_ResponseResource { + importId: string; + url: string; +} + +/** + * Response model for ListProfileImportsV2200Response operations + */ +interface ListProfileImportsV2200Response_ResponseResource { + imports?: Array<string>; +} + +/** + * Union type for all possible response models + */ +type ImportResource = FetchProfileImportV2200Response_ResponseResource | CreateProfilesImportV2201Response_ResponseResource | ListProfileImportsV2200Response_ResponseResource; + +export class ImportInstance { + protected _solution: ImportContextSolution; + protected _context?: ImportContext; + + constructor(protected _version: V1, _payload: ImportResource, storeId: string, importId?: string) { + const payload: any = _payload; + this.status = (payload.status); + this.filename = (payload.filename); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + this.fileSize = deserialize.integer(payload.fileSize); + this.columnMappings = payload.columnMappings !== null && payload.columnMappings !== undefined ? payload.columnMappings.map( + (payload: any) => new ColumnMappingItem(payload) + ) : null; + this.summary = payload.summary !== null && payload.summary !== undefined ? new FetchProfileImportV2200ResponseSummary(payload.summary) : null; + this.importId = (payload.importId); + this.url = (payload.url); + this.imports = (payload.imports); + + this._solution = { storeId, importId: importId, }; + } + + /** + * Current processing status of the import task + */ + status?: string; + /** + * Original filename of the uploaded CSV + */ + filename?: string; + /** + * Timestamp when the import was created + */ + createdAt?: Date; + /** + * Timestamp when the import was last updated + */ + updatedAt?: Date; + /** + * Size of the uploaded file in bytes (1 byte to 100 MiB) + */ + fileSize?: number; + /** + * Mappings of CSV header columns to traits\' fields + */ + columnMappings?: Array<ColumnMappingItem>; + summary?: FetchProfileImportV2200ResponseSummary; + /** + * ID of the import task. + */ + importId?: string; + /** + * Pre-signed URL to upload the CSV via a single PUT request. + */ + url?: string; + imports?: Array<string>; + + private get _proxy(): ImportContext { + this._context = this._context || new ImportContextImpl(this._version, this._solution.storeId, this._solution.importId); + return this._context; + } + + /** + * Fetch a ImportInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ImportInstance + */ + fetch(callback?: (error: Error | null, item?: ImportInstance) => any): Promise<ImportInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ImportInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ImportInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ImportInstance>) => any): Promise<ApiResponse<ImportInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + status: this.status, + filename: this.filename, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + fileSize: this.fileSize, + columnMappings: this.columnMappings, + summary: this.summary, + importId: this.importId, + url: this.url, + imports: this.imports, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ImportSolution { + storeId: string; +} + +export interface ImportListInstance { + _version: V1; + _solution: ImportSolution; + _uri: string; + + (importId: string, ): ImportContext; + get(importId: string, ): ImportContext; + + + + + /** + * Create a ImportInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ImportInstance + */ + create(params: CreateProfilesImportV2Request, headers?: any, callback?: (error: Error | null, item?: ImportInstance) => any): Promise<ImportInstance>; + + /** + * Create a ImportInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ImportInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateProfilesImportV2Request, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ImportInstance>) => any): Promise<ApiResponse<ImportInstance>>; + + + + + /** + * Lists ImportInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ImportListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: string[]) => any): Promise<string[]>; + + /** + * Lists ImportInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ImportListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<string[]>) => any): Promise<ApiResponse<string[]>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ImportListInstance(version: V1, storeId: string): ImportListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + const instance = ((importId, ) => instance.get(importId, )) as ImportListInstance; + + instance.get = function get(importId, ): ImportContext { + return new ImportContextImpl(version, storeId, importId); + } + + instance._version = version; + instance._solution = { storeId, }; + instance._uri = `/Stores/${storeId}/Profiles/Imports`; + + instance.create = function create(params: CreateProfilesImportV2Request, headers?: any, callback?: (error: Error | null, items: ImportInstance) => any): Promise<ImportInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ImportInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateProfilesImportV2Request, headers?: any, callback?: (error: Error | null, items: ApiResponse<ImportInstance>) => any): Promise<ApiResponse<ImportInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ImportResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ImportInstance> => ({ + ...response, + body: new ImportInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.list = function list( callback?: (error: Error | null, items: string[]) => any): Promise<string[]> { + const headers: any = {}; + const data: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + + // Array items are primitives (strings, numbers), return them directly + operationPromise = operationPromise.then((payload: any) => payload["imports"] || []); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + + + + instance.listWithHttpInfo = function listWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<string[]>) => any): Promise<ApiResponse<string[]>> { + const headers: any = {}; + const data: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // Array items are primitives (strings, numbers), return them directly + let operationPromise = operationVersion.fetchWithResponseInfo<ImportResource>({ uri: instance._uri, method: "get", headers}).then((response): ApiResponse<string[]> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: ((response.body as any)["imports"] || []) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/memory/v1/lookup.ts b/rest/memory/v1/lookup.ts new file mode 100644 index 000000000..c4d1b07aa --- /dev/null +++ b/rest/memory/v1/lookup.ts @@ -0,0 +1,218 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Represents a single identifier value paired with its `idType`. Write operations obey limits, uniqueness, and normalization rules configured via identifier settings. + */ +export class Identifier { + /** + * Identifier type as configured in the service\'s Identity Resolution Settings. + */ + "idType": string; + /** + * Raw value captured for the identifier. The service may normalize this value according to the `normalization` rule defined in the identifier settings before storage or matching (for example E.164 formatting for phone numbers). + */ + "value": string; + + constructor(payload) { + this.idType = payload["idType"]; + this.value = payload["value"]; + } +} + + + +/** + * Options to pass to create a LookupInstance + */ +export interface LookupListInstanceCreateOptions { + /** */ + "identifier": Identifier; +} + + +export interface LookupSolution { + storeId: string; +} + +export interface LookupListInstance { + _version: V1; + _solution: LookupSolution; + _uri: string; + + + + /** + * Create a LookupInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupInstance + */ + create(params: Identifier, headers?: any, callback?: (error: Error | null, item?: LookupInstance) => any): Promise<LookupInstance>; + + /** + * Create a LookupInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LookupInstance with HTTP metadata + */ + createWithHttpInfo(params: Identifier, headers?: any, callback?: (error: Error | null, item?: ApiResponse<LookupInstance>) => any): Promise<ApiResponse<LookupInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function LookupListInstance(version: V1, storeId: string): LookupListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + const instance = {} as LookupListInstance; + + instance._version = version; + instance._solution = { storeId, }; + instance._uri = `/Stores/${storeId}/Profiles/Lookup`; + + instance.create = function create(params: Identifier, headers?: any, callback?: (error: Error | null, items: LookupInstance) => any): Promise<LookupInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new LookupInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: Identifier, headers?: any, callback?: (error: Error | null, items: ApiResponse<LookupInstance>) => any): Promise<ApiResponse<LookupInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<LookupResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<LookupInstance> => ({ + ...response, + body: new LookupInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + + +interface LookupResource { + normalizedValue: string; + profiles: Array<string>; +} + +export class LookupInstance { + + constructor(protected _version: V1, _payload: LookupResource, storeId: string) { + const payload = _payload; + this.normalizedValue = (payload.normalizedValue); + this.profiles = (payload.profiles); + + } + + /** + * Identifier value after normalization that was used for the lookup. + */ + normalizedValue: string; + profiles: Array<string>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + normalizedValue: this.normalizedValue, + profiles: this.profiles, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/memory/v1/observation.ts b/rest/memory/v1/observation.ts new file mode 100644 index 000000000..d4dd171ac --- /dev/null +++ b/rest/memory/v1/observation.ts @@ -0,0 +1,1081 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Request payload for creating one or more observations. Supports creation of up to 10 observations. + */ +export class CreateObservationsRequest { + /** + * Array of observations to create in a single batch operation. + */ + "observations": Array<ObservationCreateRequest>; + + constructor(payload) { + this.observations = payload["observations"]; + } +} + + +/** + * Core mutable properties for creating observation objects. + */ +export class ObservationBase { + /** + * The main content of the observation. + */ + "content"?: string; + /** + * The timestamp when the observation originally occurred. + */ + "occurredAt"?: Date; + /** + * The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + */ + "source"?: string; + /** + * Array of conversation IDs associated with this observation. + */ + "conversationIds"?: Array<string>; + + constructor(payload) { + this.content = payload["content"]; + this.occurredAt = payload["occurredAt"]; + this.source = payload["source"]; + this.conversationIds = payload["conversationIds"]; + } +} + + +export class ObservationCreateRequest { + /** + * The main content of the observation. + */ + "content": string; + /** + * The timestamp when the observation originally occurred. + */ + "occurredAt": Date; + /** + * The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + */ + "source": string; + /** + * Array of conversation IDs associated with this observation. + */ + "conversationIds"?: Array<string>; + + constructor(payload) { + this.content = payload["content"]; + this.occurredAt = payload["occurredAt"]; + this.source = payload["source"]; + this.conversationIds = payload["conversationIds"]; + } +} + + + + + +/** + * Options to pass to patch a ObservationInstance + */ +export interface ObservationContextPatchOptions { + /** */ + "observationBase": ObservationBase; +} + +/** + * Options to pass to create a ObservationInstance + */ +export interface ObservationListInstanceCreateOptions { + /** */ + "createObservationsRequest": CreateObservationsRequest; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; + /** Compression algorithm used for the request body (e.g., gzip, deflate, br) */ + "contentEncoding"?: 'gzip' | 'deflate' | 'br' | 'compress'; +} + +/** + * Options to pass to each + */ +export interface ObservationListInstanceEachOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. */ + "source"?: string; + /** Filter observations created after this timestamp (inclusive). */ + "createdAfter"?: Date; + /** Filter observations created before this timestamp (exclusive). */ + "createdBefore"?: Date; + /** Filter by conversation ID. Returns only items associated with the specified conversation. */ + "conversationId"?: string; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ObservationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ObservationListInstanceOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. */ + "source"?: string; + /** Filter observations created after this timestamp (inclusive). */ + "createdAfter"?: Date; + /** Filter observations created before this timestamp (exclusive). */ + "createdBefore"?: Date; + /** Filter by conversation ID. Returns only items associated with the specified conversation. */ + "conversationId"?: string; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ObservationListInstancePageOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. */ + "source"?: string; + /** Filter observations created after this timestamp (inclusive). */ + "createdAfter"?: Date; + /** Filter observations created before this timestamp (exclusive). */ + "createdBefore"?: Date; + /** Filter by conversation ID. Returns only items associated with the specified conversation. */ + "conversationId"?: string; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; +} + + +export interface ObservationContext { + + /** + * Remove a ObservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance + */ + remove(callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance> + + /** + * Remove a ObservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>> + + /** + * Fetch a ObservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance + */ + fetch(callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance> + + /** + * Fetch a ObservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>> + + /** + * Patch a ObservationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance + */ + patch(params: ObservationBase, headers?: any, callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance>; + + /** + * Patch a ObservationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance with HTTP metadata + */ + patchWithHttpInfo(params: ObservationBase, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ObservationContextSolution { + "storeId": string; + "profileId": string; + "observationId": string; +} + +export class ObservationContextImpl implements ObservationContext { + protected _solution: ObservationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, storeId: string, profileId: string, observationId: string) { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(profileId)) { + throw new Error('Parameter \'profileId\' is not valid.'); + } + + if (!isValidPathParam(observationId)) { + throw new Error('Parameter \'observationId\' is not valid.'); + } + + this._solution = { storeId, profileId, observationId, }; + this._uri = `/Stores/${storeId}/Profiles/${profileId}/Observations/${observationId}`; + } + + remove(callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "delete", headers}); + + operationPromise = operationPromise.then(payload => new ObservationInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId, instance._solution.observationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // DELETE operation that returns a response model + let operationPromise = operationVersion.fetchWithResponseInfo<ObservationResource>({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<ObservationInstance> => ({ + ...response, + body: new ObservationInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId, instance._solution.observationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ObservationInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId, instance._solution.observationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ObservationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ObservationInstance> => ({ + ...response, + body: new ObservationInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId, instance._solution.observationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patch(params: ObservationBase, headers?: any,callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.patch({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new ObservationInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId, instance._solution.observationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patchWithHttpInfo(params: ObservationBase, headers?: any,callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.patchWithResponseInfo<ObservationResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<ObservationInstance> => ({ + ...response, + body: new ObservationInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId, instance._solution.observationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for CreateObservationsRequest + */ +export interface CreateObservationsRequest { + observations: Array<ObservationCreateRequest>; +} + +/** + * Nested model for ObservationBase + */ +export interface ObservationBase { + content?: string; + occurredAt?: Date; + source?: string; + conversationIds?: Array<string>; +} + +/** + * Nested model for ObservationCreateRequest + */ +export interface ObservationCreateRequest { + content: string; + occurredAt: Date; + source: string; + conversationIds?: Array<string>; +} + + + + interface ObservationPayload extends TokenPaginationPayload { + observations: ObservationResource[]; +} + +/** + * Response model for DeleteProfileObservation202Response operations + */ +interface DeleteProfileObservation202Response_ResponseResource { + message: string; +} + +/** + * Response model for ObservationCreatedResponse operations + */ +interface ObservationCreatedResponse_ResponseResource { + message: string; +} + +/** + * Response model for PatchProfileObservation202Response operations + */ +interface PatchProfileObservation202Response_ResponseResource { + message: string; +} + +/** + * Response model for ObservationInfo operations + */ +interface ObservationInfo_ResponseResource { + content?: string; + occurredAt?: Date; + source?: string; + conversationIds?: Array<string>; + id: string; + createdAt: Date; + updatedAt: Date; +} + +/** + * Union type for all possible response models + */ +type ObservationResource = DeleteProfileObservation202Response_ResponseResource | ObservationCreatedResponse_ResponseResource | PatchProfileObservation202Response_ResponseResource | ObservationInfo_ResponseResource; + +/** + * Response for batch observation creation. + */ +export class ObservationInstance { + protected _solution: ObservationContextSolution; + protected _context?: ObservationContext; + + constructor(protected _version: V1, _payload: ObservationResource, storeId: string, profileId: string, observationId?: string) { + const payload: any = _payload; + this.message = (payload.message); + this.content = (payload.content); + this.occurredAt = deserialize.iso8601DateTime(payload.occurredAt); + this.source = (payload.source); + this.conversationIds = (payload.conversationIds); + this.id = (payload.id); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + + this._solution = { storeId, profileId, observationId: observationId, }; + } + + message?: string; + /** + * The main content of the observation. + */ + content?: string; + /** + * The timestamp when the observation originally occurred. + */ + occurredAt?: Date; + /** + * The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + */ + source?: string; + /** + * Array of conversation IDs associated with this observation. + */ + conversationIds?: Array<string>; + /** + * A unique identifier for the observation using Twilio Type ID (TTID) format. + */ + id?: string; + /** + * The timestamp when the observation was created. + */ + createdAt?: Date; + /** + * The timestamp when the observation was last updated. + */ + updatedAt?: Date; + + private get _proxy(): ObservationContext { + this._context = this._context || new ObservationContextImpl(this._version, this._solution.storeId, this._solution.profileId, this._solution.observationId); + return this._context; + } + + /** + * Remove a ObservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance + */ + remove(callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ObservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ObservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance + */ + fetch(callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ObservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Patch a ObservationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance + */ + patch(params: ObservationBase, headers?: any, callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance>; + + patch(params?: any, callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance> + { + return this._proxy.patch(params, callback); + } + + /** + * Patch a ObservationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance with HTTP metadata + */ + patchWithHttpInfo(params: ObservationBase, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>>; + + patchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>> + { + return this._proxy.patchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + content: this.content, + occurredAt: this.occurredAt, + source: this.source, + conversationIds: this.conversationIds, + id: this.id, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ObservationSolution { + storeId: string; + profileId: string; +} + +export interface ObservationListInstance { + _version: V1; + _solution: ObservationSolution; + _uri: string; + + (observationId: string, ): ObservationContext; + get(observationId: string, ): ObservationContext; + + + + + + + + + /** + * Create a ObservationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance + */ + create(params: CreateObservationsRequest, headers?: any, callback?: (error: Error | null, item?: ObservationInstance) => any): Promise<ObservationInstance>; + + /** + * Create a ObservationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ObservationInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateObservationsRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>>; + + + + + /** + * Streams ObservationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ObservationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ObservationInstance, done: (err?: Error) => void) => void): void; + each(params: ObservationListInstanceEachOptions, callback?: (item: ObservationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ObservationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ObservationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ObservationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ObservationListInstanceEachOptions, callback?: (item: ObservationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ObservationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ObservationPage) => any): Promise<ObservationPage>; + /** + * Retrieve a single target page of ObservationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ObservationPage>) => any): Promise<ApiResponse<ObservationPage>>; + /** + * Lists ObservationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ObservationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ObservationInstance[]) => any): Promise<ObservationInstance[]>; + list(params: ObservationListInstanceOptions, callback?: (error: Error | null, items: ObservationInstance[]) => any): Promise<ObservationInstance[]>; + /** + * Lists ObservationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ObservationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ObservationInstance[]>) => any): Promise<ApiResponse<ObservationInstance[]>>; + listWithHttpInfo(params: ObservationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ObservationInstance[]>) => any): Promise<ApiResponse<ObservationInstance[]>>; + /** + * Retrieve a single page of ObservationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ObservationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ObservationPage) => any): Promise<ObservationPage>; + page(params: ObservationListInstancePageOptions, callback?: (error: Error | null, items: ObservationPage) => any): Promise<ObservationPage>; + /** + * Retrieve a single page of ObservationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ObservationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ObservationPage>) => any): Promise<ApiResponse<ObservationPage>>; + pageWithHttpInfo(params: ObservationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ObservationPage>) => any): Promise<ApiResponse<ObservationPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ObservationListInstance(version: V1, storeId: string, profileId: string): ObservationListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(profileId)) { + throw new Error('Parameter \'profileId\' is not valid.'); + } + + const instance = ((observationId, ) => instance.get(observationId, )) as ObservationListInstance; + + instance.get = function get(observationId, ): ObservationContext { + return new ObservationContextImpl(version, storeId, profileId, observationId); + } + + instance._version = version; + instance._solution = { storeId, profileId, }; + instance._uri = `/Stores/${storeId}/Profiles/${profileId}/Observations`; + + instance.create = function create(params: CreateObservationsRequest, headers?: any, callback?: (error: Error | null, items: ObservationInstance) => any): Promise<ObservationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ObservationInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateObservationsRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<ObservationInstance>) => any): Promise<ApiResponse<ObservationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ObservationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ObservationInstance> => ({ + ...response, + body: new ObservationInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ObservationListInstancePageOptions | ((error: Error | null, items: ObservationPage) => any), callback?: (error: Error | null, items: ObservationPage) => any): Promise<ObservationPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + if (params["source"] !== undefined) + data["source"] = params["source"]; + if (params["createdAfter"] !== undefined) + data["createdAfter"] = serialize.iso8601DateTime(params["createdAfter"]); + if (params["createdBefore"] !== undefined) + data["createdBefore"] = serialize.iso8601DateTime(params["createdBefore"]); + if (params["conversationId"] !== undefined) + data["conversationId"] = params["conversationId"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["acceptEncoding"] !== undefined) headers["Accept-Encoding"] = params["acceptEncoding"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ObservationPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ObservationPage) => any): Promise<ObservationPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ObservationPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ObservationListInstancePageOptions | ((error: Error | null, items: ApiResponse<ObservationPage>) => any), callback?: (error: Error | null, items: ApiResponse<ObservationPage>) => any): Promise<ApiResponse<ObservationPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + if (params["source"] !== undefined) + data["source"] = params["source"]; + if (params["createdAfter"] !== undefined) + data["createdAfter"] = serialize.iso8601DateTime(params["createdAfter"]); + if (params["createdBefore"] !== undefined) + data["createdBefore"] = serialize.iso8601DateTime(params["createdBefore"]); + if (params["conversationId"] !== undefined) + data["conversationId"] = params["conversationId"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["acceptEncoding"] !== undefined) headers["Accept-Encoding"] = params["acceptEncoding"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ObservationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ObservationPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ObservationPage>) => any): Promise<ApiResponse<ObservationPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ObservationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ObservationPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ObservationPage extends TokenPage<V1, ObservationPayload, ObservationResource, ObservationInstance> { +/** +* Initialize the ObservationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, uri: string, params: any, solution: ObservationSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of ObservationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ObservationResource): ObservationInstance { + + return new ObservationInstance( + this._version, + payload, + this._solution.storeId, + this._solution.profileId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/memory/v1/operation.ts b/rest/memory/v1/operation.ts new file mode 100644 index 000000000..ad4dd826b --- /dev/null +++ b/rest/memory/v1/operation.ts @@ -0,0 +1,318 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class OperationResultResourceId { + "type": string; + /** + * The identifier of the created or affected resource. + */ + "id": string; + + constructor(payload) { + this.type = payload["type"]; + this.id = payload["id"]; + } +} + + +export class OperationStatusError { + /** + * A URI reference identifying the problem type. + */ + "type"?: string; + /** + * A short, human-readable summary of the problem type. + */ + "title"?: string; + /** + * The numeric Twilio error code. + */ + "code"?: number; + /** + * A human-readable explanation specific to this occurrence of the problem. + */ + "detail"?: string; + + constructor(payload) { + this.type = payload["type"]; + this.title = payload["title"]; + this.code = payload["code"]; + this.detail = payload["detail"]; + } +} + + + + +export interface OperationContext { + + /** + * Fetch a OperationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance + */ + fetch(callback?: (error: Error | null, item?: OperationInstance) => any): Promise<OperationInstance> + + /** + * Fetch a OperationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OperationInstance>) => any): Promise<ApiResponse<OperationInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OperationContextSolution { + "operationId": string; +} + +export class OperationContextImpl implements OperationContext { + protected _solution: OperationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, operationId: string) { + if (!isValidPathParam(operationId)) { + throw new Error('Parameter \'operationId\' is not valid.'); + } + + this._solution = { operationId, }; + this._uri = `/ControlPlane/Operations/${operationId}`; + } + + fetch(callback?: (error: Error | null, item?: OperationInstance) => any): Promise<OperationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OperationInstance(operationVersion, payload, instance._solution.operationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OperationInstance>) => any): Promise<ApiResponse<OperationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<OperationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<OperationInstance> => ({ + ...response, + body: new OperationInstance(operationVersion, response.body, instance._solution.operationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + + +interface OperationResource { + operationId: string; + status: string; + createdAt: Date; + statusUrl: string; + completedAt: Date; + result: OperationResultResourceId; + error: OperationStatusError; + resultUrl: string; +} + +export class OperationInstance { + protected _solution: OperationContextSolution; + protected _context?: OperationContext; + + constructor(protected _version: V1, _payload: OperationResource, operationId?: string) { + const payload = _payload; + this.operationId = (payload.operationId); + this.status = (payload.status); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.statusUrl = (payload.statusUrl); + this.completedAt = deserialize.iso8601DateTime(payload.completedAt); + this.result = payload.result !== null && payload.result !== undefined ? new OperationResultResourceId(payload.result) : null; + this.error = payload.error !== null && payload.error !== undefined ? new OperationStatusError(payload.error) : null; + this.resultUrl = (payload.resultUrl); + + this._solution = { operationId: operationId, }; + } + + /** + * The unique identifier for this operation. + */ + operationId: string; + /** + * The current status of the operation. + */ + status: string; + /** + * When the operation was created. + */ + createdAt: Date; + /** + * URI to check operation status. + */ + statusUrl: string; + /** + * When the operation completed or failed. + */ + completedAt: Date; + result: OperationResultResourceId; + error: OperationStatusError; + /** + * URL to fetch the resulting resource. + */ + resultUrl: string; + + private get _proxy(): OperationContext { + this._context = this._context || new OperationContextImpl(this._version, this._solution.operationId); + return this._context; + } + + /** + * Fetch a OperationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance + */ + fetch(callback?: (error: Error | null, item?: OperationInstance) => any): Promise<OperationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a OperationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OperationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OperationInstance>) => any): Promise<ApiResponse<OperationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + operationId: this.operationId, + status: this.status, + createdAt: this.createdAt, + statusUrl: this.statusUrl, + completedAt: this.completedAt, + result: this.result, + error: this.error, + resultUrl: this.resultUrl, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OperationSolution { +} + +export interface OperationListInstance { + _version: V1; + _solution: OperationSolution; + _uri: string; + + (operationId: string, ): OperationContext; + get(operationId: string, ): OperationContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OperationListInstance(version: V1): OperationListInstance { + const instance = ((operationId, ) => instance.get(operationId, )) as OperationListInstance; + + instance.get = function get(operationId, ): OperationContext { + return new OperationContextImpl(version, operationId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/memory/v1/profile.ts b/rest/memory/v1/profile.ts new file mode 100644 index 000000000..c13fc3bbc --- /dev/null +++ b/rest/memory/v1/profile.ts @@ -0,0 +1,1116 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class IdentityProfilesMeta { + /** + * The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + */ + "key"?: string; + "pageSize"?: number; + "nextToken"?: string; + "previousToken"?: string; + + constructor(payload) { + this.key = payload["key"]; + this.pageSize = payload["pageSize"]; + this.nextToken = payload["nextToken"]; + this.previousToken = payload["previousToken"]; + } +} + + +/** + * Data for creating or updating a profile, including traits. + */ +export class ProfileData { + /** + * Multiple trait groups. + */ + "traits"?: { [key: string]: { [key: string]: any; }; }; + + constructor(payload) { + this.traits = payload["traits"]; + } +} + + +export class ProfilePatch { + /** + * Multiple trait groups. + */ + "traits"?: { [key: string]: { [key: string]: any; }; }; + + constructor(payload) { + this.traits = payload["traits"]; + } +} + + + + +/** + * Options to pass to fetch a ProfileInstance + */ +export interface ProfileContextFetchOptions { + /** Comma separated list of trait group names to include. */ + "traitGroups"?: string; +} + +/** + * Options to pass to patch a ProfileInstance + */ +export interface ProfileContextPatchOptions { + /** */ + "profilePatch": ProfilePatch; +} + +/** + * Options to pass to create a ProfileInstance + */ +export interface ProfileListInstanceCreateOptions { + /** */ + "profileData": ProfileData; +} + +/** + * Options to pass to each + */ +export interface ProfileListInstanceEachOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ProfileInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ProfileListInstanceOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ProfileListInstancePageOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; +} + + +export interface ProfileContext { + + /** + * Remove a ProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance + */ + remove(callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance> + + /** + * Remove a ProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>> + + /** + * Fetch a ProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance + */ + fetch(callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance>; + /** + * Fetch a ProfileInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance + */ + fetch(params: ProfileContextFetchOptions, callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance>; + + /** + * Fetch a ProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>>; + /** + * Fetch a ProfileInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance with HTTP metadata + */ + fetchWithHttpInfo(params: ProfileContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>>; + + /** + * Patch a ProfileInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance + */ + patch(params: ProfilePatch, headers?: any, callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance>; + + /** + * Patch a ProfileInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance with HTTP metadata + */ + patchWithHttpInfo(params: ProfilePatch, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ProfileContextSolution { + "storeId": string; + "profileId": string; +} + +export class ProfileContextImpl implements ProfileContext { + protected _solution: ProfileContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, storeId: string, profileId: string) { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(profileId)) { + throw new Error('Parameter \'profileId\' is not valid.'); + } + + this._solution = { storeId, profileId, }; + this._uri = `/Stores/${storeId}/Profiles/${profileId}`; + } + + remove(callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "delete", headers}); + + operationPromise = operationPromise.then(payload => new ProfileInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // DELETE operation that returns a response model + let operationPromise = operationVersion.fetchWithResponseInfo<ProfileResource>({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<ProfileInstance> => ({ + ...response, + body: new ProfileInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(params?: ProfileContextFetchOptions | ((error: Error | null, item?: ProfileInstance) => any),callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["traitGroups"] !== undefined) + data["traitGroups"] = params["traitGroups"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new ProfileInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: ProfileContextFetchOptions | ((error: Error | null, item?: ApiResponse<ProfileInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["traitGroups"] !== undefined) + data["traitGroups"] = params["traitGroups"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ProfileResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ProfileInstance> => ({ + ...response, + body: new ProfileInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patch(params: ProfilePatch, headers?: any,callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.patch({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new ProfileInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patchWithHttpInfo(params: ProfilePatch, headers?: any,callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.patchWithResponseInfo<ProfileResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<ProfileInstance> => ({ + ...response, + body: new ProfileInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for IdentityProfilesMeta + */ +export interface IdentityProfilesMeta { + key?: string; + pageSize?: number; + nextToken?: string; + previousToken?: string; +} + +/** + * Nested model for ProfileData + */ +export interface ProfileData { + traits?: { [key: string]: { [key: string]: any; }; }; +} + +/** + * Nested model for ProfilePatch + */ +export interface ProfilePatch { + traits?: { [key: string]: { [key: string]: any; }; }; +} + + + + interface ProfilePayload extends TokenPaginationPayload { + profiles: string[]; +} + +/** + * Response model for CreateProfile202Response operations + */ +interface CreateProfile202Response_ResponseResource { + id: string; + message: string; +} + +/** + * Response model for DeleteProfile202Response operations + */ +interface DeleteProfile202Response_ResponseResource { + message: string; +} + +/** + * Response model for PatchProfileTraits202Response operations + */ +interface PatchProfileTraits202Response_ResponseResource { + message: string; +} + +/** + * Response model for ListProfiles200Response operations + */ +interface ListProfiles200Response_ResponseResource { + profiles?: Array<string>; + meta?: IdentityProfilesMeta; +} + +/** + * Response model for Profile operations + */ +interface Profile_ResponseResource { + id?: string; + createdAt?: Date; + traits?: { [key: string]: { [key: string]: any; }; }; +} + +/** + * Union type for all possible response models + */ +type ProfileResource = CreateProfile202Response_ResponseResource | DeleteProfile202Response_ResponseResource | PatchProfileTraits202Response_ResponseResource | ListProfiles200Response_ResponseResource | Profile_ResponseResource; + +export class ProfileInstance { + protected _solution: ProfileContextSolution; + protected _context?: ProfileContext; + + constructor(protected _version: V1, _payload: ProfileResource, storeId: string, profileId?: string) { + const payload: any = _payload; + this.id = (payload.id); + this.message = (payload.message); + this.profiles = (payload.profiles); + this.meta = payload.meta !== null && payload.meta !== undefined ? new IdentityProfilesMeta(payload.meta) : null; + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.traits = (payload.traits); + + this._solution = { storeId, profileId: profileId, }; + } + + /** + * The canonical profile ID. + */ + id?: string; + message?: string; + profiles?: Array<string>; + meta?: IdentityProfilesMeta; + /** + * The time the profile was created. + */ + createdAt?: Date; + /** + * Multiple trait groups. + */ + traits?: { [key: string]: { [key: string]: any; }; }; + + private get _proxy(): ProfileContext { + this._context = this._context || new ProfileContextImpl(this._version, this._solution.storeId, this._solution.profileId); + return this._context; + } + + /** + * Remove a ProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance + */ + remove(callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance + */ + fetch(callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance>; + /** + * Fetch a ProfileInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance + */ + fetch(params: ProfileContextFetchOptions, callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a ProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>>; + /** + * Fetch a ProfileInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance with HTTP metadata + */ + fetchWithHttpInfo(params: ProfileContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Patch a ProfileInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance + */ + patch(params: ProfilePatch, headers?: any, callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance>; + + patch(params?: any, callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance> + { + return this._proxy.patch(params, callback); + } + + /** + * Patch a ProfileInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance with HTTP metadata + */ + patchWithHttpInfo(params: ProfilePatch, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>>; + + patchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>> + { + return this._proxy.patchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + message: this.message, + profiles: this.profiles, + meta: this.meta, + createdAt: this.createdAt, + traits: this.traits, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ProfileSolution { + storeId: string; +} + +export interface ProfileListInstance { + _version: V1; + _solution: ProfileSolution; + _uri: string; + + (profileId: string, ): ProfileContext; + get(profileId: string, ): ProfileContext; + + + + + + + + + /** + * Create a ProfileInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance + */ + create(params: ProfileData, headers?: any, callback?: (error: Error | null, item?: ProfileInstance) => any): Promise<ProfileInstance>; + + /** + * Create a ProfileInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ProfileInstance with HTTP metadata + */ + createWithHttpInfo(params: ProfileData, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>>; + + + + + /** + * Streams ProfileInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ProfileListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: string, done: (err?: Error) => void) => void): void; + each(params: ProfileListInstanceEachOptions, callback?: (item: string, done: (err?: Error) => void) => void): void; + /** + * Streams ProfileInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ProfileListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: string, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ProfileListInstanceEachOptions, callback?: (item: string, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ProfileInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ProfilePage) => any): Promise<ProfilePage>; + /** + * Retrieve a single target page of ProfileInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ProfilePage>) => any): Promise<ApiResponse<ProfilePage>>; + /** + * Lists ProfileInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ProfileListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: string[]) => any): Promise<string[]>; + list(params: ProfileListInstanceOptions, callback?: (error: Error | null, items: string[]) => any): Promise<string[]>; + /** + * Lists ProfileInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ProfileListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<string[]>) => any): Promise<ApiResponse<string[]>>; + listWithHttpInfo(params: ProfileListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<string[]>) => any): Promise<ApiResponse<string[]>>; + /** + * Retrieve a single page of ProfileInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ProfileListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ProfilePage) => any): Promise<ProfilePage>; + page(params: ProfileListInstancePageOptions, callback?: (error: Error | null, items: ProfilePage) => any): Promise<ProfilePage>; + /** + * Retrieve a single page of ProfileInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ProfileListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ProfilePage>) => any): Promise<ApiResponse<ProfilePage>>; + pageWithHttpInfo(params: ProfileListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ProfilePage>) => any): Promise<ApiResponse<ProfilePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ProfileListInstance(version: V1, storeId: string): ProfileListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + const instance = ((profileId, ) => instance.get(profileId, )) as ProfileListInstance; + + instance.get = function get(profileId, ): ProfileContext { + return new ProfileContextImpl(version, storeId, profileId); + } + + instance._version = version; + instance._solution = { storeId, }; + instance._uri = `/Stores/${storeId}/Profiles`; + + instance.create = function create(params: ProfileData, headers?: any, callback?: (error: Error | null, items: ProfileInstance) => any): Promise<ProfileInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ProfileInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ProfileData, headers?: any, callback?: (error: Error | null, items: ApiResponse<ProfileInstance>) => any): Promise<ApiResponse<ProfileInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ProfileResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ProfileInstance> => ({ + ...response, + body: new ProfileInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ProfileListInstancePageOptions | ((error: Error | null, items: ProfilePage) => any), callback?: (error: Error | null, items: ProfilePage) => any): Promise<ProfilePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ProfilePage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + instance.list = function list(params?: any, callback?: (error: Error | null, items: string[]) => any): Promise<string[]> { + if (params instanceof Function) { + callback = params; + params = {}; + } + params = params || {}; + + let allRecords: string[] = []; + + function fetchNextPage(nextPageParams: any): Promise<string[]> { + return instance.page(nextPageParams).then((page: any) => { + const payload = page['_payload']; + const records = payload && payload['profiles'] ? payload['profiles'] : []; + allRecords = allRecords.concat(records); + + if (params.limit && allRecords.length >= params.limit) { + allRecords = allRecords.slice(0, params.limit); + return allRecords; + } + + const nextToken = page.nextPageUrl ? new URL(page.nextPageUrl).searchParams.get('PageToken') : null; + if (nextToken) { + return fetchNextPage({ ...nextPageParams, pageToken: nextToken }); + } + return allRecords; + }); + } + + const promise = fetchNextPage(params); + return instance._version.setPromiseCallback(promise, callback); + }; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ProfilePage) => any): Promise<ProfilePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ProfilePage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ProfileListInstancePageOptions | ((error: Error | null, items: ApiResponse<ProfilePage>) => any), callback?: (error: Error | null, items: ApiResponse<ProfilePage>) => any): Promise<ApiResponse<ProfilePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ProfilePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ProfilePage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.listWithHttpInfo = function listWithHttpInfo(params?: any, callback?: (error: Error | null, items: ApiResponse<string[]>) => any): Promise<ApiResponse<string[]>> { + if (params instanceof Function) { + callback = params; + params = {}; + } + params = params || {}; + + let allRecords: string[] = []; + let lastResponse: any; + + function fetchNextPage(nextPageParams: any): Promise<ApiResponse<string[]>> { + return instance.pageWithHttpInfo(nextPageParams).then((response: ApiResponse<any>) => { + lastResponse = response; + const page = response.body; + // For primitive arrays, directly access the records array from the payload + // Access _payload using bracket notation to bypass TypeScript protected access + const payload = page['_payload']; + const records = payload && payload['profiles'] ? payload['profiles'] : []; + allRecords = allRecords.concat(records); + + if (params.limit && allRecords.length >= params.limit) { + allRecords = allRecords.slice(0, params.limit); + return { + statusCode: lastResponse.statusCode, + headers: lastResponse.headers, + body: allRecords + }; + } + + const nextToken = page.nextPageUrl ? new URL(page.nextPageUrl).searchParams.get('PageToken') : null; + if (nextToken) { + return fetchNextPage({ ...nextPageParams, pageToken: nextToken }); + } + return { + statusCode: lastResponse.statusCode, + headers: lastResponse.headers, + body: allRecords + }; + }); + } + + const promise = fetchNextPage(params); + return instance._version.setPromiseCallback(promise, callback); + }; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ProfilePage>) => any): Promise<ApiResponse<ProfilePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ProfilePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ProfilePage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ProfilePage extends TokenPage<V1, ProfilePayload, ProfileResource, string> { +/** +* Initialize the ProfilePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, uri: string, params: any, solution: ProfileSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of ProfileInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ProfileResource): string { + // Array items are primitives (strings, numbers), return directly + return payload as any; + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/memory/v1/recall.ts b/rest/memory/v1/recall.ts new file mode 100644 index 000000000..d9e6783d6 --- /dev/null +++ b/rest/memory/v1/recall.ts @@ -0,0 +1,527 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * A single communication within a conversation across channels including SMS, Voice, Email, etc. Contains fields that are relevant to an agent to maintain session memory. + */ +export class Communication { + /** + * Unique communication identifier. + */ + "id": string; + /** + * Channel-specific ID (optional). + */ + "channelId"?: string; + "content": CommunicationContent; + /** + * When communication was created. + */ + "createdAt"?: Date; + /** + * When communication was last updated. + */ + "updatedAt"?: Date; + "author": Participant; + /** + * Communication recipients + */ + "recipients": Array<CommunicationRecipients>; + + constructor(payload) { + this.id = payload["id"]; + this.channelId = payload["channelId"]; + this.content = payload["content"]; + this.createdAt = payload["createdAt"]; + this.updatedAt = payload["updatedAt"]; + this.author = payload["author"]; + this.recipients = payload["recipients"]; + } +} + + +/** + * Content of a communication. + */ +export class CommunicationContent { + /** + * Primary text content (optional). + */ + "text"?: string; + + constructor(payload) { + this.text = payload["text"]; + } +} + + +export class CommunicationRecipients { + /** + * Participant identifier. + */ + "id": string; + /** + * Participant display name + */ + "name": string; + "type"?: ParticipantType; + /** + * The canonical profile ID. + */ + "profileId"?: string; + /** + * Address of the Participant (e.g., phone number, email address) + */ + "address": string; + /** + * The channel on which the message originated + */ + "channel": string; + /** + * Delivery status of the Communication to this recipient + */ + "deliveryStatus"?: string; + + constructor(payload) { + this.id = payload["id"]; + this.name = payload["name"]; + this.type = payload["type"]; + this.profileId = payload["profileId"]; + this.address = payload["address"]; + this.channel = payload["channel"]; + this.deliveryStatus = payload["deliveryStatus"]; + } +} + + +/** + * Request payload for retrieving profile memories with advanced filtering and semantic search. + */ +export class MemoryRetrievalRequest { + /** + * A unique identifier for the conversation using Twilio Type ID (TTID) format. + */ + "conversationId"?: string; + /** + * Hybrid search query for finding relevant memories. Omit to use query expansion to generate query from previous 10 communications in conversation. + */ + "query"?: string; + /** + * Start date for filtering memories (inclusive). + */ + "beginDate"?: Date; + /** + * End date for filtering memories (exclusive). + */ + "endDate"?: Date; + /** + * Maximum number of conversational session memories to return. If omitted or set to 0, no session memories will be fetched. + */ + "communicationsLimit"?: number; + /** + * Maximum number of observation memories to return. If omitted, defaults to 20. If set to 0, no observation memories will be fetched. + */ + "observationsLimit"?: number; + /** + * Maximum number of summary memories to return. If omitted, defaults to 5. If set to 0, no summary memories will be fetched. + */ + "summariesLimit"?: number; + /** + * Minimum relevance score threshold for observations and summaries to be returned. Only memories with a relevance score greater than or equal to this threshold will be included in the response. This threshold only applies when results are ranked by relevance. When results are returned in most-recent order, this field has no effect. + */ + "relevanceThreshold"?: number; + + constructor(payload) { + this.conversationId = payload["conversationId"]; + this.query = payload["query"]; + this.beginDate = payload["beginDate"]; + this.endDate = payload["endDate"]; + this.communicationsLimit = payload["communicationsLimit"]; + this.observationsLimit = payload["observationsLimit"]; + this.summariesLimit = payload["summariesLimit"]; + this.relevanceThreshold = payload["relevanceThreshold"]; + } +} + + +/** + * Metadata about the retrieval operation. + */ +export class MemoryRetrievalResponseMeta { + /** + * Query execution time in milliseconds. + */ + "queryTime": number; + + constructor(payload) { + this.queryTime = payload["queryTime"]; + } +} + + +export class Participant { + /** + * Participant identifier. + */ + "id": string; + /** + * Participant display name + */ + "name": string; + "type"?: ParticipantType; + /** + * The canonical profile ID. + */ + "profileId"?: string; + /** + * Address of the Participant (e.g., phone number, email address) + */ + "address": string; + /** + * The channel on which the message originated + */ + "channel": string; + + constructor(payload) { + this.id = payload["id"]; + this.name = payload["name"]; + this.type = payload["type"]; + this.profileId = payload["profileId"]; + this.address = payload["address"]; + this.channel = payload["channel"]; + } +} + + +/** + * Type of Participant in the Conversation + */ +export type ParticipantType = 'HUMAN_AGENT'|'CUSTOMER'|'AI_AGENT'|'AGENT'|'UNKNOWN'; + +/** + * A transient and mutable observation memory associated with a profile. + */ +export class RecallObservationInfo { + /** + * The main content of the observation. + */ + "content": string; + /** + * The timestamp when the observation originally occurred. + */ + "occurredAt": Date; + /** + * The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + */ + "source": string; + /** + * Array of conversation IDs associated with this observation. + */ + "conversationIds"?: Array<string>; + /** + * A unique identifier for the observation using Twilio Type ID (TTID) format. + */ + "id": string; + /** + * The timestamp when the observation was created. + */ + "createdAt": Date; + /** + * The timestamp when the observation was last updated. + */ + "updatedAt": Date; + /** + * The relevance score of the observation in relation to the query. Higher values indicate greater relevance. This field is omitted when results are returned in most-recent order. This may occur when no query is provided and one cannot be inferred from the conversation context, or when the system defaults to chronological retrieval to ensure high availability. + */ + "score"?: number; + + constructor(payload) { + this.content = payload["content"]; + this.occurredAt = payload["occurredAt"]; + this.source = payload["source"]; + this.conversationIds = payload["conversationIds"]; + this.id = payload["id"]; + this.createdAt = payload["createdAt"]; + this.updatedAt = payload["updatedAt"]; + this.score = payload["score"]; + } +} + + +/** + * A summary memory derived from conversations. + */ +export class RecallSummaryInfo { + /** + * The source system that generated the summary. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + */ + "source"?: string; + /** + * The main content of the summary. + */ + "content": string; + /** + * The timestamp when the summary was originally created. + */ + "occurredAt": Date; + /** + * A unique identifier for the conversation using Twilio Type ID (TTID) format. + */ + "conversationId": string; + /** + * A unique identifier for the summary using Twilio Type ID (TTID) format. + */ + "id": string; + /** + * The timestamp when the summary was created. + */ + "createdAt": Date; + /** + * The timestamp when the summary was last updated. + */ + "updatedAt": Date; + /** + * The relevance score of the summary in relation to the query. Higher values indicate greater relevance. This field is omitted when results are returned in most-recent order. This may occur when no query is provided and one cannot be inferred from the conversation context, or when the system defaults to chronological retrieval to ensure high availability. + */ + "score"?: number; + + constructor(payload) { + this.source = payload["source"]; + this.content = payload["content"]; + this.occurredAt = payload["occurredAt"]; + this.conversationId = payload["conversationId"]; + this.id = payload["id"]; + this.createdAt = payload["createdAt"]; + this.updatedAt = payload["updatedAt"]; + this.score = payload["score"]; + } +} + + + +/** + * Options to pass to create a RecallInstance + */ +export interface RecallListInstanceCreateOptions { + /** */ + "memoryRetrievalRequest": MemoryRetrievalRequest; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; + /** Compression algorithm used for the request body (e.g., gzip, deflate, br) */ + "contentEncoding"?: 'gzip' | 'deflate' | 'br' | 'compress'; +} + + +export interface RecallSolution { + storeId: string; + profileId: string; +} + +export interface RecallListInstance { + _version: V1; + _solution: RecallSolution; + _uri: string; + + + + /** + * Create a RecallInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecallInstance + */ + create(params: MemoryRetrievalRequest, headers?: any, callback?: (error: Error | null, item?: RecallInstance) => any): Promise<RecallInstance>; + + /** + * Create a RecallInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecallInstance with HTTP metadata + */ + createWithHttpInfo(params: MemoryRetrievalRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<RecallInstance>) => any): Promise<ApiResponse<RecallInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RecallListInstance(version: V1, storeId: string, profileId: string): RecallListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(profileId)) { + throw new Error('Parameter \'profileId\' is not valid.'); + } + + const instance = {} as RecallListInstance; + + instance._version = version; + instance._solution = { storeId, profileId, }; + instance._uri = `/Stores/${storeId}/Profiles/${profileId}/Recall`; + + instance.create = function create(params: MemoryRetrievalRequest, headers?: any, callback?: (error: Error | null, items: RecallInstance) => any): Promise<RecallInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RecallInstance(operationVersion, payload, instance._solution.storeId, instance._solution.profileId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MemoryRetrievalRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<RecallInstance>) => any): Promise<ApiResponse<RecallInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<RecallResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RecallInstance> => ({ + ...response, + body: new RecallInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.profileId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + + +interface RecallResource { + observations: Array<RecallObservationInfo>; + summaries: Array<RecallSummaryInfo>; + communications: Array<Communication>; + meta: MemoryRetrievalResponseMeta; +} + +/** + * Response containing retrieved profile memories organized by type. + */ +export class RecallInstance { + + constructor(protected _version: V1, _payload: RecallResource, storeId: string, profileId: string) { + const payload = _payload; + this.observations = payload.observations !== null && payload.observations !== undefined ? payload.observations.map( + (payload: any) => new RecallObservationInfo(payload) + ) : null; + this.summaries = payload.summaries !== null && payload.summaries !== undefined ? payload.summaries.map( + (payload: any) => new RecallSummaryInfo(payload) + ) : null; + this.communications = payload.communications !== null && payload.communications !== undefined ? payload.communications.map( + (payload: any) => new Communication(payload) + ) : null; + this.meta = payload.meta !== null && payload.meta !== undefined ? new MemoryRetrievalResponseMeta(payload.meta) : null; + + } + + /** + * Array of observation memories. + */ + observations: Array<RecallObservationInfo>; + /** + * Array of summary memories derived from observations at the end of conversations. + */ + summaries: Array<RecallSummaryInfo>; + /** + * Array of recent communication context. + */ + communications: Array<Communication>; + meta: MemoryRetrievalResponseMeta; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + observations: this.observations, + summaries: this.summaries, + communications: this.communications, + meta: this.meta, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/memory/v1/revision.ts b/rest/memory/v1/revision.ts new file mode 100644 index 000000000..c781a9be6 --- /dev/null +++ b/rest/memory/v1/revision.ts @@ -0,0 +1,452 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface RevisionListInstanceEachOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RevisionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RevisionListInstanceOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RevisionListInstancePageOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Compression algorithms supported by the client (e.g., gzip, deflate, br) */ + "acceptEncoding"?: string; +} + + + +export interface RevisionSolution { + storeId: string; + profileId: string; + observationId: string; +} + +export interface RevisionListInstance { + _version: V1; + _solution: RevisionSolution; + _uri: string; + + + + + /** + * Streams RevisionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RevisionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RevisionInstance, done: (err?: Error) => void) => void): void; + each(params: RevisionListInstanceEachOptions, callback?: (item: RevisionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RevisionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RevisionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RevisionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RevisionListInstanceEachOptions, callback?: (item: RevisionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RevisionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RevisionPage) => any): Promise<RevisionPage>; + /** + * Retrieve a single target page of RevisionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RevisionPage>) => any): Promise<ApiResponse<RevisionPage>>; + /** + * Lists RevisionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RevisionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RevisionInstance[]) => any): Promise<RevisionInstance[]>; + list(params: RevisionListInstanceOptions, callback?: (error: Error | null, items: RevisionInstance[]) => any): Promise<RevisionInstance[]>; + /** + * Lists RevisionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RevisionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RevisionInstance[]>) => any): Promise<ApiResponse<RevisionInstance[]>>; + listWithHttpInfo(params: RevisionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RevisionInstance[]>) => any): Promise<ApiResponse<RevisionInstance[]>>; + /** + * Retrieve a single page of RevisionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RevisionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RevisionPage) => any): Promise<RevisionPage>; + page(params: RevisionListInstancePageOptions, callback?: (error: Error | null, items: RevisionPage) => any): Promise<RevisionPage>; + /** + * Retrieve a single page of RevisionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RevisionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RevisionPage>) => any): Promise<ApiResponse<RevisionPage>>; + pageWithHttpInfo(params: RevisionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RevisionPage>) => any): Promise<ApiResponse<RevisionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RevisionListInstance(version: V1, storeId: string, profileId: string, observationId: string): RevisionListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(profileId)) { + throw new Error('Parameter \'profileId\' is not valid.'); + } + + if (!isValidPathParam(observationId)) { + throw new Error('Parameter \'observationId\' is not valid.'); + } + + const instance = {} as RevisionListInstance; + + instance._version = version; + instance._solution = { storeId, profileId, observationId, }; + instance._uri = `/Stores/${storeId}/Profiles/${profileId}/Observations/${observationId}/Revisions`; + + instance.page = function page(params?: RevisionListInstancePageOptions | ((error: Error | null, items: RevisionPage) => any), callback?: (error: Error | null, items: RevisionPage) => any): Promise<RevisionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["acceptEncoding"] !== undefined) headers["Accept-Encoding"] = params["acceptEncoding"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RevisionPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RevisionPage) => any): Promise<RevisionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RevisionPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RevisionListInstancePageOptions | ((error: Error | null, items: ApiResponse<RevisionPage>) => any), callback?: (error: Error | null, items: ApiResponse<RevisionPage>) => any): Promise<ApiResponse<RevisionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["acceptEncoding"] !== undefined) headers["Accept-Encoding"] = params["acceptEncoding"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RevisionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RevisionPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RevisionPage>) => any): Promise<ApiResponse<RevisionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RevisionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RevisionPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface RevisionPayload extends TokenPaginationPayload { + revisions: RevisionResource[]; +} + +interface RevisionResource { + content: string; + occurredAt: Date; + source: string; + conversationIds: Array<string>; + id: string; + createdAt: Date; + updatedAt: Date; +} + +/** + * A transient and mutable observation memory associated with a profile. + */ +export class RevisionInstance { + + constructor(protected _version: V1, _payload: RevisionResource, storeId: string, profileId: string, observationId: string) { + const payload = _payload; + this.content = (payload.content); + this.occurredAt = deserialize.iso8601DateTime(payload.occurredAt); + this.source = (payload.source); + this.conversationIds = (payload.conversationIds); + this.id = (payload.id); + this.createdAt = deserialize.iso8601DateTime(payload.createdAt); + this.updatedAt = deserialize.iso8601DateTime(payload.updatedAt); + + } + + /** + * The main content of the observation. + */ + content: string; + /** + * The timestamp when the observation originally occurred. + */ + occurredAt: Date; + /** + * The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + */ + source: string; + /** + * Array of conversation IDs associated with this observation. + */ + conversationIds: Array<string>; + /** + * A unique identifier for the observation using Twilio Type ID (TTID) format. + */ + id: string; + /** + * The timestamp when the observation was created. + */ + createdAt: Date; + /** + * The timestamp when the observation was last updated. + */ + updatedAt: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + content: this.content, + occurredAt: this.occurredAt, + source: this.source, + conversationIds: this.conversationIds, + id: this.id, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class RevisionPage extends TokenPage<V1, RevisionPayload, RevisionResource, RevisionInstance> { +/** +* Initialize the RevisionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, uri: string, params: any, solution: RevisionSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of RevisionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RevisionResource): RevisionInstance { + + return new RevisionInstance( + this._version, + payload, + this._solution.storeId, + this._solution.profileId, + this._solution.observationId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/memory/v1/store.ts b/rest/memory/v1/store.ts new file mode 100644 index 000000000..04aab0fda --- /dev/null +++ b/rest/memory/v1/store.ts @@ -0,0 +1,1113 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class Meta { + /** + * The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + */ + "key"?: string; + /** + * The number of items returned in this page of results. + */ + "pageSize"?: number; + "nextToken"?: string; + "previousToken"?: string; + + constructor(payload) { + this.key = payload["key"]; + this.pageSize = payload["pageSize"]; + this.nextToken = payload["nextToken"]; + this.previousToken = payload["previousToken"]; + } +} + + +export class PatchStoreRequest { + /** + * Provides a unique and addressable name to be assigned to this Store. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + */ + "displayName"?: string; + /** + * A human readable description of this resource, up to 128 characters. + */ + "description"?: string; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + } +} + + +export class ServiceRequest { + /** + * Provides a unique and addressable name to be assigned to this Store. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + */ + "displayName": string; + /** + * A human readable description of this resource, up to 128 characters. + */ + "description"?: string; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + } +} + + + + + +/** + * Options to pass to patch a StoreInstance + */ +export interface StoreContextPatchOptions { + /** Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource\'s current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. */ + "ifMatch"?: string; + /** */ + "patchStoreRequest"?: PatchStoreRequest; +} + +/** + * Options to pass to create a StoreInstance + */ +export interface StoreListInstanceCreateOptions { + /** */ + "serviceRequest": ServiceRequest; +} + +/** + * Options to pass to each + */ +export interface StoreListInstanceEachOptions { + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: StoreInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface StoreListInstanceOptions { + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface StoreListInstancePageOptions { + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; +} + + +export interface StoreContext { + + /** + * Remove a StoreInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance + */ + remove(callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance> + + /** + * Remove a StoreInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>> + + /** + * Fetch a StoreInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance + */ + fetch(callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance> + + /** + * Fetch a StoreInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>> + + /** + * Patch a StoreInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance + */ + patch(callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance>; + /** + * Patch a StoreInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance + */ + patch(params: PatchStoreRequest, headers?: any, callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance>; + + /** + * Patch a StoreInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance with HTTP metadata + */ + patchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>>; + /** + * Patch a StoreInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance with HTTP metadata + */ + patchWithHttpInfo(params: PatchStoreRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface StoreContextSolution { + "storeId": string; +} + +export class StoreContextImpl implements StoreContext { + protected _solution: StoreContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, storeId: string) { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + this._solution = { storeId, }; + this._uri = `/ControlPlane/Stores/${storeId}`; + } + + remove(callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "delete", headers}); + + operationPromise = operationPromise.then(payload => new StoreInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // DELETE operation that returns a response model + let operationPromise = operationVersion.fetchWithResponseInfo<StoreResource>({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<StoreInstance> => ({ + ...response, + body: new StoreInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new StoreInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<StoreResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<StoreInstance> => ({ + ...response, + body: new StoreInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patch(params?: PatchStoreRequest | ((error: Error | null, item?: StoreInstance) => any), headers?: any,callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<PatchStoreRequest> as PatchStoreRequest; + } else { + params = params || {} as Partial<PatchStoreRequest> as PatchStoreRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.patch({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new StoreInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patchWithHttpInfo(params?: PatchStoreRequest | ((error: Error | null, item?: ApiResponse<StoreInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<PatchStoreRequest> as PatchStoreRequest; + } else { + params = params || {} as Partial<PatchStoreRequest> as PatchStoreRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.patchWithResponseInfo<StoreResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<StoreInstance> => ({ + ...response, + body: new StoreInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for Meta + */ +export interface Meta { + key?: string; + pageSize?: number; + nextToken?: string; + previousToken?: string; +} + +/** + * Nested model for PatchStoreRequest + */ +export interface PatchStoreRequest { + displayName?: string; + description?: string; +} + +/** + * Nested model for ServiceRequest + */ +export interface ServiceRequest { + displayName: string; + description?: string; +} + + + + interface StorePayload extends TokenPaginationPayload { + stores: string[]; +} + +/** + * Response model for PatchStore202Response operations + */ +interface PatchStore202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Response model for CreateStore202Response operations + */ +interface CreateStore202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Response model for ServiceList operations + */ +interface ServiceList_ResponseResource { + stores?: Array<string>; + meta?: Meta; +} + +/** + * Response model for DeleteStore202Response operations + */ +interface DeleteStore202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Response model for Store operations + */ +interface Store_ResponseResource { + displayName: string; + description?: string; + id: string; + status: string; + intelligenceServiceId: string; + version: number; +} + +/** + * Union type for all possible response models + */ +type StoreResource = PatchStore202Response_ResponseResource | CreateStore202Response_ResponseResource | ServiceList_ResponseResource | DeleteStore202Response_ResponseResource | Store_ResponseResource; + +export class StoreInstance { + protected _solution: StoreContextSolution; + protected _context?: StoreContext; + + constructor(protected _version: V1, _payload: StoreResource, storeId?: string) { + const payload: any = _payload; + this.message = (payload.message); + this.statusUrl = (payload.statusUrl); + this.stores = (payload.stores); + this.meta = payload.meta !== null && payload.meta !== undefined ? new Meta(payload.meta) : null; + this.displayName = (payload.displayName); + this.description = (payload.description); + this.id = (payload.id); + this.status = (payload.status); + this.intelligenceServiceId = (payload.intelligenceServiceId); + this.version = deserialize.integer(payload.version); + + this._solution = { storeId: storeId, }; + } + + message?: string; + /** + * URI to check operation status. + */ + statusUrl?: string; + /** + * List of Memory Store IDs associated with the Twilio account. + */ + stores?: Array<string>; + meta?: Meta; + /** + * Provides a unique and addressable name to be assigned to this Store. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + */ + displayName?: string; + /** + * A human readable description of this resource, up to 128 characters. + */ + description?: string; + /** + * The unique identifier for the Memory Store + */ + id?: string; + /** + * The current status of the Memory Store. A store begins in the QUEUED state as it is scheduled for processing. It then moves to PROVISIONING at the beginning of processing. It transitions to ACTIVE once all dependent resources are provisioned, including Conversational Intelligence capabilities. If there is an issue provisioning resources, the store will move to the FAILED state. + */ + status?: string; + /** + * The ID of the associated intelligence service that was provisioned for memory extraction. + */ + intelligenceServiceId?: string; + /** + * The current version number of the Memory Store. Incremented on each successful update. + */ + version?: number; + + private get _proxy(): StoreContext { + this._context = this._context || new StoreContextImpl(this._version, this._solution.storeId); + return this._context; + } + + /** + * Remove a StoreInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance + */ + remove(callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a StoreInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a StoreInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance + */ + fetch(callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a StoreInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Patch a StoreInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance + */ + patch(callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance>; + /** + * Patch a StoreInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance + */ + patch(params: PatchStoreRequest, headers?: any, callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance>; + + patch(params?: any, callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance> + { + return this._proxy.patch(params, callback); + } + + /** + * Patch a StoreInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance with HTTP metadata + */ + patchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>>; + /** + * Patch a StoreInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance with HTTP metadata + */ + patchWithHttpInfo(params: PatchStoreRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>>; + + patchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>> + { + return this._proxy.patchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + statusUrl: this.statusUrl, + stores: this.stores, + meta: this.meta, + displayName: this.displayName, + description: this.description, + id: this.id, + status: this.status, + intelligenceServiceId: this.intelligenceServiceId, + version: this.version, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface StoreSolution { +} + +export interface StoreListInstance { + _version: V1; + _solution: StoreSolution; + _uri: string; + + (storeId: string, ): StoreContext; + get(storeId: string, ): StoreContext; + + + + + + + + + /** + * Create a StoreInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance + */ + create(params: ServiceRequest, headers?: any, callback?: (error: Error | null, item?: StoreInstance) => any): Promise<StoreInstance>; + + /** + * Create a StoreInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StoreInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>>; + + + + + /** + * Streams StoreInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StoreListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: string, done: (err?: Error) => void) => void): void; + each(params: StoreListInstanceEachOptions, callback?: (item: string, done: (err?: Error) => void) => void): void; + /** + * Streams StoreInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StoreListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: string, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: StoreListInstanceEachOptions, callback?: (item: string, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of StoreInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: StorePage) => any): Promise<StorePage>; + /** + * Retrieve a single target page of StoreInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<StorePage>) => any): Promise<ApiResponse<StorePage>>; + /** + * Lists StoreInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StoreListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: string[]) => any): Promise<string[]>; + list(params: StoreListInstanceOptions, callback?: (error: Error | null, items: string[]) => any): Promise<string[]>; + /** + * Lists StoreInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StoreListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<string[]>) => any): Promise<ApiResponse<string[]>>; + listWithHttpInfo(params: StoreListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<string[]>) => any): Promise<ApiResponse<string[]>>; + /** + * Retrieve a single page of StoreInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StoreListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: StorePage) => any): Promise<StorePage>; + page(params: StoreListInstancePageOptions, callback?: (error: Error | null, items: StorePage) => any): Promise<StorePage>; + /** + * Retrieve a single page of StoreInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StoreListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<StorePage>) => any): Promise<ApiResponse<StorePage>>; + pageWithHttpInfo(params: StoreListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<StorePage>) => any): Promise<ApiResponse<StorePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function StoreListInstance(version: V1): StoreListInstance { + const instance = ((storeId, ) => instance.get(storeId, )) as StoreListInstance; + + instance.get = function get(storeId, ): StoreContext { + return new StoreContextImpl(version, storeId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ControlPlane/Stores`; + + instance.create = function create(params: ServiceRequest, headers?: any, callback?: (error: Error | null, items: StoreInstance) => any): Promise<StoreInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new StoreInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<StoreInstance>) => any): Promise<ApiResponse<StoreInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<StoreResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<StoreInstance> => ({ + ...response, + body: new StoreInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: StoreListInstancePageOptions | ((error: Error | null, items: StorePage) => any), callback?: (error: Error | null, items: StorePage) => any): Promise<StorePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new StorePage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + instance.list = function list(params?: any, callback?: (error: Error | null, items: string[]) => any): Promise<string[]> { + if (params instanceof Function) { + callback = params; + params = {}; + } + params = params || {}; + + let allRecords: string[] = []; + + function fetchNextPage(nextPageParams: any): Promise<string[]> { + return instance.page(nextPageParams).then((page: any) => { + const payload = page['_payload']; + const records = payload && payload['stores'] ? payload['stores'] : []; + allRecords = allRecords.concat(records); + + if (params.limit && allRecords.length >= params.limit) { + allRecords = allRecords.slice(0, params.limit); + return allRecords; + } + + const nextToken = page.nextPageUrl ? new URL(page.nextPageUrl).searchParams.get('PageToken') : null; + if (nextToken) { + return fetchNextPage({ ...nextPageParams, pageToken: nextToken }); + } + return allRecords; + }); + } + + const promise = fetchNextPage(params); + return instance._version.setPromiseCallback(promise, callback); + }; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: StorePage) => any): Promise<StorePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new StorePage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: StoreListInstancePageOptions | ((error: Error | null, items: ApiResponse<StorePage>) => any), callback?: (error: Error | null, items: ApiResponse<StorePage>) => any): Promise<ApiResponse<StorePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<StorePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new StorePage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.listWithHttpInfo = function listWithHttpInfo(params?: any, callback?: (error: Error | null, items: ApiResponse<string[]>) => any): Promise<ApiResponse<string[]>> { + if (params instanceof Function) { + callback = params; + params = {}; + } + params = params || {}; + + let allRecords: string[] = []; + let lastResponse: any; + + function fetchNextPage(nextPageParams: any): Promise<ApiResponse<string[]>> { + return instance.pageWithHttpInfo(nextPageParams).then((response: ApiResponse<any>) => { + lastResponse = response; + const page = response.body; + // For primitive arrays, directly access the records array from the payload + // Access _payload using bracket notation to bypass TypeScript protected access + const payload = page['_payload']; + const records = payload && payload['stores'] ? payload['stores'] : []; + allRecords = allRecords.concat(records); + + if (params.limit && allRecords.length >= params.limit) { + allRecords = allRecords.slice(0, params.limit); + return { + statusCode: lastResponse.statusCode, + headers: lastResponse.headers, + body: allRecords + }; + } + + const nextToken = page.nextPageUrl ? new URL(page.nextPageUrl).searchParams.get('PageToken') : null; + if (nextToken) { + return fetchNextPage({ ...nextPageParams, pageToken: nextToken }); + } + return { + statusCode: lastResponse.statusCode, + headers: lastResponse.headers, + body: allRecords + }; + }); + } + + const promise = fetchNextPage(params); + return instance._version.setPromiseCallback(promise, callback); + }; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<StorePage>) => any): Promise<ApiResponse<StorePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<StorePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new StorePage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class StorePage extends TokenPage<V1, StorePayload, StoreResource, string> { +/** +* Initialize the StorePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, uri: string, params: any, solution: StoreSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of StoreInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: StoreResource): string { + // Array items are primitives (strings, numbers), return directly + return payload as any; + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/memory/v1/trait.ts b/rest/memory/v1/trait.ts new file mode 100644 index 000000000..5d6d13fbd --- /dev/null +++ b/rest/memory/v1/trait.ts @@ -0,0 +1,437 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface TraitListInstanceEachOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Comma separated list of trait group names to include. */ + "traitGroups"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TraitInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TraitListInstanceOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Comma separated list of trait group names to include. */ + "traitGroups"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TraitListInstancePageOptions { + /** The maximum number of items to return per page, maximum of 1000. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Comma separated list of trait group names to include. */ + "traitGroups"?: string; +} + + + +export interface TraitSolution { + storeId: string; + profileId: string; +} + +export interface TraitListInstance { + _version: V1; + _solution: TraitSolution; + _uri: string; + + + + + /** + * Streams TraitInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TraitInstance, done: (err?: Error) => void) => void): void; + each(params: TraitListInstanceEachOptions, callback?: (item: TraitInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TraitInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TraitInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TraitListInstanceEachOptions, callback?: (item: TraitInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TraitInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TraitPage) => any): Promise<TraitPage>; + /** + * Retrieve a single target page of TraitInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TraitPage>) => any): Promise<ApiResponse<TraitPage>>; + /** + * Lists TraitInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TraitInstance[]) => any): Promise<TraitInstance[]>; + list(params: TraitListInstanceOptions, callback?: (error: Error | null, items: TraitInstance[]) => any): Promise<TraitInstance[]>; + /** + * Lists TraitInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TraitInstance[]>) => any): Promise<ApiResponse<TraitInstance[]>>; + listWithHttpInfo(params: TraitListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TraitInstance[]>) => any): Promise<ApiResponse<TraitInstance[]>>; + /** + * Retrieve a single page of TraitInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TraitPage) => any): Promise<TraitPage>; + page(params: TraitListInstancePageOptions, callback?: (error: Error | null, items: TraitPage) => any): Promise<TraitPage>; + /** + * Retrieve a single page of TraitInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TraitPage>) => any): Promise<ApiResponse<TraitPage>>; + pageWithHttpInfo(params: TraitListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TraitPage>) => any): Promise<ApiResponse<TraitPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TraitListInstance(version: V1, storeId: string, profileId: string): TraitListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(profileId)) { + throw new Error('Parameter \'profileId\' is not valid.'); + } + + const instance = {} as TraitListInstance; + + instance._version = version; + instance._solution = { storeId, profileId, }; + instance._uri = `/Stores/${storeId}/Profiles/${profileId}/Traits`; + + instance.page = function page(params?: TraitListInstancePageOptions | ((error: Error | null, items: TraitPage) => any), callback?: (error: Error | null, items: TraitPage) => any): Promise<TraitPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + if (params["traitGroups"] !== undefined) + data["traitGroups"] = params["traitGroups"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TraitPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TraitPage) => any): Promise<TraitPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TraitPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TraitListInstancePageOptions | ((error: Error | null, items: ApiResponse<TraitPage>) => any), callback?: (error: Error | null, items: ApiResponse<TraitPage>) => any): Promise<ApiResponse<TraitPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + if (params["traitGroups"] !== undefined) + data["traitGroups"] = params["traitGroups"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TraitPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TraitPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TraitPage>) => any): Promise<ApiResponse<TraitPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TraitPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TraitPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TraitPayload extends TokenPaginationPayload { + traits: TraitResource[]; +} + +interface TraitResource { + name: string; + value: any; + traitGroup: string; + timestamp: Date; +} + +/** + * Full metadata about a trait, beyond the name value pair. + */ +export class TraitInstance { + + constructor(protected _version: V1, _payload: TraitResource, storeId: string, profileId: string) { + const payload = _payload; + this.name = (payload.name); + this.value = (payload.value); + this.traitGroup = (payload.traitGroup); + this.timestamp = deserialize.iso8601DateTime(payload.timestamp); + + } + + /** + * The name of the trait. + */ + name: string; + /** + * The value of a trait. Can be a string, integer, boolean, or an array of these types (arrays cannot contain nested arrays). + */ + value: any; + /** + * The trait group name to which this trait belongs. + */ + traitGroup: string; + /** + * The time the trait was created or last updated. + */ + timestamp: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + name: this.name, + value: this.value, + traitGroup: this.traitGroup, + timestamp: this.timestamp, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class TraitPage extends TokenPage<V1, TraitPayload, TraitResource, TraitInstance> { +/** +* Initialize the TraitPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, uri: string, params: any, solution: TraitSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of TraitInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TraitResource): TraitInstance { + + return new TraitInstance( + this._version, + payload, + this._solution.storeId, + this._solution.profileId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/memory/v1/traitGroup.ts b/rest/memory/v1/traitGroup.ts new file mode 100644 index 000000000..68725ce9b --- /dev/null +++ b/rest/memory/v1/traitGroup.ts @@ -0,0 +1,1347 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio Memory API + * APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import TokenPage, { TokenPaginationPayload } from "../../../base/TokenPage"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class Meta { + /** + * The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + */ + "key"?: string; + /** + * The number of items returned in this page of results. + */ + "pageSize"?: number; + "nextToken"?: string; + "previousToken"?: string; + + constructor(payload) { + this.key = payload["key"]; + this.pageSize = payload["pageSize"]; + this.nextToken = payload["nextToken"]; + this.previousToken = payload["previousToken"]; + } +} + + +export class PatchTraitGroupRequest { + /** + * Updated description of the Trait Group + */ + "description"?: string; + /** + * Map of traits to add, update, or remove in this Trait Group, where the key is the trait name. - To update/add a trait: provide the complete TraitDefinition object - To remove a trait: set dataType to an empty string (\"\") + */ + "traits"?: { [key: string]: TraitDefinition; }; + + constructor(payload) { + this.description = payload["description"]; + this.traits = payload["traits"]; + } +} + + +/** + * A Trait is a single attribute or characteristic of a profile, such as age, location, or preferences. + */ +export class TraitDefinition { + /** + * Data type of the Trait, such as STRING, NUMBER, BOOLEAN, ARRAY. For DELETE operations in PATCH requests, set this to an empty string (\"\") to mark the trait for deletion. + */ + "dataType": string; + /** + * Description of the Trait, providing additional context or information. + */ + "description"?: string; + "validationRule"?: ValidationRule; + /** + * The name of the identifier type to promote the trait value to, such as \'\'email\'\', \'\'phone\'\', \'\'user_id\'\', etc. This allows the trait to be mapped to an identifier in Identity Resolution. The identifier type should be configured in the Identity Resolution Settings. + */ + "idTypePromotion"?: string; + + constructor(payload) { + this.dataType = payload["dataType"]; + this.description = payload["description"]; + this.validationRule = payload["validationRule"]; + this.idTypePromotion = payload["idTypePromotion"]; + } +} + + +export class TraitGroup { + /** + * Provides a unique and addressable name to be assigned to this Trait Group + */ + "displayName": string; + /** + * description of the Trait Group + */ + "description"?: string; + /** + * Map of traits that are part of this Trait Group, where the key is the trait name and the value is the trait\'s definition. + */ + "traits"?: { [key: string]: TraitGroupCoreTraitsValue; }; + /** + * The current version number of the Trait Group. Incremented on each successful update. + */ + "version": number; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + this.traits = payload["traits"]; + this.version = payload["version"]; + } +} + + +/** + * A Trait is a single attribute or characteristic of a profile, such as age, location, or preferences. + */ +export class TraitGroupCoreTraitsValue { + /** + * Data type of the Trait, such as STRING, NUMBER, BOOLEAN, ARRAY. For DELETE operations in PATCH requests, set this to an empty string (\"\") to mark the trait for deletion. + */ + "dataType": string; + /** + * Description of the Trait, providing additional context or information. + */ + "description"?: string; + "validationRule"?: ValidationRule; + /** + * The name of the identifier type to promote the trait value to, such as \'\'email\'\', \'\'phone\'\', \'\'user_id\'\', etc. This allows the trait to be mapped to an identifier in Identity Resolution. The identifier type should be configured in the Identity Resolution Settings. + */ + "idTypePromotion"?: string; + + constructor(payload) { + this.dataType = payload["dataType"]; + this.description = payload["description"]; + this.validationRule = payload["validationRule"]; + this.idTypePromotion = payload["idTypePromotion"]; + } +} + + +/** + * Payload schema for creating Trait Groups. + */ +export class TraitGroupRequest { + /** + * Unique name of the Trait Group + */ + "displayName": string; + /** + * description of the Trait Group + */ + "description"?: string; + /** + * Map of traits belonging to this Trait Group, keyed by trait name. + */ + "traits"?: { [key: string]: TraitGroupCoreTraitsValue; }; + + constructor(payload) { + this.displayName = payload["displayName"]; + this.description = payload["description"]; + this.traits = payload["traits"]; + } +} + + +export class ValidationRule { + /** + * Regex pattern (max 1000 chars) + */ + "pattern"?: string; + /** + * Minimum string length + */ + "minLength"?: number; + /** + * Maximum string length + */ + "maxLength"?: number; + /** + * Discriminator field indicating this is an array validation rule. + */ + "ruleType": string; + /** + * Minimum value + */ + "min"?: number; + /** + * Maximum value + */ + "max"?: number; + /** + * Minimum number of items + */ + "minItems"?: number; + /** + * Maximum number of items + */ + "maxItems"?: number; + + constructor(payload) { + this.pattern = payload["pattern"]; + this.minLength = payload["minLength"]; + this.maxLength = payload["maxLength"]; + this.ruleType = payload["ruleType"]; + this.min = payload["min"]; + this.max = payload["max"]; + this.minItems = payload["minItems"]; + this.maxItems = payload["maxItems"]; + } +} + + + + +/** + * Options to pass to fetch a TraitGroupInstance + */ +export interface TraitGroupContextFetchOptions { + /** Whether to include trait definitions in the response */ + "includeTraits"?: boolean; + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; +} + +/** + * Options to pass to patch a TraitGroupInstance + */ +export interface TraitGroupContextPatchOptions { + /** Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource\'s current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. */ + "ifMatch"?: string; + /** */ + "patchTraitGroupRequest"?: PatchTraitGroupRequest; +} + +/** + * Options to pass to create a TraitGroupInstance + */ +export interface TraitGroupListInstanceCreateOptions { + /** */ + "traitGroupRequest"?: TraitGroupRequest; +} + +/** + * Options to pass to each + */ +export interface TraitGroupListInstanceEachOptions { + /** Whether to include trait definitions in the response */ + "includeTraits"?: boolean; + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TraitGroupInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TraitGroupListInstanceOptions { + /** Whether to include trait definitions in the response */ + "includeTraits"?: boolean; + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TraitGroupListInstancePageOptions { + /** Whether to include trait definitions in the response */ + "includeTraits"?: boolean; + /** The maximum number of items to return per page, maximum of 100. */ + "pageSize"?: number; + /** The token for the page of results to retrieve. */ + "pageToken"?: string; + /** Either \'ASC\' or \'DESC\' to sort results ascending or descending respectively. */ + "orderBy"?: 'ASC' | 'DESC'; +} + + +export interface TraitGroupContext { + + /** + * Remove a TraitGroupInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + remove(callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance> + + /** + * Remove a TraitGroupInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>> + + /** + * Fetch a TraitGroupInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + fetch(callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance>; + /** + * Fetch a TraitGroupInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + fetch(params: TraitGroupContextFetchOptions, callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance>; + + /** + * Fetch a TraitGroupInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>>; + /** + * Fetch a TraitGroupInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + fetchWithHttpInfo(params: TraitGroupContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>>; + + /** + * Patch a TraitGroupInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + patch(callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance>; + /** + * Patch a TraitGroupInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + patch(params: PatchTraitGroupRequest, headers?: any, callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance>; + + /** + * Patch a TraitGroupInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + patchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>>; + /** + * Patch a TraitGroupInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + patchWithHttpInfo(params: PatchTraitGroupRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TraitGroupContextSolution { + "storeId": string; + "traitGroupName": string; +} + +export class TraitGroupContextImpl implements TraitGroupContext { + protected _solution: TraitGroupContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, storeId: string, traitGroupName: string) { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + if (!isValidPathParam(traitGroupName)) { + throw new Error('Parameter \'traitGroupName\' is not valid.'); + } + + this._solution = { storeId, traitGroupName, }; + this._uri = `/ControlPlane/Stores/${storeId}/TraitGroups/${traitGroupName}`; + } + + remove(callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "delete", headers}); + + operationPromise = operationPromise.then(payload => new TraitGroupInstance(operationVersion, payload, instance._solution.storeId, instance._solution.traitGroupName)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // DELETE operation that returns a response model + let operationPromise = operationVersion.fetchWithResponseInfo<TraitGroupResource>({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<TraitGroupInstance> => ({ + ...response, + body: new TraitGroupInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.traitGroupName) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(params?: TraitGroupContextFetchOptions | ((error: Error | null, item?: TraitGroupInstance) => any),callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["includeTraits"] !== undefined) + data["includeTraits"] = serialize.bool(params["includeTraits"]); + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new TraitGroupInstance(operationVersion, payload, instance._solution.storeId, instance._solution.traitGroupName)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: TraitGroupContextFetchOptions | ((error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["includeTraits"] !== undefined) + data["includeTraits"] = serialize.bool(params["includeTraits"]); + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TraitGroupResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TraitGroupInstance> => ({ + ...response, + body: new TraitGroupInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.traitGroupName) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patch(params?: PatchTraitGroupRequest | ((error: Error | null, item?: TraitGroupInstance) => any), headers?: any,callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<PatchTraitGroupRequest> as PatchTraitGroupRequest; + } else { + params = params || {} as Partial<PatchTraitGroupRequest> as PatchTraitGroupRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.patch({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new TraitGroupInstance(operationVersion, payload, instance._solution.storeId, instance._solution.traitGroupName)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patchWithHttpInfo(params?: PatchTraitGroupRequest | ((error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<PatchTraitGroupRequest> as PatchTraitGroupRequest; + } else { + params = params || {} as Partial<PatchTraitGroupRequest> as PatchTraitGroupRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.patchWithResponseInfo<TraitGroupResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<TraitGroupInstance> => ({ + ...response, + body: new TraitGroupInstance(operationVersion, response.body, instance._solution.storeId, instance._solution.traitGroupName) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for Meta + */ +export interface Meta { + key?: string; + pageSize?: number; + nextToken?: string; + previousToken?: string; +} + +/** + * Nested model for PatchTraitGroupRequest + */ +export interface PatchTraitGroupRequest { + description?: string; + traits?: { [key: string]: TraitDefinition; }; +} + +/** + * Nested model for TraitDefinition + */ +export interface TraitDefinition { + dataType: string; + description?: string; + validationRule?: ValidationRule; + idTypePromotion?: string; +} + +/** + * Nested model for TraitGroup + */ +export interface TraitGroup { + displayName: string; + description?: string; + traits?: { [key: string]: TraitGroupCoreTraitsValue; }; + version: number; +} + +/** + * Nested model for TraitGroupCoreTraitsValue + */ +export interface TraitGroupCoreTraitsValue { + dataType: string; + description?: string; + validationRule?: ValidationRule; + idTypePromotion?: string; +} + +/** + * Nested model for TraitGroupRequest + */ +export interface TraitGroupRequest { + displayName: string; + description?: string; + traits?: { [key: string]: TraitGroupCoreTraitsValue; }; +} + +/** + * Nested model for ValidationRule + */ +export interface ValidationRule { + pattern?: string; + minLength?: number; + maxLength?: number; + ruleType: string; + min?: number; + max?: number; + minItems?: number; + maxItems?: number; +} + + + + interface TraitGroupPayload extends TokenPaginationPayload { + traitGroups: TraitGroupResource[]; +} + +/** + * Response model for DeleteTraitGroup202Response operations + */ +interface DeleteTraitGroup202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Response model for TraitGroup operations + */ +interface TraitGroup_ResponseResource { + displayName: string; + description?: string; + traits?: { [key: string]: TraitGroupCoreTraitsValue; }; + version: number; +} + +/** + * Response model for PatchTraitGroup202Response operations + */ +interface PatchTraitGroup202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Response model for FetchTraitGroup200Response operations + */ +interface FetchTraitGroup200Response_ResponseResource { + traitGroup?: TraitGroup; + meta?: Meta; +} + +/** + * Response model for CreateTraitGroup202Response operations + */ +interface CreateTraitGroup202Response_ResponseResource { + message?: string; + statusUrl?: string; +} + +/** + * Union type for all possible response models + */ +type TraitGroupResource = DeleteTraitGroup202Response_ResponseResource | TraitGroup_ResponseResource | PatchTraitGroup202Response_ResponseResource | FetchTraitGroup200Response_ResponseResource | CreateTraitGroup202Response_ResponseResource; + +export class TraitGroupInstance { + protected _solution: TraitGroupContextSolution; + protected _context?: TraitGroupContext; + + constructor(protected _version: V1, _payload: TraitGroupResource, storeId: string, traitGroupName?: string) { + const payload: any = _payload; + this.message = (payload.message); + this.statusUrl = (payload.statusUrl); + this.displayName = (payload.displayName); + this.description = (payload.description); + this.traits = payload.traits; + this.version = deserialize.integer(payload.version); + this.traitGroup = payload.traitGroup !== null && payload.traitGroup !== undefined ? new TraitGroup(payload.traitGroup) : null; + this.meta = payload.meta !== null && payload.meta !== undefined ? new Meta(payload.meta) : null; + + this._solution = { storeId, traitGroupName: traitGroupName, }; + } + + message?: string; + /** + * URI to check operation status. + */ + statusUrl?: string; + /** + * Provides a unique and addressable name to be assigned to this Trait Group + */ + displayName?: string; + /** + * description of the Trait Group + */ + description?: string; + /** + * Map of traits that are part of this Trait Group, where the key is the trait name and the value is the trait\'s definition. + */ + traits?: { [key: string]: TraitGroupCoreTraitsValue; }; + /** + * The current version number of the Trait Group. Incremented on each successful update. + */ + version?: number; + traitGroup?: TraitGroup; + meta?: Meta; + + private get _proxy(): TraitGroupContext { + this._context = this._context || new TraitGroupContextImpl(this._version, this._solution.storeId, this._solution.traitGroupName); + return this._context; + } + + /** + * Remove a TraitGroupInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + remove(callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TraitGroupInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TraitGroupInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + fetch(callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance>; + /** + * Fetch a TraitGroupInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + fetch(params: TraitGroupContextFetchOptions, callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a TraitGroupInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>>; + /** + * Fetch a TraitGroupInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + fetchWithHttpInfo(params: TraitGroupContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Patch a TraitGroupInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + patch(callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance>; + /** + * Patch a TraitGroupInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + patch(params: PatchTraitGroupRequest, headers?: any, callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance>; + + patch(params?: any, callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance> + { + return this._proxy.patch(params, callback); + } + + /** + * Patch a TraitGroupInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + patchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>>; + /** + * Patch a TraitGroupInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + patchWithHttpInfo(params: PatchTraitGroupRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>>; + + patchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>> + { + return this._proxy.patchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + statusUrl: this.statusUrl, + displayName: this.displayName, + description: this.description, + traits: this.traits, + version: this.version, + traitGroup: this.traitGroup, + meta: this.meta, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TraitGroupSolution { + storeId: string; +} + +export interface TraitGroupListInstance { + _version: V1; + _solution: TraitGroupSolution; + _uri: string; + + (traitGroupName: string, ): TraitGroupContext; + get(traitGroupName: string, ): TraitGroupContext; + + + + + + + + + /** + * Create a TraitGroupInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + create(callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance>; + /** + * Create a TraitGroupInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance + */ + create(params: TraitGroupRequest, headers?: any, callback?: (error: Error | null, item?: TraitGroupInstance) => any): Promise<TraitGroupInstance>; + + /** + * Create a TraitGroupInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>>; + /** + * Create a TraitGroupInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TraitGroupInstance with HTTP metadata + */ + createWithHttpInfo(params: TraitGroupRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>>; + + + + + /** + * Streams TraitGroupInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitGroupListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TraitGroupInstance, done: (err?: Error) => void) => void): void; + each(params: TraitGroupListInstanceEachOptions, callback?: (item: TraitGroupInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TraitGroupInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitGroupListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TraitGroupInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TraitGroupListInstanceEachOptions, callback?: (item: TraitGroupInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TraitGroupInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TraitGroupPage) => any): Promise<TraitGroupPage>; + /** + * Retrieve a single target page of TraitGroupInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TraitGroupPage>) => any): Promise<ApiResponse<TraitGroupPage>>; + /** + * Lists TraitGroupInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitGroupListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TraitGroupInstance[]) => any): Promise<TraitGroupInstance[]>; + list(params: TraitGroupListInstanceOptions, callback?: (error: Error | null, items: TraitGroupInstance[]) => any): Promise<TraitGroupInstance[]>; + /** + * Lists TraitGroupInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitGroupListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TraitGroupInstance[]>) => any): Promise<ApiResponse<TraitGroupInstance[]>>; + listWithHttpInfo(params: TraitGroupListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TraitGroupInstance[]>) => any): Promise<ApiResponse<TraitGroupInstance[]>>; + /** + * Retrieve a single page of TraitGroupInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitGroupListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TraitGroupPage) => any): Promise<TraitGroupPage>; + page(params: TraitGroupListInstancePageOptions, callback?: (error: Error | null, items: TraitGroupPage) => any): Promise<TraitGroupPage>; + /** + * Retrieve a single page of TraitGroupInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TraitGroupListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TraitGroupPage>) => any): Promise<ApiResponse<TraitGroupPage>>; + pageWithHttpInfo(params: TraitGroupListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TraitGroupPage>) => any): Promise<ApiResponse<TraitGroupPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TraitGroupListInstance(version: V1, storeId: string): TraitGroupListInstance { + if (!isValidPathParam(storeId)) { + throw new Error('Parameter \'storeId\' is not valid.'); + } + + const instance = ((traitGroupName, ) => instance.get(traitGroupName, )) as TraitGroupListInstance; + + instance.get = function get(traitGroupName, ): TraitGroupContext { + return new TraitGroupContextImpl(version, storeId, traitGroupName); + } + + instance._version = version; + instance._solution = { storeId, }; + instance._uri = `/ControlPlane/Stores/${storeId}/TraitGroups`; + + instance.create = function create(params?: TraitGroupRequest | ((error: Error | null, items: TraitGroupInstance) => any), headers?: any, callback?: (error: Error | null, items: TraitGroupInstance) => any): Promise<TraitGroupInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<TraitGroupRequest> as TraitGroupRequest; + } else { + params = params || {} as Partial<TraitGroupRequest> as TraitGroupRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TraitGroupInstance(operationVersion, payload, instance._solution.storeId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: TraitGroupRequest | ((error: Error | null, items: ApiResponse<TraitGroupInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<TraitGroupInstance>) => any): Promise<ApiResponse<TraitGroupInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<TraitGroupRequest> as TraitGroupRequest; + } else { + params = params || {} as Partial<TraitGroupRequest> as TraitGroupRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TraitGroupResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TraitGroupInstance> => ({ + ...response, + body: new TraitGroupInstance(operationVersion, response.body, instance._solution.storeId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TraitGroupListInstancePageOptions | ((error: Error | null, items: TraitGroupPage) => any), callback?: (error: Error | null, items: TraitGroupPage) => any): Promise<TraitGroupPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["includeTraits"] !== undefined) + data["includeTraits"] = serialize.bool(params["includeTraits"]); + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TraitGroupPage(operationVersion, payload, instance._uri, data, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TraitGroupPage) => any): Promise<TraitGroupPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TraitGroupPage(instance._version, payload, instance._uri, {}, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TraitGroupListInstancePageOptions | ((error: Error | null, items: ApiResponse<TraitGroupPage>) => any), callback?: (error: Error | null, items: ApiResponse<TraitGroupPage>) => any): Promise<ApiResponse<TraitGroupPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["includeTraits"] !== undefined) + data["includeTraits"] = serialize.bool(params["includeTraits"]); + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + if (params["pageToken"] !== undefined) + data["pageToken"] = params["pageToken"]; + if (params["orderBy"] !== undefined) + data["orderBy"] = params["orderBy"]; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TraitGroupPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TraitGroupPage(operationVersion, response, instance._uri, data, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TraitGroupPage>) => any): Promise<ApiResponse<TraitGroupPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TraitGroupPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TraitGroupPage(instance._version, response, instance._uri, {}, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TraitGroupPage extends TokenPage<V1, TraitGroupPayload, TraitGroupResource, TraitGroupInstance> { +/** +* Initialize the TraitGroupPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param uri - URI of the resource +* @param params - Query parameters +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, uri: string, params: any, solution: TraitGroupSolution) { + super(version, response, uri, params, solution); + } + + /** + * Build an instance of TraitGroupInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TraitGroupResource): TraitGroupInstance { + + return new TraitGroupInstance( + this._version, + payload, + this._solution.storeId, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/V1.ts b/rest/messaging/V1.ts new file mode 100644 index 000000000..21d7eed40 --- /dev/null +++ b/rest/messaging/V1.ts @@ -0,0 +1,146 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import MessagingBase from "../MessagingBase"; +import Version from "../../base/Version"; +import { BrandRegistrationListInstance } from "./v1/brandRegistration"; +import { DeactivationsListInstance } from "./v1/deactivations"; +import { DomainCertsListInstance } from "./v1/domainCerts"; +import { DomainConfigListInstance } from "./v1/domainConfig"; +import { DomainConfigMessagingServiceListInstance } from "./v1/domainConfigMessagingService"; +import { DomainValidateDnListInstance } from "./v1/domainValidateDn"; +import { ExternalCampaignListInstance } from "./v1/externalCampaign"; +import { LinkshorteningMessagingServiceListInstance } from "./v1/linkshorteningMessagingService"; +import { LinkshorteningMessagingServiceDomainAssociationListInstance } from "./v1/linkshorteningMessagingServiceDomainAssociation"; +import { RequestManagedCertListInstance } from "./v1/requestManagedCert"; +import { ServiceListInstance } from "./v1/service"; +import { TollfreeVerificationListInstance } from "./v1/tollfreeVerification"; +import { UsecaseListInstance } from "./v1/usecase"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Messaging + * + * @param domain - The Twilio (Twilio.Messaging) domain + */ + constructor(domain: MessagingBase) { + super(domain, "v1"); + } + + /** brandRegistrations - { Twilio.Messaging.V1.BrandRegistrationListInstance } resource */ + protected _brandRegistrations?: BrandRegistrationListInstance; + /** deactivations - { Twilio.Messaging.V1.DeactivationsListInstance } resource */ + protected _deactivations?: DeactivationsListInstance; + /** domainCerts - { Twilio.Messaging.V1.DomainCertsListInstance } resource */ + protected _domainCerts?: DomainCertsListInstance; + /** domainConfig - { Twilio.Messaging.V1.DomainConfigListInstance } resource */ + protected _domainConfig?: DomainConfigListInstance; + /** domainConfigMessagingService - { Twilio.Messaging.V1.DomainConfigMessagingServiceListInstance } resource */ + protected _domainConfigMessagingService?: DomainConfigMessagingServiceListInstance; + /** domainValidateDns - { Twilio.Messaging.V1.DomainValidateDnListInstance } resource */ + protected _domainValidateDns?: DomainValidateDnListInstance; + /** externalCampaign - { Twilio.Messaging.V1.ExternalCampaignListInstance } resource */ + protected _externalCampaign?: ExternalCampaignListInstance; + /** linkshorteningMessagingService - { Twilio.Messaging.V1.LinkshorteningMessagingServiceListInstance } resource */ + protected _linkshorteningMessagingService?: LinkshorteningMessagingServiceListInstance; + /** linkshorteningMessagingServiceDomainAssociation - { Twilio.Messaging.V1.LinkshorteningMessagingServiceDomainAssociationListInstance } resource */ + protected _linkshorteningMessagingServiceDomainAssociation?: LinkshorteningMessagingServiceDomainAssociationListInstance; + /** requestManagedCert - { Twilio.Messaging.V1.RequestManagedCertListInstance } resource */ + protected _requestManagedCert?: RequestManagedCertListInstance; + /** services - { Twilio.Messaging.V1.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + /** tollfreeVerifications - { Twilio.Messaging.V1.TollfreeVerificationListInstance } resource */ + protected _tollfreeVerifications?: TollfreeVerificationListInstance; + /** usecases - { Twilio.Messaging.V1.UsecaseListInstance } resource */ + protected _usecases?: UsecaseListInstance; + + /** Getter for brandRegistrations resource */ + get brandRegistrations(): BrandRegistrationListInstance { + this._brandRegistrations = this._brandRegistrations || BrandRegistrationListInstance(this); + return this._brandRegistrations; + } + + /** Getter for deactivations resource */ + get deactivations(): DeactivationsListInstance { + this._deactivations = this._deactivations || DeactivationsListInstance(this); + return this._deactivations; + } + + /** Getter for domainCerts resource */ + get domainCerts(): DomainCertsListInstance { + this._domainCerts = this._domainCerts || DomainCertsListInstance(this); + return this._domainCerts; + } + + /** Getter for domainConfig resource */ + get domainConfig(): DomainConfigListInstance { + this._domainConfig = this._domainConfig || DomainConfigListInstance(this); + return this._domainConfig; + } + + /** Getter for domainConfigMessagingService resource */ + get domainConfigMessagingService(): DomainConfigMessagingServiceListInstance { + this._domainConfigMessagingService = this._domainConfigMessagingService || DomainConfigMessagingServiceListInstance(this); + return this._domainConfigMessagingService; + } + + /** Getter for domainValidateDns resource */ + get domainValidateDns(): DomainValidateDnListInstance { + this._domainValidateDns = this._domainValidateDns || DomainValidateDnListInstance(this); + return this._domainValidateDns; + } + + /** Getter for externalCampaign resource */ + get externalCampaign(): ExternalCampaignListInstance { + this._externalCampaign = this._externalCampaign || ExternalCampaignListInstance(this); + return this._externalCampaign; + } + + /** Getter for linkshorteningMessagingService resource */ + get linkshorteningMessagingService(): LinkshorteningMessagingServiceListInstance { + this._linkshorteningMessagingService = this._linkshorteningMessagingService || LinkshorteningMessagingServiceListInstance(this); + return this._linkshorteningMessagingService; + } + + /** Getter for linkshorteningMessagingServiceDomainAssociation resource */ + get linkshorteningMessagingServiceDomainAssociation(): LinkshorteningMessagingServiceDomainAssociationListInstance { + this._linkshorteningMessagingServiceDomainAssociation = this._linkshorteningMessagingServiceDomainAssociation || LinkshorteningMessagingServiceDomainAssociationListInstance(this); + return this._linkshorteningMessagingServiceDomainAssociation; + } + + /** Getter for requestManagedCert resource */ + get requestManagedCert(): RequestManagedCertListInstance { + this._requestManagedCert = this._requestManagedCert || RequestManagedCertListInstance(this); + return this._requestManagedCert; + } + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + + /** Getter for tollfreeVerifications resource */ + get tollfreeVerifications(): TollfreeVerificationListInstance { + this._tollfreeVerifications = this._tollfreeVerifications || TollfreeVerificationListInstance(this); + return this._tollfreeVerifications; + } + + /** Getter for usecases resource */ + get usecases(): UsecaseListInstance { + this._usecases = this._usecases || UsecaseListInstance(this); + return this._usecases; + } + +} diff --git a/rest/messaging/V2.ts b/rest/messaging/V2.ts new file mode 100644 index 000000000..2eec73bcb --- /dev/null +++ b/rest/messaging/V2.ts @@ -0,0 +1,56 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import MessagingBase from "../MessagingBase"; +import Version from "../../base/Version"; +import { ChannelsSenderListInstance } from "./v2/channelsSender"; +import { DomainCertsListInstance } from "./v2/domainCerts"; +import { TypingIndicatorListInstance } from "./v2/typingIndicator"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Messaging + * + * @param domain - The Twilio (Twilio.Messaging) domain + */ + constructor(domain: MessagingBase) { + super(domain, "v2"); + } + + /** channelsSenders - { Twilio.Messaging.V2.ChannelsSenderListInstance } resource */ + protected _channelsSenders?: ChannelsSenderListInstance; + /** domainCerts - { Twilio.Messaging.V2.DomainCertsListInstance } resource */ + protected _domainCerts?: DomainCertsListInstance; + /** typingIndicator - { Twilio.Messaging.V2.TypingIndicatorListInstance } resource */ + protected _typingIndicator?: TypingIndicatorListInstance; + + /** Getter for channelsSenders resource */ + get channelsSenders(): ChannelsSenderListInstance { + this._channelsSenders = this._channelsSenders || ChannelsSenderListInstance(this); + return this._channelsSenders; + } + + /** Getter for domainCerts resource */ + get domainCerts(): DomainCertsListInstance { + this._domainCerts = this._domainCerts || DomainCertsListInstance(this); + return this._domainCerts; + } + + /** Getter for typingIndicator resource */ + get typingIndicator(): TypingIndicatorListInstance { + this._typingIndicator = this._typingIndicator || TypingIndicatorListInstance(this); + return this._typingIndicator; + } + +} diff --git a/rest/messaging/V3.ts b/rest/messaging/V3.ts new file mode 100644 index 000000000..85398ebc9 --- /dev/null +++ b/rest/messaging/V3.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import MessagingBase from "../MessagingBase"; +import Version from "../../base/Version"; +import { TypingIndicatorListInstance } from "./v3/typingIndicator"; + +export default class V3 extends Version { + /** + * Initialize the V3 version of Messaging + * + * @param domain - The Twilio (Twilio.Messaging) domain + */ + constructor(domain: MessagingBase) { + super(domain, "v3"); + } + + /** typingIndicator - { Twilio.Messaging.V3.TypingIndicatorListInstance } resource */ + protected _typingIndicator?: TypingIndicatorListInstance; + + /** Getter for typingIndicator resource */ + get typingIndicator(): TypingIndicatorListInstance { + this._typingIndicator = this._typingIndicator || TypingIndicatorListInstance(this); + return this._typingIndicator; + } + +} diff --git a/rest/messaging/v1/brandRegistration.ts b/rest/messaging/v1/brandRegistration.ts new file mode 100644 index 000000000..a873912d2 --- /dev/null +++ b/rest/messaging/v1/brandRegistration.ts @@ -0,0 +1,905 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { BrandRegistrationOtpListInstance } from "./brandRegistration/brandRegistrationOtp"; +import { BrandVettingListInstance } from "./brandRegistration/brandVetting"; + + +/** + * DEPRECATED. Feedback on how to improve brand score + */ +export type BrandRegistrationBrandFeedback = 'TAX_ID'|'STOCK_SYMBOL'|'NONPROFIT'|'GOVERNMENT_ENTITY'|'OTHERS'; + +/** + * When a brand is registered, TCR will attempt to verify the identity of the brand based on the supplied information. + */ +export type BrandRegistrationIdentityStatus = 'SELF_DECLARED'|'UNVERIFIED'|'VERIFIED'|'VETTED_VERIFIED'; + +/** + * Brand Registration status. One of \"PENDING\", \"APPROVED\", \"FAILED\", \"IN_REVIEW\", \"DELETION_PENDING\", \"DELETION_FAILED\", \"SUSPENDED\". + */ +export type BrandRegistrationStatus = 'PENDING'|'APPROVED'|'FAILED'|'IN_REVIEW'|'DELETION_PENDING'|'DELETION_FAILED'|'SUSPENDED'; + + + + +/** + * Options to pass to create a BrandRegistrationInstance + */ +export interface BrandRegistrationListInstanceCreateOptions { + /** Customer Profile Bundle Sid. */ + "customerProfileBundleSid": string; + /** A2P Messaging Profile Bundle Sid. */ + "a2PProfileBundleSid": string; + /** Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. */ + "brandType"?: string; + /** A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. */ + "mock"?: boolean; + /** A flag to disable automatic secondary vetting for brands which it would otherwise be done. */ + "skipAutomaticSecVet"?: boolean; +} + +/** + * Options to pass to each + */ +export interface BrandRegistrationListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BrandRegistrationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BrandRegistrationListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BrandRegistrationListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface BrandRegistrationContext { + brandRegistrationOtps: BrandRegistrationOtpListInstance; + brandVettings: BrandVettingListInstance; + + /** + * Fetch a BrandRegistrationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationInstance + */ + fetch(callback?: (error: Error | null, item?: BrandRegistrationInstance) => any): Promise<BrandRegistrationInstance> + + /** + * Fetch a BrandRegistrationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BrandRegistrationInstance>) => any): Promise<ApiResponse<BrandRegistrationInstance>> + + /** + * Update a BrandRegistrationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationInstance + */ + update(callback?: (error: Error | null, item?: BrandRegistrationInstance) => any): Promise<BrandRegistrationInstance> + + /** + * Update a BrandRegistrationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BrandRegistrationInstance>) => any): Promise<ApiResponse<BrandRegistrationInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BrandRegistrationContextSolution { + "sid": string; +} + +export class BrandRegistrationContextImpl implements BrandRegistrationContext { + protected _solution: BrandRegistrationContextSolution; + protected _uri: string; + + protected _brandRegistrationOtps?: BrandRegistrationOtpListInstance; + protected _brandVettings?: BrandVettingListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/a2p/BrandRegistrations/${sid}`; + } + + get brandRegistrationOtps(): BrandRegistrationOtpListInstance { + this._brandRegistrationOtps = this._brandRegistrationOtps || BrandRegistrationOtpListInstance(this._version, this._solution.sid); + return this._brandRegistrationOtps; + } + + get brandVettings(): BrandVettingListInstance { + this._brandVettings = this._brandVettings || BrandVettingListInstance(this._version, this._solution.sid); + return this._brandVettings; + } + + fetch(callback?: (error: Error | null, item?: BrandRegistrationInstance) => any): Promise<BrandRegistrationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BrandRegistrationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BrandRegistrationInstance>) => any): Promise<ApiResponse<BrandRegistrationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<BrandRegistrationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<BrandRegistrationInstance> => ({ + ...response, + body: new BrandRegistrationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(callback?: (error: Error | null, item?: BrandRegistrationInstance) => any): Promise<BrandRegistrationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new BrandRegistrationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BrandRegistrationInstance>) => any): Promise<ApiResponse<BrandRegistrationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<BrandRegistrationResource>({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse<BrandRegistrationInstance> => ({ + ...response, + body: new BrandRegistrationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BrandRegistrationPayload extends TwilioResponsePayload { + data: BrandRegistrationResource[]; +} + +interface BrandRegistrationResource { + sid: string; + account_sid: string; + customer_profile_bundle_sid: string; + a2p_profile_bundle_sid: string; + date_created: Date; + date_updated: Date; + brand_type: string; + status: BrandRegistrationStatus; + tcr_id: string; + failure_reason: string; + errors: Array<any>; + url: string; + brand_score: number; + brand_feedback: Array<BrandRegistrationBrandFeedback>; + identity_status: BrandRegistrationIdentityStatus; + russell_3000: boolean; + government_entity: boolean; + tax_exempt_status: string; + skip_automatic_sec_vet: boolean; + mock: boolean; + links: Record<string, string>; +} + +export class BrandRegistrationInstance { + protected _solution: BrandRegistrationContextSolution; + protected _context?: BrandRegistrationContext; + + constructor(protected _version: V1, payload: BrandRegistrationResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.customerProfileBundleSid = (payload.customer_profile_bundle_sid); + this.a2pProfileBundleSid = (payload.a2p_profile_bundle_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.brandType = (payload.brand_type); + this.status = payload.status; + this.tcrId = (payload.tcr_id); + this.failureReason = (payload.failure_reason); + this.errors = (payload.errors); + this.url = (payload.url); + this.brandScore = deserialize.integer(payload.brand_score); + this.brandFeedback = (payload.brand_feedback); + this.identityStatus = payload.identity_status; + this.russell3000 = (payload.russell_3000); + this.governmentEntity = (payload.government_entity); + this.taxExemptStatus = (payload.tax_exempt_status); + this.skipAutomaticSecVet = (payload.skip_automatic_sec_vet); + this.mock = (payload.mock); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string to identify Brand Registration. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Brand Registration resource. + */ + accountSid: string; + /** + * A2P Messaging Profile Bundle BundleSid. + */ + customerProfileBundleSid: string; + /** + * A2P Messaging Profile Bundle BundleSid. + */ + a2pProfileBundleSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * Type of brand. One of: \"STANDARD\", \"SOLE_PROPRIETOR\". SOLE_PROPRIETOR is for the low volume, SOLE_PROPRIETOR campaign use case. There can only be one SOLE_PROPRIETOR campaign created per SOLE_PROPRIETOR brand. STANDARD is for all other campaign use cases. Multiple campaign use cases can be created per STANDARD brand. + */ + brandType: string; + status: BrandRegistrationStatus; + /** + * Campaign Registry (TCR) Brand ID. Assigned only after successful brand registration. + */ + tcrId: string; + /** + * DEPRECATED. A reason why brand registration has failed. Only applicable when status is FAILED. + */ + failureReason: string; + /** + * A list of errors that occurred during the brand registration process. + */ + errors: Array<any>; + /** + * The absolute URL of the Brand Registration resource. + */ + url: string; + /** + * The secondary vetting score if it was done. Otherwise, it will be the brand score if it\'s returned from TCR. It may be null if no score is available. + */ + brandScore: number; + /** + * DEPRECATED. Feedback on how to improve brand score + */ + brandFeedback: Array<BrandRegistrationBrandFeedback>; + identityStatus: BrandRegistrationIdentityStatus; + /** + * Publicly traded company identified in the Russell 3000 Index + */ + russell3000: boolean; + /** + * Identified as a government entity + */ + governmentEntity: boolean; + /** + * Nonprofit organization tax-exempt status per section 501 of the U.S. tax code. + */ + taxExemptStatus: string; + /** + * A flag to disable automatic secondary vetting for brands which it would otherwise be done. + */ + skipAutomaticSecVet: boolean; + /** + * A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + */ + mock: boolean; + links: Record<string, string>; + + private get _proxy(): BrandRegistrationContext { + this._context = this._context || new BrandRegistrationContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a BrandRegistrationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationInstance + */ + fetch(callback?: (error: Error | null, item?: BrandRegistrationInstance) => any): Promise<BrandRegistrationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BrandRegistrationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BrandRegistrationInstance>) => any): Promise<ApiResponse<BrandRegistrationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a BrandRegistrationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationInstance + */ + update(callback?: (error: Error | null, item?: BrandRegistrationInstance) => any): Promise<BrandRegistrationInstance> + + { + return this._proxy.update(callback); + } + + /** + * Update a BrandRegistrationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BrandRegistrationInstance>) => any): Promise<ApiResponse<BrandRegistrationInstance>> + + { + return this._proxy.updateWithHttpInfo(callback); + } + + /** + * Access the brandRegistrationOtps. + */ + brandRegistrationOtps(): BrandRegistrationOtpListInstance { + return this._proxy.brandRegistrationOtps; + } + + /** + * Access the brandVettings. + */ + brandVettings(): BrandVettingListInstance { + return this._proxy.brandVettings; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + customerProfileBundleSid: this.customerProfileBundleSid, + a2pProfileBundleSid: this.a2pProfileBundleSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + brandType: this.brandType, + status: this.status, + tcrId: this.tcrId, + failureReason: this.failureReason, + errors: this.errors, + url: this.url, + brandScore: this.brandScore, + brandFeedback: this.brandFeedback, + identityStatus: this.identityStatus, + russell3000: this.russell3000, + governmentEntity: this.governmentEntity, + taxExemptStatus: this.taxExemptStatus, + skipAutomaticSecVet: this.skipAutomaticSecVet, + mock: this.mock, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BrandRegistrationSolution { +} + +export interface BrandRegistrationListInstance { + _version: V1; + _solution: BrandRegistrationSolution; + _uri: string; + + (sid: string, ): BrandRegistrationContext; + get(sid: string, ): BrandRegistrationContext; + + + + + + + /** + * Create a BrandRegistrationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationInstance + */ + create(params: BrandRegistrationListInstanceCreateOptions, callback?: (error: Error | null, item?: BrandRegistrationInstance) => any): Promise<BrandRegistrationInstance>; + + /** + * Create a BrandRegistrationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationInstance with HTTP metadata + */ + createWithHttpInfo(params: BrandRegistrationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<BrandRegistrationInstance>) => any): Promise<ApiResponse<BrandRegistrationInstance>>; + + + + + /** + * Streams BrandRegistrationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandRegistrationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BrandRegistrationInstance, done: (err?: Error) => void) => void): void; + each(params: BrandRegistrationListInstanceEachOptions, callback?: (item: BrandRegistrationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BrandRegistrationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandRegistrationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BrandRegistrationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BrandRegistrationListInstanceEachOptions, callback?: (item: BrandRegistrationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BrandRegistrationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BrandRegistrationPage) => any): Promise<BrandRegistrationPage>; + /** + * Retrieve a single target page of BrandRegistrationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<BrandRegistrationPage>) => any): Promise<ApiResponse<BrandRegistrationPage>>; + /** + * Lists BrandRegistrationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandRegistrationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BrandRegistrationInstance[]) => any): Promise<BrandRegistrationInstance[]>; + list(params: BrandRegistrationListInstanceOptions, callback?: (error: Error | null, items: BrandRegistrationInstance[]) => any): Promise<BrandRegistrationInstance[]>; + /** + * Lists BrandRegistrationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandRegistrationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BrandRegistrationInstance[]>) => any): Promise<ApiResponse<BrandRegistrationInstance[]>>; + listWithHttpInfo(params: BrandRegistrationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<BrandRegistrationInstance[]>) => any): Promise<ApiResponse<BrandRegistrationInstance[]>>; + /** + * Retrieve a single page of BrandRegistrationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandRegistrationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BrandRegistrationPage) => any): Promise<BrandRegistrationPage>; + page(params: BrandRegistrationListInstancePageOptions, callback?: (error: Error | null, items: BrandRegistrationPage) => any): Promise<BrandRegistrationPage>; + /** + * Retrieve a single page of BrandRegistrationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandRegistrationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BrandRegistrationPage>) => any): Promise<ApiResponse<BrandRegistrationPage>>; + pageWithHttpInfo(params: BrandRegistrationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<BrandRegistrationPage>) => any): Promise<ApiResponse<BrandRegistrationPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BrandRegistrationListInstance(version: V1): BrandRegistrationListInstance { + const instance = ((sid, ) => instance.get(sid, )) as BrandRegistrationListInstance; + + instance.get = function get(sid, ): BrandRegistrationContext { + return new BrandRegistrationContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/a2p/BrandRegistrations`; + + instance.create = function create(params: BrandRegistrationListInstanceCreateOptions, callback?: (error: Error | null, items: BrandRegistrationInstance) => any): Promise<BrandRegistrationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["customerProfileBundleSid"] === null || params["customerProfileBundleSid"] === undefined) { + throw new Error('Required parameter "params[\'customerProfileBundleSid\']" missing.'); + } + + if (params["a2PProfileBundleSid"] === null || params["a2PProfileBundleSid"] === undefined) { + throw new Error('Required parameter "params[\'a2PProfileBundleSid\']" missing.'); + } + + let data: any = {}; + + + + data["CustomerProfileBundleSid"] = params["customerProfileBundleSid"]; + + data["A2PProfileBundleSid"] = params["a2PProfileBundleSid"]; + if (params["brandType"] !== undefined) + data["BrandType"] = params["brandType"]; + if (params["mock"] !== undefined) + data["Mock"] = serialize.bool(params["mock"]); + if (params["skipAutomaticSecVet"] !== undefined) + data["SkipAutomaticSecVet"] = serialize.bool(params["skipAutomaticSecVet"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BrandRegistrationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: BrandRegistrationListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<BrandRegistrationInstance>) => any): Promise<ApiResponse<BrandRegistrationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["customerProfileBundleSid"] === null || params["customerProfileBundleSid"] === undefined) { + throw new Error('Required parameter "params[\'customerProfileBundleSid\']" missing.'); + } + + if (params["a2PProfileBundleSid"] === null || params["a2PProfileBundleSid"] === undefined) { + throw new Error('Required parameter "params[\'a2PProfileBundleSid\']" missing.'); + } + + let data: any = {}; + + + + data["CustomerProfileBundleSid"] = params["customerProfileBundleSid"]; + + data["A2PProfileBundleSid"] = params["a2PProfileBundleSid"]; + if (params["brandType"] !== undefined) + data["BrandType"] = params["brandType"]; + if (params["mock"] !== undefined) + data["Mock"] = serialize.bool(params["mock"]); + if (params["skipAutomaticSecVet"] !== undefined) + data["SkipAutomaticSecVet"] = serialize.bool(params["skipAutomaticSecVet"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BrandRegistrationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BrandRegistrationInstance> => ({ + ...response, + body: new BrandRegistrationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: BrandRegistrationListInstancePageOptions | ((error: Error | null, items: BrandRegistrationPage) => any), callback?: (error: Error | null, items: BrandRegistrationPage) => any): Promise<BrandRegistrationPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BrandRegistrationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BrandRegistrationPage) => any): Promise<BrandRegistrationPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BrandRegistrationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BrandRegistrationListInstancePageOptions | ((error: Error | null, items: ApiResponse<BrandRegistrationPage>) => any), callback?: (error: Error | null, items: ApiResponse<BrandRegistrationPage>) => any): Promise<ApiResponse<BrandRegistrationPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<BrandRegistrationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BrandRegistrationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<BrandRegistrationPage>) => any): Promise<ApiResponse<BrandRegistrationPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<BrandRegistrationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BrandRegistrationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class BrandRegistrationPage extends Page<V1, BrandRegistrationPayload, BrandRegistrationResource, BrandRegistrationInstance> { +/** +* Initialize the BrandRegistrationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: BrandRegistrationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of BrandRegistrationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BrandRegistrationResource): BrandRegistrationInstance { + + return new BrandRegistrationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v1/brandRegistration/brandRegistrationOtp.ts b/rest/messaging/v1/brandRegistration/brandRegistrationOtp.ts new file mode 100644 index 000000000..9e11a0425 --- /dev/null +++ b/rest/messaging/v1/brandRegistration/brandRegistrationOtp.ts @@ -0,0 +1,162 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +export interface BrandRegistrationOtpSolution { + brandRegistrationSid: string; +} + +export interface BrandRegistrationOtpListInstance { + _version: V1; + _solution: BrandRegistrationOtpSolution; + _uri: string; + + + + /** + * Create a BrandRegistrationOtpInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationOtpInstance + */ + create(callback?: (error: Error | null, item?: BrandRegistrationOtpInstance) => any): Promise<BrandRegistrationOtpInstance> + + /** + * Create a BrandRegistrationOtpInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandRegistrationOtpInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BrandRegistrationOtpInstance>) => any): Promise<ApiResponse<BrandRegistrationOtpInstance>> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BrandRegistrationOtpListInstance(version: V1, brandRegistrationSid: string): BrandRegistrationOtpListInstance { + if (!isValidPathParam(brandRegistrationSid)) { + throw new Error('Parameter \'brandRegistrationSid\' is not valid.'); + } + + const instance = {} as BrandRegistrationOtpListInstance; + + instance._version = version; + instance._solution = { brandRegistrationSid, }; + instance._uri = `/a2p/BrandRegistrations/${brandRegistrationSid}/SmsOtp`; + + instance.create = function create( callback?: (error: Error | null, items: BrandRegistrationOtpInstance) => any): Promise<BrandRegistrationOtpInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new BrandRegistrationOtpInstance(operationVersion, payload, instance._solution.brandRegistrationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<BrandRegistrationOtpInstance>) => any): Promise<ApiResponse<BrandRegistrationOtpInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BrandRegistrationOtpResource>({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse<BrandRegistrationOtpInstance> => ({ + ...response, + body: new BrandRegistrationOtpInstance(operationVersion, response.body, instance._solution.brandRegistrationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface BrandRegistrationOtpPayload extends BrandRegistrationOtpResource {} + +interface BrandRegistrationOtpResource { + account_sid: string; + brand_registration_sid: string; +} + +export class BrandRegistrationOtpInstance { + + constructor(protected _version: V1, payload: BrandRegistrationOtpResource, brandRegistrationSid: string) { + + this.accountSid = (payload.account_sid); + this.brandRegistrationSid = (payload.brand_registration_sid); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Brand Registration resource. + */ + accountSid: string; + /** + * The unique string to identify Brand Registration of Sole Proprietor Brand + */ + brandRegistrationSid: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + brandRegistrationSid: this.brandRegistrationSid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/messaging/v1/brandRegistration/brandVetting.ts b/rest/messaging/v1/brandRegistration/brandVetting.ts new file mode 100644 index 000000000..0196a1d51 --- /dev/null +++ b/rest/messaging/v1/brandRegistration/brandVetting.ts @@ -0,0 +1,697 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The third-party provider that has conducted the vetting. One of “CampaignVerify” (Campaign Verify tokens) or “AEGIS” (Secondary Vetting). + */ +export type BrandVettingVettingProvider = 'campaign-verify'|'aegis'; + + + +/** + * Options to pass to create a BrandVettingInstance + */ +export interface BrandVettingListInstanceCreateOptions { + /** */ + "vettingProvider": BrandVettingVettingProvider; + /** The unique ID of the vetting */ + "vettingId"?: string; +} + +/** + * Options to pass to each + */ +export interface BrandVettingListInstanceEachOptions { + /** The third-party provider of the vettings to read */ + "vettingProvider"?: BrandVettingVettingProvider; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BrandVettingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BrandVettingListInstanceOptions { + /** The third-party provider of the vettings to read */ + "vettingProvider"?: BrandVettingVettingProvider; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BrandVettingListInstancePageOptions { + /** The third-party provider of the vettings to read */ + "vettingProvider"?: BrandVettingVettingProvider; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface BrandVettingContext { + + /** + * Fetch a BrandVettingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandVettingInstance + */ + fetch(callback?: (error: Error | null, item?: BrandVettingInstance) => any): Promise<BrandVettingInstance> + + /** + * Fetch a BrandVettingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandVettingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BrandVettingInstance>) => any): Promise<ApiResponse<BrandVettingInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BrandVettingContextSolution { + "brandSid": string; + "brandVettingSid": string; +} + +export class BrandVettingContextImpl implements BrandVettingContext { + protected _solution: BrandVettingContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, brandSid: string, brandVettingSid: string) { + if (!isValidPathParam(brandSid)) { + throw new Error('Parameter \'brandSid\' is not valid.'); + } + + if (!isValidPathParam(brandVettingSid)) { + throw new Error('Parameter \'brandVettingSid\' is not valid.'); + } + + this._solution = { brandSid, brandVettingSid, }; + this._uri = `/a2p/BrandRegistrations/${brandSid}/Vettings/${brandVettingSid}`; + } + + fetch(callback?: (error: Error | null, item?: BrandVettingInstance) => any): Promise<BrandVettingInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BrandVettingInstance(operationVersion, payload, instance._solution.brandSid, instance._solution.brandVettingSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BrandVettingInstance>) => any): Promise<ApiResponse<BrandVettingInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<BrandVettingResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<BrandVettingInstance> => ({ + ...response, + body: new BrandVettingInstance(operationVersion, response.body, instance._solution.brandSid, instance._solution.brandVettingSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BrandVettingPayload extends TwilioResponsePayload { + data: BrandVettingResource[]; +} + +interface BrandVettingResource { + account_sid: string; + brand_sid: string; + brand_vetting_sid: string; + date_updated: Date; + date_created: Date; + vetting_id: string; + vetting_class: string; + vetting_status: string; + vetting_provider: BrandVettingVettingProvider; + url: string; +} + +export class BrandVettingInstance { + protected _solution: BrandVettingContextSolution; + protected _context?: BrandVettingContext; + + constructor(protected _version: V1, payload: BrandVettingResource, brandSid: string, brandVettingSid?: string) { + + this.accountSid = (payload.account_sid); + this.brandSid = (payload.brand_sid); + this.brandVettingSid = (payload.brand_vetting_sid); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.vettingId = (payload.vetting_id); + this.vettingClass = (payload.vetting_class); + this.vettingStatus = (payload.vetting_status); + this.vettingProvider = payload.vetting_provider; + this.url = (payload.url); + + this._solution = { brandSid, brandVettingSid: brandVettingSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the vetting record. + */ + accountSid: string; + /** + * The unique string to identify Brand Registration. + */ + brandSid: string; + /** + * The Twilio SID of the third-party vetting record. + */ + brandVettingSid: string; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The unique identifier of the vetting from the third-party provider. + */ + vettingId: string; + /** + * The type of vetting that has been conducted. One of “STANDARD” (Aegis) or “POLITICAL” (Campaign Verify). + */ + vettingClass: string; + /** + * The status of the import vetting attempt. One of “PENDING,” “SUCCESS,” or “FAILED”. + */ + vettingStatus: string; + vettingProvider: BrandVettingVettingProvider; + /** + * The absolute URL of the Brand Vetting resource. + */ + url: string; + + private get _proxy(): BrandVettingContext { + this._context = this._context || new BrandVettingContextImpl(this._version, this._solution.brandSid, this._solution.brandVettingSid); + return this._context; + } + + /** + * Fetch a BrandVettingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandVettingInstance + */ + fetch(callback?: (error: Error | null, item?: BrandVettingInstance) => any): Promise<BrandVettingInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BrandVettingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandVettingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BrandVettingInstance>) => any): Promise<ApiResponse<BrandVettingInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + brandSid: this.brandSid, + brandVettingSid: this.brandVettingSid, + dateUpdated: this.dateUpdated, + dateCreated: this.dateCreated, + vettingId: this.vettingId, + vettingClass: this.vettingClass, + vettingStatus: this.vettingStatus, + vettingProvider: this.vettingProvider, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BrandVettingSolution { + brandSid: string; +} + +export interface BrandVettingListInstance { + _version: V1; + _solution: BrandVettingSolution; + _uri: string; + + (brandVettingSid: string, ): BrandVettingContext; + get(brandVettingSid: string, ): BrandVettingContext; + + + + + /** + * Create a BrandVettingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandVettingInstance + */ + create(params: BrandVettingListInstanceCreateOptions, callback?: (error: Error | null, item?: BrandVettingInstance) => any): Promise<BrandVettingInstance>; + + /** + * Create a BrandVettingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BrandVettingInstance with HTTP metadata + */ + createWithHttpInfo(params: BrandVettingListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<BrandVettingInstance>) => any): Promise<ApiResponse<BrandVettingInstance>>; + + + + + /** + * Streams BrandVettingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandVettingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BrandVettingInstance, done: (err?: Error) => void) => void): void; + each(params: BrandVettingListInstanceEachOptions, callback?: (item: BrandVettingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BrandVettingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandVettingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BrandVettingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BrandVettingListInstanceEachOptions, callback?: (item: BrandVettingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BrandVettingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BrandVettingPage) => any): Promise<BrandVettingPage>; + /** + * Retrieve a single target page of BrandVettingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<BrandVettingPage>) => any): Promise<ApiResponse<BrandVettingPage>>; + /** + * Lists BrandVettingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandVettingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BrandVettingInstance[]) => any): Promise<BrandVettingInstance[]>; + list(params: BrandVettingListInstanceOptions, callback?: (error: Error | null, items: BrandVettingInstance[]) => any): Promise<BrandVettingInstance[]>; + /** + * Lists BrandVettingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandVettingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BrandVettingInstance[]>) => any): Promise<ApiResponse<BrandVettingInstance[]>>; + listWithHttpInfo(params: BrandVettingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<BrandVettingInstance[]>) => any): Promise<ApiResponse<BrandVettingInstance[]>>; + /** + * Retrieve a single page of BrandVettingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandVettingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BrandVettingPage) => any): Promise<BrandVettingPage>; + page(params: BrandVettingListInstancePageOptions, callback?: (error: Error | null, items: BrandVettingPage) => any): Promise<BrandVettingPage>; + /** + * Retrieve a single page of BrandVettingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BrandVettingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BrandVettingPage>) => any): Promise<ApiResponse<BrandVettingPage>>; + pageWithHttpInfo(params: BrandVettingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<BrandVettingPage>) => any): Promise<ApiResponse<BrandVettingPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BrandVettingListInstance(version: V1, brandSid: string): BrandVettingListInstance { + if (!isValidPathParam(brandSid)) { + throw new Error('Parameter \'brandSid\' is not valid.'); + } + + const instance = ((brandVettingSid, ) => instance.get(brandVettingSid, )) as BrandVettingListInstance; + + instance.get = function get(brandVettingSid, ): BrandVettingContext { + return new BrandVettingContextImpl(version, brandSid, brandVettingSid); + } + + instance._version = version; + instance._solution = { brandSid, }; + instance._uri = `/a2p/BrandRegistrations/${brandSid}/Vettings`; + + instance.create = function create(params: BrandVettingListInstanceCreateOptions, callback?: (error: Error | null, items: BrandVettingInstance) => any): Promise<BrandVettingInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["vettingProvider"] === null || params["vettingProvider"] === undefined) { + throw new Error('Required parameter "params[\'vettingProvider\']" missing.'); + } + + let data: any = {}; + + + + data["VettingProvider"] = params["vettingProvider"]; + if (params["vettingId"] !== undefined) + data["VettingId"] = params["vettingId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BrandVettingInstance(operationVersion, payload, instance._solution.brandSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: BrandVettingListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<BrandVettingInstance>) => any): Promise<ApiResponse<BrandVettingInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["vettingProvider"] === null || params["vettingProvider"] === undefined) { + throw new Error('Required parameter "params[\'vettingProvider\']" missing.'); + } + + let data: any = {}; + + + + data["VettingProvider"] = params["vettingProvider"]; + if (params["vettingId"] !== undefined) + data["VettingId"] = params["vettingId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BrandVettingResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BrandVettingInstance> => ({ + ...response, + body: new BrandVettingInstance(operationVersion, response.body, instance._solution.brandSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: BrandVettingListInstancePageOptions | ((error: Error | null, items: BrandVettingPage) => any), callback?: (error: Error | null, items: BrandVettingPage) => any): Promise<BrandVettingPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["vettingProvider"] !== undefined) + data["VettingProvider"] = params["vettingProvider"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BrandVettingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BrandVettingPage) => any): Promise<BrandVettingPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BrandVettingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BrandVettingListInstancePageOptions | ((error: Error | null, items: ApiResponse<BrandVettingPage>) => any), callback?: (error: Error | null, items: ApiResponse<BrandVettingPage>) => any): Promise<ApiResponse<BrandVettingPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["vettingProvider"] !== undefined) + data["VettingProvider"] = params["vettingProvider"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<BrandVettingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BrandVettingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<BrandVettingPage>) => any): Promise<ApiResponse<BrandVettingPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<BrandVettingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BrandVettingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class BrandVettingPage extends Page<V1, BrandVettingPayload, BrandVettingResource, BrandVettingInstance> { +/** +* Initialize the BrandVettingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: BrandVettingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of BrandVettingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BrandVettingResource): BrandVettingInstance { + + return new BrandVettingInstance( + this._version, + payload, + this._solution.brandSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v1/deactivations.ts b/rest/messaging/v1/deactivations.ts new file mode 100644 index 000000000..7bc94e973 --- /dev/null +++ b/rest/messaging/v1/deactivations.ts @@ -0,0 +1,306 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a DeactivationsInstance + */ +export interface DeactivationsContextFetchOptions { + /** The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. */ + "date"?: Date; +} + +export interface DeactivationsContext { + + /** + * Fetch a DeactivationsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeactivationsInstance + */ + fetch(callback?: (error: Error | null, item?: DeactivationsInstance) => any): Promise<DeactivationsInstance>; + /** + * Fetch a DeactivationsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeactivationsInstance + */ + fetch(params: DeactivationsContextFetchOptions, callback?: (error: Error | null, item?: DeactivationsInstance) => any): Promise<DeactivationsInstance>; + + /** + * Fetch a DeactivationsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeactivationsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DeactivationsInstance>) => any): Promise<ApiResponse<DeactivationsInstance>>; + /** + * Fetch a DeactivationsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeactivationsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: DeactivationsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<DeactivationsInstance>) => any): Promise<ApiResponse<DeactivationsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DeactivationsContextSolution { +} + +export class DeactivationsContextImpl implements DeactivationsContext { + protected _solution: DeactivationsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/Deactivations`; + } + + fetch(params?: DeactivationsContextFetchOptions | ((error: Error | null, item?: DeactivationsInstance) => any),callback?: (error: Error | null, item?: DeactivationsInstance) => any): Promise<DeactivationsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["date"] !== undefined) + data["Date"] = serialize.iso8601Date(params["date"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new DeactivationsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: DeactivationsContextFetchOptions | ((error: Error | null, item?: ApiResponse<DeactivationsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<DeactivationsInstance>) => any): Promise<ApiResponse<DeactivationsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["date"] !== undefined) + data["Date"] = serialize.iso8601Date(params["date"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DeactivationsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<DeactivationsInstance> => ({ + ...response, + body: new DeactivationsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DeactivationsPayload extends DeactivationsResource {} + +interface DeactivationsResource { + redirect_to: string; +} + +export class DeactivationsInstance { + protected _solution: DeactivationsContextSolution; + protected _context?: DeactivationsContext; + + constructor(protected _version: V1, payload: DeactivationsResource) { + + this.redirectTo = (payload.redirect_to); + + this._solution = { }; + } + + /** + * Returns an authenticated url that redirects to a file containing the deactivated numbers for the requested day. This url is valid for up to two minutes. + */ + redirectTo: string; + + private get _proxy(): DeactivationsContext { + this._context = this._context || new DeactivationsContextImpl(this._version); + return this._context; + } + + /** + * Fetch a DeactivationsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeactivationsInstance + */ + fetch(callback?: (error: Error | null, item?: DeactivationsInstance) => any): Promise<DeactivationsInstance>; + /** + * Fetch a DeactivationsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeactivationsInstance + */ + fetch(params: DeactivationsContextFetchOptions, callback?: (error: Error | null, item?: DeactivationsInstance) => any): Promise<DeactivationsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: DeactivationsInstance) => any): Promise<DeactivationsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a DeactivationsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeactivationsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DeactivationsInstance>) => any): Promise<ApiResponse<DeactivationsInstance>>; + /** + * Fetch a DeactivationsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeactivationsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: DeactivationsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<DeactivationsInstance>) => any): Promise<ApiResponse<DeactivationsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<DeactivationsInstance>) => any): Promise<ApiResponse<DeactivationsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + redirectTo: this.redirectTo, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DeactivationsSolution { +} + +export interface DeactivationsListInstance { + _version: V1; + _solution: DeactivationsSolution; + _uri: string; + + (): DeactivationsContext; + get(): DeactivationsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DeactivationsListInstance(version: V1): DeactivationsListInstance { + const instance = (() => instance.get()) as DeactivationsListInstance; + + instance.get = function get(): DeactivationsContext { + return new DeactivationsContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/messaging/v1/domainCerts.ts b/rest/messaging/v1/domainCerts.ts new file mode 100644 index 000000000..6df04816b --- /dev/null +++ b/rest/messaging/v1/domainCerts.ts @@ -0,0 +1,489 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a DomainCertsInstance + */ +export interface DomainCertsContextUpdateOptions { + /** Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. */ + "tlsCert": string; +} + +export interface DomainCertsContext { + + /** + * Remove a DomainCertsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a DomainCertsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a DomainCertsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance + */ + fetch(callback?: (error: Error | null, item?: DomainCertsInstance) => any): Promise<DomainCertsInstance> + + /** + * Fetch a DomainCertsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainCertsInstance>) => any): Promise<ApiResponse<DomainCertsInstance>> + + /** + * Update a DomainCertsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance + */ + update(params: DomainCertsContextUpdateOptions, callback?: (error: Error | null, item?: DomainCertsInstance) => any): Promise<DomainCertsInstance>; + + /** + * Update a DomainCertsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance with HTTP metadata + */ + updateWithHttpInfo(params: DomainCertsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<DomainCertsInstance>) => any): Promise<ApiResponse<DomainCertsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DomainCertsContextSolution { + "domainSid": string; +} + +export class DomainCertsContextImpl implements DomainCertsContext { + protected _solution: DomainCertsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, domainSid: string) { + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + this._solution = { domainSid, }; + this._uri = `/LinkShortening/Domains/${domainSid}/Certificate`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: DomainCertsInstance) => any): Promise<DomainCertsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DomainCertsInstance(operationVersion, payload, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainCertsInstance>) => any): Promise<ApiResponse<DomainCertsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DomainCertsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DomainCertsInstance> => ({ + ...response, + body: new DomainCertsInstance(operationVersion, response.body, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: DomainCertsContextUpdateOptions,callback?: (error: Error | null, item?: DomainCertsInstance) => any): Promise<DomainCertsInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["tlsCert"] === null || params["tlsCert"] === undefined) { + throw new Error('Required parameter "params[\'tlsCert\']" missing.'); + } + + let data: any = {}; + + + + data["TlsCert"] = params["tlsCert"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DomainCertsInstance(operationVersion, payload, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: DomainCertsContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<DomainCertsInstance>) => any): Promise<ApiResponse<DomainCertsInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["tlsCert"] === null || params["tlsCert"] === undefined) { + throw new Error('Required parameter "params[\'tlsCert\']" missing.'); + } + + let data: any = {}; + + + + data["TlsCert"] = params["tlsCert"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<DomainCertsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<DomainCertsInstance> => ({ + ...response, + body: new DomainCertsInstance(operationVersion, response.body, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DomainCertsPayload extends DomainCertsResource {} + +interface DomainCertsResource { + domain_sid: string; + date_updated: Date; + date_expires: Date; + date_created: Date; + domain_name: string; + certificate_sid: string; + url: string; + cert_in_validation: any; +} + +export class DomainCertsInstance { + protected _solution: DomainCertsContextSolution; + protected _context?: DomainCertsContext; + + constructor(protected _version: V1, payload: DomainCertsResource, domainSid?: string) { + + this.domainSid = (payload.domain_sid); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.dateExpires = deserialize.iso8601DateTime(payload.date_expires); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.domainName = (payload.domain_name); + this.certificateSid = (payload.certificate_sid); + this.url = (payload.url); + this.certInValidation = (payload.cert_in_validation); + + this._solution = { domainSid: domainSid, }; + } + + /** + * The unique string that we created to identify the Domain resource. + */ + domainSid: string; + /** + * Date that this Domain was last updated. + */ + dateUpdated: Date; + /** + * Date that the private certificate associated with this domain expires. You will need to update the certificate before that date to ensure your shortened links will continue to work. + */ + dateExpires: Date; + /** + * Date that this Domain was registered to the Twilio platform to create a new Domain object. + */ + dateCreated: Date; + /** + * Full url path for this domain. + */ + domainName: string; + /** + * The unique string that we created to identify this Certificate resource. + */ + certificateSid: string; + url: string; + /** + * Optional JSON field describing the status and upload date of a new certificate in the process of validation + */ + certInValidation: any; + + private get _proxy(): DomainCertsContext { + this._context = this._context || new DomainCertsContextImpl(this._version, this._solution.domainSid); + return this._context; + } + + /** + * Remove a DomainCertsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a DomainCertsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a DomainCertsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance + */ + fetch(callback?: (error: Error | null, item?: DomainCertsInstance) => any): Promise<DomainCertsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DomainCertsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainCertsInstance>) => any): Promise<ApiResponse<DomainCertsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a DomainCertsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance + */ + update(params: DomainCertsContextUpdateOptions, callback?: (error: Error | null, item?: DomainCertsInstance) => any): Promise<DomainCertsInstance>; + + update(params?: any, callback?: (error: Error | null, item?: DomainCertsInstance) => any): Promise<DomainCertsInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a DomainCertsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance with HTTP metadata + */ + updateWithHttpInfo(params: DomainCertsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<DomainCertsInstance>) => any): Promise<ApiResponse<DomainCertsInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<DomainCertsInstance>) => any): Promise<ApiResponse<DomainCertsInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domainSid: this.domainSid, + dateUpdated: this.dateUpdated, + dateExpires: this.dateExpires, + dateCreated: this.dateCreated, + domainName: this.domainName, + certificateSid: this.certificateSid, + url: this.url, + certInValidation: this.certInValidation, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DomainCertsSolution { +} + +export interface DomainCertsListInstance { + _version: V1; + _solution: DomainCertsSolution; + _uri: string; + + (domainSid: string, ): DomainCertsContext; + get(domainSid: string, ): DomainCertsContext; + + + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DomainCertsListInstance(version: V1): DomainCertsListInstance { + const instance = ((domainSid, ) => instance.get(domainSid, )) as DomainCertsListInstance; + + instance.get = function get(domainSid, ): DomainCertsContext { + return new DomainCertsContextImpl(version, domainSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/messaging/v1/domainConfig.ts b/rest/messaging/v1/domainConfig.ts new file mode 100644 index 000000000..9910b4c0d --- /dev/null +++ b/rest/messaging/v1/domainConfig.ts @@ -0,0 +1,466 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a DomainConfigInstance + */ +export interface DomainConfigContextUpdateOptions { + /** Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. */ + "fallbackUrl"?: string; + /** URL to receive click events to your webhook whenever the recipients click on the shortened links */ + "callbackUrl"?: string; + /** Boolean field to set customer delivery preference when there is a failure in linkShortening service */ + "continueOnFailure"?: boolean; + /** Customer\\\'s choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. */ + "disableHttps"?: boolean; +} + +export interface DomainConfigContext { + + /** + * Fetch a DomainConfigInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance + */ + fetch(callback?: (error: Error | null, item?: DomainConfigInstance) => any): Promise<DomainConfigInstance> + + /** + * Fetch a DomainConfigInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainConfigInstance>) => any): Promise<ApiResponse<DomainConfigInstance>> + + /** + * Update a DomainConfigInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance + */ + update(callback?: (error: Error | null, item?: DomainConfigInstance) => any): Promise<DomainConfigInstance>; + /** + * Update a DomainConfigInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance + */ + update(params: DomainConfigContextUpdateOptions, callback?: (error: Error | null, item?: DomainConfigInstance) => any): Promise<DomainConfigInstance>; + + /** + * Update a DomainConfigInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainConfigInstance>) => any): Promise<ApiResponse<DomainConfigInstance>>; + /** + * Update a DomainConfigInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance with HTTP metadata + */ + updateWithHttpInfo(params: DomainConfigContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<DomainConfigInstance>) => any): Promise<ApiResponse<DomainConfigInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DomainConfigContextSolution { + "domainSid": string; +} + +export class DomainConfigContextImpl implements DomainConfigContext { + protected _solution: DomainConfigContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, domainSid: string) { + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + this._solution = { domainSid, }; + this._uri = `/LinkShortening/Domains/${domainSid}/Config`; + } + + fetch(callback?: (error: Error | null, item?: DomainConfigInstance) => any): Promise<DomainConfigInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DomainConfigInstance(operationVersion, payload, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainConfigInstance>) => any): Promise<ApiResponse<DomainConfigInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DomainConfigResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DomainConfigInstance> => ({ + ...response, + body: new DomainConfigInstance(operationVersion, response.body, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: DomainConfigContextUpdateOptions | ((error: Error | null, item?: DomainConfigInstance) => any),callback?: (error: Error | null, item?: DomainConfigInstance) => any): Promise<DomainConfigInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["fallbackUrl"] !== undefined) + data["FallbackUrl"] = params["fallbackUrl"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["continueOnFailure"] !== undefined) + data["ContinueOnFailure"] = serialize.bool(params["continueOnFailure"]); + if (params["disableHttps"] !== undefined) + data["DisableHttps"] = serialize.bool(params["disableHttps"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DomainConfigInstance(operationVersion, payload, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: DomainConfigContextUpdateOptions | ((error: Error | null, item?: ApiResponse<DomainConfigInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<DomainConfigInstance>) => any): Promise<ApiResponse<DomainConfigInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["fallbackUrl"] !== undefined) + data["FallbackUrl"] = params["fallbackUrl"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["continueOnFailure"] !== undefined) + data["ContinueOnFailure"] = serialize.bool(params["continueOnFailure"]); + if (params["disableHttps"] !== undefined) + data["DisableHttps"] = serialize.bool(params["disableHttps"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<DomainConfigResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<DomainConfigInstance> => ({ + ...response, + body: new DomainConfigInstance(operationVersion, response.body, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DomainConfigPayload extends DomainConfigResource {} + +interface DomainConfigResource { + domain_sid: string; + config_sid: string; + fallback_url: string; + callback_url: string; + continue_on_failure: boolean; + date_created: Date; + date_updated: Date; + url: string; + disable_https: boolean; +} + +export class DomainConfigInstance { + protected _solution: DomainConfigContextSolution; + protected _context?: DomainConfigContext; + + constructor(protected _version: V1, payload: DomainConfigResource, domainSid?: string) { + + this.domainSid = (payload.domain_sid); + this.configSid = (payload.config_sid); + this.fallbackUrl = (payload.fallback_url); + this.callbackUrl = (payload.callback_url); + this.continueOnFailure = (payload.continue_on_failure); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.disableHttps = (payload.disable_https); + + this._solution = { domainSid: domainSid, }; + } + + /** + * The unique string that we created to identify the Domain resource. + */ + domainSid: string; + /** + * The unique string that we created to identify the Domain config (prefix ZK). + */ + configSid: string; + /** + * Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + */ + fallbackUrl: string; + /** + * URL to receive click events to your webhook whenever the recipients click on the shortened links. + */ + callbackUrl: string; + /** + * Boolean field to set customer delivery preference when there is a failure in linkShortening service + */ + continueOnFailure: boolean; + /** + * Date this Domain Config was created. + */ + dateCreated: Date; + /** + * Date that this Domain Config was last updated. + */ + dateUpdated: Date; + url: string; + /** + * Customer\'s choice to send links with/without \"https://\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + */ + disableHttps: boolean; + + private get _proxy(): DomainConfigContext { + this._context = this._context || new DomainConfigContextImpl(this._version, this._solution.domainSid); + return this._context; + } + + /** + * Fetch a DomainConfigInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance + */ + fetch(callback?: (error: Error | null, item?: DomainConfigInstance) => any): Promise<DomainConfigInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DomainConfigInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainConfigInstance>) => any): Promise<ApiResponse<DomainConfigInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a DomainConfigInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance + */ + update(callback?: (error: Error | null, item?: DomainConfigInstance) => any): Promise<DomainConfigInstance>; + /** + * Update a DomainConfigInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance + */ + update(params: DomainConfigContextUpdateOptions, callback?: (error: Error | null, item?: DomainConfigInstance) => any): Promise<DomainConfigInstance>; + + update(params?: any, callback?: (error: Error | null, item?: DomainConfigInstance) => any): Promise<DomainConfigInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a DomainConfigInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainConfigInstance>) => any): Promise<ApiResponse<DomainConfigInstance>>; + /** + * Update a DomainConfigInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigInstance with HTTP metadata + */ + updateWithHttpInfo(params: DomainConfigContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<DomainConfigInstance>) => any): Promise<ApiResponse<DomainConfigInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<DomainConfigInstance>) => any): Promise<ApiResponse<DomainConfigInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domainSid: this.domainSid, + configSid: this.configSid, + fallbackUrl: this.fallbackUrl, + callbackUrl: this.callbackUrl, + continueOnFailure: this.continueOnFailure, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + disableHttps: this.disableHttps, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DomainConfigSolution { +} + +export interface DomainConfigListInstance { + _version: V1; + _solution: DomainConfigSolution; + _uri: string; + + (domainSid: string, ): DomainConfigContext; + get(domainSid: string, ): DomainConfigContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DomainConfigListInstance(version: V1): DomainConfigListInstance { + const instance = ((domainSid, ) => instance.get(domainSid, )) as DomainConfigListInstance; + + instance.get = function get(domainSid, ): DomainConfigContext { + return new DomainConfigContextImpl(version, domainSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/messaging/v1/domainConfigMessagingService.ts b/rest/messaging/v1/domainConfigMessagingService.ts new file mode 100644 index 000000000..3ab0c1120 --- /dev/null +++ b/rest/messaging/v1/domainConfigMessagingService.ts @@ -0,0 +1,287 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +export interface DomainConfigMessagingServiceContext { + + /** + * Fetch a DomainConfigMessagingServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigMessagingServiceInstance + */ + fetch(callback?: (error: Error | null, item?: DomainConfigMessagingServiceInstance) => any): Promise<DomainConfigMessagingServiceInstance> + + /** + * Fetch a DomainConfigMessagingServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigMessagingServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainConfigMessagingServiceInstance>) => any): Promise<ApiResponse<DomainConfigMessagingServiceInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DomainConfigMessagingServiceContextSolution { + "messagingServiceSid": string; +} + +export class DomainConfigMessagingServiceContextImpl implements DomainConfigMessagingServiceContext { + protected _solution: DomainConfigMessagingServiceContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, messagingServiceSid: string) { + if (!isValidPathParam(messagingServiceSid)) { + throw new Error('Parameter \'messagingServiceSid\' is not valid.'); + } + + this._solution = { messagingServiceSid, }; + this._uri = `/LinkShortening/MessagingService/${messagingServiceSid}/DomainConfig`; + } + + fetch(callback?: (error: Error | null, item?: DomainConfigMessagingServiceInstance) => any): Promise<DomainConfigMessagingServiceInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DomainConfigMessagingServiceInstance(operationVersion, payload, instance._solution.messagingServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainConfigMessagingServiceInstance>) => any): Promise<ApiResponse<DomainConfigMessagingServiceInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DomainConfigMessagingServiceResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DomainConfigMessagingServiceInstance> => ({ + ...response, + body: new DomainConfigMessagingServiceInstance(operationVersion, response.body, instance._solution.messagingServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DomainConfigMessagingServicePayload extends DomainConfigMessagingServiceResource {} + +interface DomainConfigMessagingServiceResource { + domain_sid: string; + config_sid: string; + messaging_service_sid: string; + fallback_url: string; + callback_url: string; + continue_on_failure: boolean; + date_created: Date; + date_updated: Date; + url: string; +} + +export class DomainConfigMessagingServiceInstance { + protected _solution: DomainConfigMessagingServiceContextSolution; + protected _context?: DomainConfigMessagingServiceContext; + + constructor(protected _version: V1, payload: DomainConfigMessagingServiceResource, messagingServiceSid?: string) { + + this.domainSid = (payload.domain_sid); + this.configSid = (payload.config_sid); + this.messagingServiceSid = (payload.messaging_service_sid); + this.fallbackUrl = (payload.fallback_url); + this.callbackUrl = (payload.callback_url); + this.continueOnFailure = (payload.continue_on_failure); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { messagingServiceSid: messagingServiceSid, }; + } + + /** + * The unique string that we created to identify the Domain resource. + */ + domainSid: string; + /** + * The unique string that we created to identify the Domain config (prefix ZK). + */ + configSid: string; + /** + * The unique string that identifies the messaging service + */ + messagingServiceSid: string; + /** + * Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + */ + fallbackUrl: string; + /** + * URL to receive click events to your webhook whenever the recipients click on the shortened links. + */ + callbackUrl: string; + /** + * Boolean field to set customer delivery preference when there is a failure in linkShortening service + */ + continueOnFailure: boolean; + /** + * Date this Domain Config was created. + */ + dateCreated: Date; + /** + * Date that this Domain Config was last updated. + */ + dateUpdated: Date; + url: string; + + private get _proxy(): DomainConfigMessagingServiceContext { + this._context = this._context || new DomainConfigMessagingServiceContextImpl(this._version, this._solution.messagingServiceSid); + return this._context; + } + + /** + * Fetch a DomainConfigMessagingServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigMessagingServiceInstance + */ + fetch(callback?: (error: Error | null, item?: DomainConfigMessagingServiceInstance) => any): Promise<DomainConfigMessagingServiceInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DomainConfigMessagingServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainConfigMessagingServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainConfigMessagingServiceInstance>) => any): Promise<ApiResponse<DomainConfigMessagingServiceInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domainSid: this.domainSid, + configSid: this.configSid, + messagingServiceSid: this.messagingServiceSid, + fallbackUrl: this.fallbackUrl, + callbackUrl: this.callbackUrl, + continueOnFailure: this.continueOnFailure, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DomainConfigMessagingServiceSolution { +} + +export interface DomainConfigMessagingServiceListInstance { + _version: V1; + _solution: DomainConfigMessagingServiceSolution; + _uri: string; + + (messagingServiceSid: string, ): DomainConfigMessagingServiceContext; + get(messagingServiceSid: string, ): DomainConfigMessagingServiceContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DomainConfigMessagingServiceListInstance(version: V1): DomainConfigMessagingServiceListInstance { + const instance = ((messagingServiceSid, ) => instance.get(messagingServiceSid, )) as DomainConfigMessagingServiceListInstance; + + instance.get = function get(messagingServiceSid, ): DomainConfigMessagingServiceContext { + return new DomainConfigMessagingServiceContextImpl(version, messagingServiceSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/messaging/v1/domainValidateDn.ts b/rest/messaging/v1/domainValidateDn.ts new file mode 100644 index 000000000..32c134e8f --- /dev/null +++ b/rest/messaging/v1/domainValidateDn.ts @@ -0,0 +1,246 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +export interface DomainValidateDnContext { + + /** + * Fetch a DomainValidateDnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainValidateDnInstance + */ + fetch(callback?: (error: Error | null, item?: DomainValidateDnInstance) => any): Promise<DomainValidateDnInstance> + + /** + * Fetch a DomainValidateDnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainValidateDnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainValidateDnInstance>) => any): Promise<ApiResponse<DomainValidateDnInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DomainValidateDnContextSolution { + "domainSid": string; +} + +export class DomainValidateDnContextImpl implements DomainValidateDnContext { + protected _solution: DomainValidateDnContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, domainSid: string) { + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + this._solution = { domainSid, }; + this._uri = `/LinkShortening/Domains/${domainSid}/ValidateDns`; + } + + fetch(callback?: (error: Error | null, item?: DomainValidateDnInstance) => any): Promise<DomainValidateDnInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DomainValidateDnInstance(operationVersion, payload, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainValidateDnInstance>) => any): Promise<ApiResponse<DomainValidateDnInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DomainValidateDnResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DomainValidateDnInstance> => ({ + ...response, + body: new DomainValidateDnInstance(operationVersion, response.body, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DomainValidateDnPayload extends DomainValidateDnResource {} + +interface DomainValidateDnResource { + domain_sid: string; + is_valid: boolean; + reason: string; + url: string; +} + +export class DomainValidateDnInstance { + protected _solution: DomainValidateDnContextSolution; + protected _context?: DomainValidateDnContext; + + constructor(protected _version: V1, payload: DomainValidateDnResource, domainSid?: string) { + + this.domainSid = (payload.domain_sid); + this.isValid = (payload.is_valid); + this.reason = (payload.reason); + this.url = (payload.url); + + this._solution = { domainSid: domainSid, }; + } + + /** + * The unique string that we created to identify the Domain resource. + */ + domainSid: string; + isValid: boolean; + reason: string; + url: string; + + private get _proxy(): DomainValidateDnContext { + this._context = this._context || new DomainValidateDnContextImpl(this._version, this._solution.domainSid); + return this._context; + } + + /** + * Fetch a DomainValidateDnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainValidateDnInstance + */ + fetch(callback?: (error: Error | null, item?: DomainValidateDnInstance) => any): Promise<DomainValidateDnInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DomainValidateDnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainValidateDnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainValidateDnInstance>) => any): Promise<ApiResponse<DomainValidateDnInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domainSid: this.domainSid, + isValid: this.isValid, + reason: this.reason, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DomainValidateDnSolution { +} + +export interface DomainValidateDnListInstance { + _version: V1; + _solution: DomainValidateDnSolution; + _uri: string; + + (domainSid: string, ): DomainValidateDnContext; + get(domainSid: string, ): DomainValidateDnContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DomainValidateDnListInstance(version: V1): DomainValidateDnListInstance { + const instance = ((domainSid, ) => instance.get(domainSid, )) as DomainValidateDnListInstance; + + instance.get = function get(domainSid, ): DomainValidateDnContext { + return new DomainValidateDnContextImpl(version, domainSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/messaging/v1/externalCampaign.ts b/rest/messaging/v1/externalCampaign.ts new file mode 100644 index 000000000..fee83f4a4 --- /dev/null +++ b/rest/messaging/v1/externalCampaign.ts @@ -0,0 +1,243 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a ExternalCampaignInstance + */ +export interface ExternalCampaignListInstanceCreateOptions { + /** ID of the preregistered campaign. */ + "campaignId": string; + /** The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. */ + "messagingServiceSid": string; + /** Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. */ + "cnpMigration"?: boolean; +} + + +export interface ExternalCampaignSolution { +} + +export interface ExternalCampaignListInstance { + _version: V1; + _solution: ExternalCampaignSolution; + _uri: string; + + + + /** + * Create a ExternalCampaignInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExternalCampaignInstance + */ + create(params: ExternalCampaignListInstanceCreateOptions, callback?: (error: Error | null, item?: ExternalCampaignInstance) => any): Promise<ExternalCampaignInstance>; + + /** + * Create a ExternalCampaignInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExternalCampaignInstance with HTTP metadata + */ + createWithHttpInfo(params: ExternalCampaignListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ExternalCampaignInstance>) => any): Promise<ApiResponse<ExternalCampaignInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExternalCampaignListInstance(version: V1): ExternalCampaignListInstance { + const instance = {} as ExternalCampaignListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services/PreregisteredUsa2p`; + + instance.create = function create(params: ExternalCampaignListInstanceCreateOptions, callback?: (error: Error | null, items: ExternalCampaignInstance) => any): Promise<ExternalCampaignInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["campaignId"] === null || params["campaignId"] === undefined) { + throw new Error('Required parameter "params[\'campaignId\']" missing.'); + } + + if (params["messagingServiceSid"] === null || params["messagingServiceSid"] === undefined) { + throw new Error('Required parameter "params[\'messagingServiceSid\']" missing.'); + } + + let data: any = {}; + + + + data["CampaignId"] = params["campaignId"]; + + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["cnpMigration"] !== undefined) + data["CnpMigration"] = serialize.bool(params["cnpMigration"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ExternalCampaignInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ExternalCampaignListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ExternalCampaignInstance>) => any): Promise<ApiResponse<ExternalCampaignInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["campaignId"] === null || params["campaignId"] === undefined) { + throw new Error('Required parameter "params[\'campaignId\']" missing.'); + } + + if (params["messagingServiceSid"] === null || params["messagingServiceSid"] === undefined) { + throw new Error('Required parameter "params[\'messagingServiceSid\']" missing.'); + } + + let data: any = {}; + + + + data["CampaignId"] = params["campaignId"]; + + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["cnpMigration"] !== undefined) + data["CnpMigration"] = serialize.bool(params["cnpMigration"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ExternalCampaignResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ExternalCampaignInstance> => ({ + ...response, + body: new ExternalCampaignInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ExternalCampaignPayload extends ExternalCampaignResource {} + +interface ExternalCampaignResource { + sid: string; + account_sid: string; + campaign_id: string; + messaging_service_sid: string; + date_created: Date; +} + +export class ExternalCampaignInstance { + + constructor(protected _version: V1, payload: ExternalCampaignResource) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.campaignId = (payload.campaign_id); + this.messagingServiceSid = (payload.messaging_service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + + } + + /** + * The unique string that identifies a US A2P Compliance resource `QE2c6890da8086d771620e9b13fadeba0b`. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Campaign belongs to. + */ + accountSid: string; + /** + * ID of the preregistered campaign. + */ + campaignId: string; + /** + * The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + */ + messagingServiceSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + campaignId: this.campaignId, + messagingServiceSid: this.messagingServiceSid, + dateCreated: this.dateCreated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/messaging/v1/linkshorteningMessagingService.ts b/rest/messaging/v1/linkshorteningMessagingService.ts new file mode 100644 index 000000000..8a785cd10 --- /dev/null +++ b/rest/messaging/v1/linkshorteningMessagingService.ts @@ -0,0 +1,328 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface LinkshorteningMessagingServiceContext { + + /** + * Create a LinkshorteningMessagingServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LinkshorteningMessagingServiceInstance + */ + create(callback?: (error: Error | null, item?: LinkshorteningMessagingServiceInstance) => any): Promise<LinkshorteningMessagingServiceInstance> + + /** + * Create a LinkshorteningMessagingServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LinkshorteningMessagingServiceInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LinkshorteningMessagingServiceInstance>) => any): Promise<ApiResponse<LinkshorteningMessagingServiceInstance>> + + /** + * Remove a LinkshorteningMessagingServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a LinkshorteningMessagingServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface LinkshorteningMessagingServiceContextSolution { + "domainSid": string; + "messagingServiceSid": string; +} + +export class LinkshorteningMessagingServiceContextImpl implements LinkshorteningMessagingServiceContext { + protected _solution: LinkshorteningMessagingServiceContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, domainSid: string, messagingServiceSid: string) { + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + if (!isValidPathParam(messagingServiceSid)) { + throw new Error('Parameter \'messagingServiceSid\' is not valid.'); + } + + this._solution = { domainSid, messagingServiceSid, }; + this._uri = `/LinkShortening/Domains/${domainSid}/MessagingServices/${messagingServiceSid}`; + } + + create(callback?: (error: Error | null, item?: LinkshorteningMessagingServiceInstance) => any): Promise<LinkshorteningMessagingServiceInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new LinkshorteningMessagingServiceInstance(operationVersion, payload, instance._solution.domainSid, instance._solution.messagingServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LinkshorteningMessagingServiceInstance>) => any): Promise<ApiResponse<LinkshorteningMessagingServiceInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<LinkshorteningMessagingServiceResource>({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse<LinkshorteningMessagingServiceInstance> => ({ + ...response, + body: new LinkshorteningMessagingServiceInstance(operationVersion, response.body, instance._solution.domainSid, instance._solution.messagingServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface LinkshorteningMessagingServicePayload extends LinkshorteningMessagingServiceResource {} + +interface LinkshorteningMessagingServiceResource { + domain_sid: string; + messaging_service_sid: string; + url: string; +} + +export class LinkshorteningMessagingServiceInstance { + protected _solution: LinkshorteningMessagingServiceContextSolution; + protected _context?: LinkshorteningMessagingServiceContext; + + constructor(protected _version: V1, payload: LinkshorteningMessagingServiceResource, domainSid?: string, messagingServiceSid?: string) { + + this.domainSid = (payload.domain_sid); + this.messagingServiceSid = (payload.messaging_service_sid); + this.url = (payload.url); + + this._solution = { domainSid: domainSid, messagingServiceSid: messagingServiceSid, }; + } + + /** + * The unique string identifies the domain resource + */ + domainSid: string; + /** + * The unique string that identifies the messaging service + */ + messagingServiceSid: string; + url: string; + + private get _proxy(): LinkshorteningMessagingServiceContext { + this._context = this._context || new LinkshorteningMessagingServiceContextImpl(this._version, this._solution.domainSid, this._solution.messagingServiceSid); + return this._context; + } + + /** + * Create a LinkshorteningMessagingServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LinkshorteningMessagingServiceInstance + */ + create(callback?: (error: Error | null, item?: LinkshorteningMessagingServiceInstance) => any): Promise<LinkshorteningMessagingServiceInstance> + + { + return this._proxy.create(callback); + } + + /** + * Create a LinkshorteningMessagingServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LinkshorteningMessagingServiceInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LinkshorteningMessagingServiceInstance>) => any): Promise<ApiResponse<LinkshorteningMessagingServiceInstance>> + + { + return this._proxy.createWithHttpInfo(callback); + } + + /** + * Remove a LinkshorteningMessagingServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a LinkshorteningMessagingServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domainSid: this.domainSid, + messagingServiceSid: this.messagingServiceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface LinkshorteningMessagingServiceSolution { +} + +export interface LinkshorteningMessagingServiceListInstance { + _version: V1; + _solution: LinkshorteningMessagingServiceSolution; + _uri: string; + + (domainSid: string, messagingServiceSid: string, ): LinkshorteningMessagingServiceContext; + get(domainSid: string, messagingServiceSid: string, ): LinkshorteningMessagingServiceContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function LinkshorteningMessagingServiceListInstance(version: V1): LinkshorteningMessagingServiceListInstance { + const instance = ((domainSid, messagingServiceSid, ) => instance.get(domainSid, messagingServiceSid, )) as LinkshorteningMessagingServiceListInstance; + + instance.get = function get(domainSid, messagingServiceSid, ): LinkshorteningMessagingServiceContext { + return new LinkshorteningMessagingServiceContextImpl(version, domainSid, messagingServiceSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/messaging/v1/linkshorteningMessagingServiceDomainAssociation.ts b/rest/messaging/v1/linkshorteningMessagingServiceDomainAssociation.ts new file mode 100644 index 000000000..f8b3de381 --- /dev/null +++ b/rest/messaging/v1/linkshorteningMessagingServiceDomainAssociation.ts @@ -0,0 +1,245 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +export interface LinkshorteningMessagingServiceDomainAssociationContext { + + /** + * Fetch a LinkshorteningMessagingServiceDomainAssociationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LinkshorteningMessagingServiceDomainAssociationInstance + */ + fetch(callback?: (error: Error | null, item?: LinkshorteningMessagingServiceDomainAssociationInstance) => any): Promise<LinkshorteningMessagingServiceDomainAssociationInstance> + + /** + * Fetch a LinkshorteningMessagingServiceDomainAssociationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LinkshorteningMessagingServiceDomainAssociationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LinkshorteningMessagingServiceDomainAssociationInstance>) => any): Promise<ApiResponse<LinkshorteningMessagingServiceDomainAssociationInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface LinkshorteningMessagingServiceDomainAssociationContextSolution { + "messagingServiceSid": string; +} + +export class LinkshorteningMessagingServiceDomainAssociationContextImpl implements LinkshorteningMessagingServiceDomainAssociationContext { + protected _solution: LinkshorteningMessagingServiceDomainAssociationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, messagingServiceSid: string) { + if (!isValidPathParam(messagingServiceSid)) { + throw new Error('Parameter \'messagingServiceSid\' is not valid.'); + } + + this._solution = { messagingServiceSid, }; + this._uri = `/LinkShortening/MessagingServices/${messagingServiceSid}/Domain`; + } + + fetch(callback?: (error: Error | null, item?: LinkshorteningMessagingServiceDomainAssociationInstance) => any): Promise<LinkshorteningMessagingServiceDomainAssociationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new LinkshorteningMessagingServiceDomainAssociationInstance(operationVersion, payload, instance._solution.messagingServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LinkshorteningMessagingServiceDomainAssociationInstance>) => any): Promise<ApiResponse<LinkshorteningMessagingServiceDomainAssociationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<LinkshorteningMessagingServiceDomainAssociationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<LinkshorteningMessagingServiceDomainAssociationInstance> => ({ + ...response, + body: new LinkshorteningMessagingServiceDomainAssociationInstance(operationVersion, response.body, instance._solution.messagingServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface LinkshorteningMessagingServiceDomainAssociationPayload extends LinkshorteningMessagingServiceDomainAssociationResource {} + +interface LinkshorteningMessagingServiceDomainAssociationResource { + domain_sid: string; + messaging_service_sid: string; + url: string; +} + +export class LinkshorteningMessagingServiceDomainAssociationInstance { + protected _solution: LinkshorteningMessagingServiceDomainAssociationContextSolution; + protected _context?: LinkshorteningMessagingServiceDomainAssociationContext; + + constructor(protected _version: V1, payload: LinkshorteningMessagingServiceDomainAssociationResource, messagingServiceSid?: string) { + + this.domainSid = (payload.domain_sid); + this.messagingServiceSid = (payload.messaging_service_sid); + this.url = (payload.url); + + this._solution = { messagingServiceSid: messagingServiceSid, }; + } + + /** + * The unique string that we created to identify the Domain resource. + */ + domainSid: string; + /** + * The unique string that identifies the messaging service + */ + messagingServiceSid: string; + url: string; + + private get _proxy(): LinkshorteningMessagingServiceDomainAssociationContext { + this._context = this._context || new LinkshorteningMessagingServiceDomainAssociationContextImpl(this._version, this._solution.messagingServiceSid); + return this._context; + } + + /** + * Fetch a LinkshorteningMessagingServiceDomainAssociationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LinkshorteningMessagingServiceDomainAssociationInstance + */ + fetch(callback?: (error: Error | null, item?: LinkshorteningMessagingServiceDomainAssociationInstance) => any): Promise<LinkshorteningMessagingServiceDomainAssociationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a LinkshorteningMessagingServiceDomainAssociationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LinkshorteningMessagingServiceDomainAssociationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LinkshorteningMessagingServiceDomainAssociationInstance>) => any): Promise<ApiResponse<LinkshorteningMessagingServiceDomainAssociationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domainSid: this.domainSid, + messagingServiceSid: this.messagingServiceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface LinkshorteningMessagingServiceDomainAssociationSolution { +} + +export interface LinkshorteningMessagingServiceDomainAssociationListInstance { + _version: V1; + _solution: LinkshorteningMessagingServiceDomainAssociationSolution; + _uri: string; + + (messagingServiceSid: string, ): LinkshorteningMessagingServiceDomainAssociationContext; + get(messagingServiceSid: string, ): LinkshorteningMessagingServiceDomainAssociationContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function LinkshorteningMessagingServiceDomainAssociationListInstance(version: V1): LinkshorteningMessagingServiceDomainAssociationListInstance { + const instance = ((messagingServiceSid, ) => instance.get(messagingServiceSid, )) as LinkshorteningMessagingServiceDomainAssociationListInstance; + + instance.get = function get(messagingServiceSid, ): LinkshorteningMessagingServiceDomainAssociationContext { + return new LinkshorteningMessagingServiceDomainAssociationContextImpl(version, messagingServiceSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/messaging/v1/requestManagedCert.ts b/rest/messaging/v1/requestManagedCert.ts new file mode 100644 index 000000000..d4958fdba --- /dev/null +++ b/rest/messaging/v1/requestManagedCert.ts @@ -0,0 +1,287 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +export interface RequestManagedCertContext { + + /** + * Update a RequestManagedCertInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RequestManagedCertInstance + */ + update(callback?: (error: Error | null, item?: RequestManagedCertInstance) => any): Promise<RequestManagedCertInstance> + + /** + * Update a RequestManagedCertInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RequestManagedCertInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RequestManagedCertInstance>) => any): Promise<ApiResponse<RequestManagedCertInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RequestManagedCertContextSolution { + "domainSid": string; +} + +export class RequestManagedCertContextImpl implements RequestManagedCertContext { + protected _solution: RequestManagedCertContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, domainSid: string) { + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + this._solution = { domainSid, }; + this._uri = `/LinkShortening/Domains/${domainSid}/RequestManagedCert`; + } + + update(callback?: (error: Error | null, item?: RequestManagedCertInstance) => any): Promise<RequestManagedCertInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new RequestManagedCertInstance(operationVersion, payload, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RequestManagedCertInstance>) => any): Promise<ApiResponse<RequestManagedCertInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<RequestManagedCertResource>({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse<RequestManagedCertInstance> => ({ + ...response, + body: new RequestManagedCertInstance(operationVersion, response.body, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RequestManagedCertPayload extends RequestManagedCertResource {} + +interface RequestManagedCertResource { + domain_sid: string; + date_updated: Date; + date_created: Date; + date_expires: Date; + domain_name: string; + certificate_sid: string; + url: string; + managed: boolean; + requesting: boolean; +} + +export class RequestManagedCertInstance { + protected _solution: RequestManagedCertContextSolution; + protected _context?: RequestManagedCertContext; + + constructor(protected _version: V1, payload: RequestManagedCertResource, domainSid?: string) { + + this.domainSid = (payload.domain_sid); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateExpires = deserialize.iso8601DateTime(payload.date_expires); + this.domainName = (payload.domain_name); + this.certificateSid = (payload.certificate_sid); + this.url = (payload.url); + this.managed = (payload.managed); + this.requesting = (payload.requesting); + + this._solution = { domainSid: domainSid, }; + } + + /** + * The unique string that we created to identify the Domain resource. + */ + domainSid: string; + /** + * Date that this Domain was last updated. + */ + dateUpdated: Date; + /** + * Date that this Domain was registered to the Twilio platform to create a new Domain object. + */ + dateCreated: Date; + /** + * Date that the private certificate associated with this domain expires. This is the expiration date of your existing cert. + */ + dateExpires: Date; + /** + * Full url path for this domain. + */ + domainName: string; + /** + * The unique string that we created to identify this Certificate resource. + */ + certificateSid: string; + url: string; + /** + * A boolean flag indicating if the certificate is managed by Twilio. + */ + managed: boolean; + /** + * A boolean flag indicating if a managed certificate needs to be fulfilled by Twilio. + */ + requesting: boolean; + + private get _proxy(): RequestManagedCertContext { + this._context = this._context || new RequestManagedCertContextImpl(this._version, this._solution.domainSid); + return this._context; + } + + /** + * Update a RequestManagedCertInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RequestManagedCertInstance + */ + update(callback?: (error: Error | null, item?: RequestManagedCertInstance) => any): Promise<RequestManagedCertInstance> + + { + return this._proxy.update(callback); + } + + /** + * Update a RequestManagedCertInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RequestManagedCertInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RequestManagedCertInstance>) => any): Promise<ApiResponse<RequestManagedCertInstance>> + + { + return this._proxy.updateWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domainSid: this.domainSid, + dateUpdated: this.dateUpdated, + dateCreated: this.dateCreated, + dateExpires: this.dateExpires, + domainName: this.domainName, + certificateSid: this.certificateSid, + url: this.url, + managed: this.managed, + requesting: this.requesting, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RequestManagedCertSolution { +} + +export interface RequestManagedCertListInstance { + _version: V1; + _solution: RequestManagedCertSolution; + _uri: string; + + (domainSid: string, ): RequestManagedCertContext; + get(domainSid: string, ): RequestManagedCertContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RequestManagedCertListInstance(version: V1): RequestManagedCertListInstance { + const instance = ((domainSid, ) => instance.get(domainSid, )) as RequestManagedCertListInstance; + + instance.get = function get(domainSid, ): RequestManagedCertContext { + return new RequestManagedCertContextImpl(version, domainSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/messaging/v1/service.ts b/rest/messaging/v1/service.ts new file mode 100644 index 000000000..69c8ae7b1 --- /dev/null +++ b/rest/messaging/v1/service.ts @@ -0,0 +1,1295 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { AlphaSenderListInstance } from "./service/alphaSender"; +import { ChannelSenderListInstance } from "./service/channelSender"; +import { DestinationAlphaSenderListInstance } from "./service/destinationAlphaSender"; +import { PhoneNumberListInstance } from "./service/phoneNumber"; +import { ShortCodeListInstance } from "./service/shortCode"; +import { UsAppToPersonListInstance } from "./service/usAppToPerson"; +import { UsAppToPersonUsecaseListInstance } from "./service/usAppToPersonUsecase"; + + +/** + * Reserved. + */ +export type ServiceScanMessageContent = 'inherit'|'enable'|'disable'; + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. */ + "inboundRequestUrl"?: string; + /** The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. */ + "inboundMethod"?: string; + /** The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. */ + "fallbackUrl"?: string; + /** The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. */ + "fallbackMethod"?: string; + /** The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. */ + "statusCallback"?: string; + /** Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. */ + "stickySender"?: boolean; + /** Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. */ + "mmsConverter"?: boolean; + /** Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. */ + "smartEncoding"?: boolean; + /** */ + "scanMessageContent"?: ServiceScanMessageContent; + /** [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. */ + "fallbackToLongCode"?: boolean; + /** Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. */ + "areaCodeGeomatch"?: boolean; + /** How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. */ + "validityPeriod"?: number; + /** Reserved. */ + "synchronousValidation"?: boolean; + /** A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. */ + "usecase"?: string; + /** A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. */ + "useInboundWebhookOnNumber"?: boolean; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName": string; + /** The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. */ + "inboundRequestUrl"?: string; + /** The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. */ + "inboundMethod"?: string; + /** The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. */ + "fallbackUrl"?: string; + /** The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. */ + "fallbackMethod"?: string; + /** The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. */ + "statusCallback"?: string; + /** Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. */ + "stickySender"?: boolean; + /** Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. */ + "mmsConverter"?: boolean; + /** Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. */ + "smartEncoding"?: boolean; + /** */ + "scanMessageContent"?: ServiceScanMessageContent; + /** [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. */ + "fallbackToLongCode"?: boolean; + /** Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. */ + "areaCodeGeomatch"?: boolean; + /** How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. */ + "validityPeriod"?: number; + /** Reserved. */ + "synchronousValidation"?: boolean; + /** A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. */ + "usecase"?: string; + /** A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. */ + "useInboundWebhookOnNumber"?: boolean; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + alphaSenders: AlphaSenderListInstance; + channelSenders: ChannelSenderListInstance; + destinationAlphaSenders: DestinationAlphaSenderListInstance; + phoneNumbers: PhoneNumberListInstance; + shortCodes: ShortCodeListInstance; + usAppToPerson: UsAppToPersonListInstance; + usAppToPersonUsecases: UsAppToPersonUsecaseListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _alphaSenders?: AlphaSenderListInstance; + protected _channelSenders?: ChannelSenderListInstance; + protected _destinationAlphaSenders?: DestinationAlphaSenderListInstance; + protected _phoneNumbers?: PhoneNumberListInstance; + protected _shortCodes?: ShortCodeListInstance; + protected _usAppToPerson?: UsAppToPersonListInstance; + protected _usAppToPersonUsecases?: UsAppToPersonUsecaseListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get alphaSenders(): AlphaSenderListInstance { + this._alphaSenders = this._alphaSenders || AlphaSenderListInstance(this._version, this._solution.sid); + return this._alphaSenders; + } + + get channelSenders(): ChannelSenderListInstance { + this._channelSenders = this._channelSenders || ChannelSenderListInstance(this._version, this._solution.sid); + return this._channelSenders; + } + + get destinationAlphaSenders(): DestinationAlphaSenderListInstance { + this._destinationAlphaSenders = this._destinationAlphaSenders || DestinationAlphaSenderListInstance(this._version, this._solution.sid); + return this._destinationAlphaSenders; + } + + get phoneNumbers(): PhoneNumberListInstance { + this._phoneNumbers = this._phoneNumbers || PhoneNumberListInstance(this._version, this._solution.sid); + return this._phoneNumbers; + } + + get shortCodes(): ShortCodeListInstance { + this._shortCodes = this._shortCodes || ShortCodeListInstance(this._version, this._solution.sid); + return this._shortCodes; + } + + get usAppToPerson(): UsAppToPersonListInstance { + this._usAppToPerson = this._usAppToPerson || UsAppToPersonListInstance(this._version, this._solution.sid); + return this._usAppToPerson; + } + + get usAppToPersonUsecases(): UsAppToPersonUsecaseListInstance { + this._usAppToPersonUsecases = this._usAppToPersonUsecases || UsAppToPersonUsecaseListInstance(this._version, this._solution.sid); + return this._usAppToPersonUsecases; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["inboundRequestUrl"] !== undefined) + data["InboundRequestUrl"] = params["inboundRequestUrl"]; + if (params["inboundMethod"] !== undefined) + data["InboundMethod"] = params["inboundMethod"]; + if (params["fallbackUrl"] !== undefined) + data["FallbackUrl"] = params["fallbackUrl"]; + if (params["fallbackMethod"] !== undefined) + data["FallbackMethod"] = params["fallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["stickySender"] !== undefined) + data["StickySender"] = serialize.bool(params["stickySender"]); + if (params["mmsConverter"] !== undefined) + data["MmsConverter"] = serialize.bool(params["mmsConverter"]); + if (params["smartEncoding"] !== undefined) + data["SmartEncoding"] = serialize.bool(params["smartEncoding"]); + if (params["scanMessageContent"] !== undefined) + data["ScanMessageContent"] = params["scanMessageContent"]; + if (params["fallbackToLongCode"] !== undefined) + data["FallbackToLongCode"] = serialize.bool(params["fallbackToLongCode"]); + if (params["areaCodeGeomatch"] !== undefined) + data["AreaCodeGeomatch"] = serialize.bool(params["areaCodeGeomatch"]); + if (params["validityPeriod"] !== undefined) + data["ValidityPeriod"] = params["validityPeriod"]; + if (params["synchronousValidation"] !== undefined) + data["SynchronousValidation"] = serialize.bool(params["synchronousValidation"]); + if (params["usecase"] !== undefined) + data["Usecase"] = params["usecase"]; + if (params["useInboundWebhookOnNumber"] !== undefined) + data["UseInboundWebhookOnNumber"] = serialize.bool(params["useInboundWebhookOnNumber"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ServiceInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["inboundRequestUrl"] !== undefined) + data["InboundRequestUrl"] = params["inboundRequestUrl"]; + if (params["inboundMethod"] !== undefined) + data["InboundMethod"] = params["inboundMethod"]; + if (params["fallbackUrl"] !== undefined) + data["FallbackUrl"] = params["fallbackUrl"]; + if (params["fallbackMethod"] !== undefined) + data["FallbackMethod"] = params["fallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["stickySender"] !== undefined) + data["StickySender"] = serialize.bool(params["stickySender"]); + if (params["mmsConverter"] !== undefined) + data["MmsConverter"] = serialize.bool(params["mmsConverter"]); + if (params["smartEncoding"] !== undefined) + data["SmartEncoding"] = serialize.bool(params["smartEncoding"]); + if (params["scanMessageContent"] !== undefined) + data["ScanMessageContent"] = params["scanMessageContent"]; + if (params["fallbackToLongCode"] !== undefined) + data["FallbackToLongCode"] = serialize.bool(params["fallbackToLongCode"]); + if (params["areaCodeGeomatch"] !== undefined) + data["AreaCodeGeomatch"] = serialize.bool(params["areaCodeGeomatch"]); + if (params["validityPeriod"] !== undefined) + data["ValidityPeriod"] = params["validityPeriod"]; + if (params["synchronousValidation"] !== undefined) + data["SynchronousValidation"] = serialize.bool(params["synchronousValidation"]); + if (params["usecase"] !== undefined) + data["Usecase"] = params["usecase"]; + if (params["useInboundWebhookOnNumber"] !== undefined) + data["UseInboundWebhookOnNumber"] = serialize.bool(params["useInboundWebhookOnNumber"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + sid: string; + account_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + inbound_request_url: string; + inbound_method: string; + fallback_url: string; + fallback_method: string; + status_callback: string; + sticky_sender: boolean; + mms_converter: boolean; + smart_encoding: boolean; + scan_message_content: ServiceScanMessageContent; + fallback_to_long_code: boolean; + area_code_geomatch: boolean; + synchronous_validation: boolean; + validity_period: number; + url: string; + links: Record<string, string>; + usecase: string; + us_app_to_person_registered: boolean; + use_inbound_webhook_on_number: boolean; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V1, payload: ServiceResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.inboundRequestUrl = (payload.inbound_request_url); + this.inboundMethod = (payload.inbound_method); + this.fallbackUrl = (payload.fallback_url); + this.fallbackMethod = (payload.fallback_method); + this.statusCallback = (payload.status_callback); + this.stickySender = (payload.sticky_sender); + this.mmsConverter = (payload.mms_converter); + this.smartEncoding = (payload.smart_encoding); + this.scanMessageContent = payload.scan_message_content; + this.fallbackToLongCode = (payload.fallback_to_long_code); + this.areaCodeGeomatch = (payload.area_code_geomatch); + this.synchronousValidation = (payload.synchronous_validation); + this.validityPeriod = deserialize.integer(payload.validity_period); + this.url = (payload.url); + this.links = (payload.links); + this.usecase = (payload.usecase); + this.usAppToPersonRegistered = (payload.us_app_to_person_registered); + this.useInboundWebhookOnNumber = (payload.use_inbound_webhook_on_number); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Service resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + */ + inboundRequestUrl: string; + /** + * The HTTP method we use to call `inbound_request_url`. Can be `GET` or `POST`. + */ + inboundMethod: string; + /** + * The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + */ + fallbackUrl: string; + /** + * The HTTP method we use to call `fallback_url`. Can be: `GET` or `POST`. + */ + fallbackMethod: string; + /** + * The URL we call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + */ + statusCallback: string; + /** + * Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + */ + stickySender: boolean; + /** + * Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + */ + mmsConverter: boolean; + /** + * Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + */ + smartEncoding: boolean; + scanMessageContent: ServiceScanMessageContent; + /** + * [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + */ + fallbackToLongCode: boolean; + /** + * Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + */ + areaCodeGeomatch: boolean; + /** + * Reserved. + */ + synchronousValidation: boolean; + /** + * How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + */ + validityPeriod: number; + /** + * The absolute URL of the Service resource. + */ + url: string; + /** + * The absolute URLs of related resources. + */ + links: Record<string, string>; + /** + * A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + */ + usecase: string; + /** + * Whether US A2P campaign is registered for this Service. + */ + usAppToPersonRegistered: boolean; + /** + * A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + */ + useInboundWebhookOnNumber: boolean; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the alphaSenders. + */ + alphaSenders(): AlphaSenderListInstance { + return this._proxy.alphaSenders; + } + + /** + * Access the channelSenders. + */ + channelSenders(): ChannelSenderListInstance { + return this._proxy.channelSenders; + } + + /** + * Access the destinationAlphaSenders. + */ + destinationAlphaSenders(): DestinationAlphaSenderListInstance { + return this._proxy.destinationAlphaSenders; + } + + /** + * Access the phoneNumbers. + */ + phoneNumbers(): PhoneNumberListInstance { + return this._proxy.phoneNumbers; + } + + /** + * Access the shortCodes. + */ + shortCodes(): ShortCodeListInstance { + return this._proxy.shortCodes; + } + + /** + * Access the usAppToPerson. + */ + usAppToPerson(): UsAppToPersonListInstance { + return this._proxy.usAppToPerson; + } + + /** + * Access the usAppToPersonUsecases. + */ + usAppToPersonUsecases(): UsAppToPersonUsecaseListInstance { + return this._proxy.usAppToPersonUsecases; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + inboundRequestUrl: this.inboundRequestUrl, + inboundMethod: this.inboundMethod, + fallbackUrl: this.fallbackUrl, + fallbackMethod: this.fallbackMethod, + statusCallback: this.statusCallback, + stickySender: this.stickySender, + mmsConverter: this.mmsConverter, + smartEncoding: this.smartEncoding, + scanMessageContent: this.scanMessageContent, + fallbackToLongCode: this.fallbackToLongCode, + areaCodeGeomatch: this.areaCodeGeomatch, + synchronousValidation: this.synchronousValidation, + validityPeriod: this.validityPeriod, + url: this.url, + links: this.links, + usecase: this.usecase, + usAppToPersonRegistered: this.usAppToPersonRegistered, + useInboundWebhookOnNumber: this.useInboundWebhookOnNumber, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V1; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V1): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ServiceInstance) => any): Promise<ServiceInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["inboundRequestUrl"] !== undefined) + data["InboundRequestUrl"] = params["inboundRequestUrl"]; + if (params["inboundMethod"] !== undefined) + data["InboundMethod"] = params["inboundMethod"]; + if (params["fallbackUrl"] !== undefined) + data["FallbackUrl"] = params["fallbackUrl"]; + if (params["fallbackMethod"] !== undefined) + data["FallbackMethod"] = params["fallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["stickySender"] !== undefined) + data["StickySender"] = serialize.bool(params["stickySender"]); + if (params["mmsConverter"] !== undefined) + data["MmsConverter"] = serialize.bool(params["mmsConverter"]); + if (params["smartEncoding"] !== undefined) + data["SmartEncoding"] = serialize.bool(params["smartEncoding"]); + if (params["scanMessageContent"] !== undefined) + data["ScanMessageContent"] = params["scanMessageContent"]; + if (params["fallbackToLongCode"] !== undefined) + data["FallbackToLongCode"] = serialize.bool(params["fallbackToLongCode"]); + if (params["areaCodeGeomatch"] !== undefined) + data["AreaCodeGeomatch"] = serialize.bool(params["areaCodeGeomatch"]); + if (params["validityPeriod"] !== undefined) + data["ValidityPeriod"] = params["validityPeriod"]; + if (params["synchronousValidation"] !== undefined) + data["SynchronousValidation"] = serialize.bool(params["synchronousValidation"]); + if (params["usecase"] !== undefined) + data["Usecase"] = params["usecase"]; + if (params["useInboundWebhookOnNumber"] !== undefined) + data["UseInboundWebhookOnNumber"] = serialize.bool(params["useInboundWebhookOnNumber"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["inboundRequestUrl"] !== undefined) + data["InboundRequestUrl"] = params["inboundRequestUrl"]; + if (params["inboundMethod"] !== undefined) + data["InboundMethod"] = params["inboundMethod"]; + if (params["fallbackUrl"] !== undefined) + data["FallbackUrl"] = params["fallbackUrl"]; + if (params["fallbackMethod"] !== undefined) + data["FallbackMethod"] = params["fallbackMethod"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["stickySender"] !== undefined) + data["StickySender"] = serialize.bool(params["stickySender"]); + if (params["mmsConverter"] !== undefined) + data["MmsConverter"] = serialize.bool(params["mmsConverter"]); + if (params["smartEncoding"] !== undefined) + data["SmartEncoding"] = serialize.bool(params["smartEncoding"]); + if (params["scanMessageContent"] !== undefined) + data["ScanMessageContent"] = params["scanMessageContent"]; + if (params["fallbackToLongCode"] !== undefined) + data["FallbackToLongCode"] = serialize.bool(params["fallbackToLongCode"]); + if (params["areaCodeGeomatch"] !== undefined) + data["AreaCodeGeomatch"] = serialize.bool(params["areaCodeGeomatch"]); + if (params["validityPeriod"] !== undefined) + data["ValidityPeriod"] = params["validityPeriod"]; + if (params["synchronousValidation"] !== undefined) + data["SynchronousValidation"] = serialize.bool(params["synchronousValidation"]); + if (params["usecase"] !== undefined) + data["Usecase"] = params["usecase"]; + if (params["useInboundWebhookOnNumber"] !== undefined) + data["UseInboundWebhookOnNumber"] = serialize.bool(params["useInboundWebhookOnNumber"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse<ServicePage>) => any), callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page<V1, ServicePayload, ServiceResource, ServiceInstance> { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v1/service/alphaSender.ts b/rest/messaging/v1/service/alphaSender.ts new file mode 100644 index 000000000..517d67ff2 --- /dev/null +++ b/rest/messaging/v1/service/alphaSender.ts @@ -0,0 +1,753 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a AlphaSenderInstance + */ +export interface AlphaSenderListInstanceCreateOptions { + /** The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. */ + "alphaSender": string; +} + +/** + * Options to pass to each + */ +export interface AlphaSenderListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AlphaSenderInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AlphaSenderListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AlphaSenderListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AlphaSenderContext { + + /** + * Remove a AlphaSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a AlphaSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a AlphaSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlphaSenderInstance + */ + fetch(callback?: (error: Error | null, item?: AlphaSenderInstance) => any): Promise<AlphaSenderInstance> + + /** + * Fetch a AlphaSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlphaSenderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AlphaSenderInstance>) => any): Promise<ApiResponse<AlphaSenderInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AlphaSenderContextSolution { + "serviceSid": string; + "sid": string; +} + +export class AlphaSenderContextImpl implements AlphaSenderContext { + protected _solution: AlphaSenderContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/AlphaSenders/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AlphaSenderInstance) => any): Promise<AlphaSenderInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AlphaSenderInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AlphaSenderInstance>) => any): Promise<ApiResponse<AlphaSenderInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AlphaSenderResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AlphaSenderInstance> => ({ + ...response, + body: new AlphaSenderInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AlphaSenderPayload extends TwilioResponsePayload { + alpha_senders: AlphaSenderResource[]; +} + +interface AlphaSenderResource { + sid: string; + account_sid: string; + service_sid: string; + date_created: Date; + date_updated: Date; + alpha_sender: string; + capabilities: Array<string>; + url: string; +} + +export class AlphaSenderInstance { + protected _solution: AlphaSenderContextSolution; + protected _context?: AlphaSenderContext; + + constructor(protected _version: V1, payload: AlphaSenderResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.alphaSender = (payload.alpha_sender); + this.capabilities = (payload.capabilities); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the AlphaSender resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AlphaSender resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + */ + serviceSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The Alphanumeric Sender ID string. + */ + alphaSender: string; + /** + * An array of values that describe whether the number can receive calls or messages. Can be: `SMS`. + */ + capabilities: Array<string>; + /** + * The absolute URL of the AlphaSender resource. + */ + url: string; + + private get _proxy(): AlphaSenderContext { + this._context = this._context || new AlphaSenderContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a AlphaSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AlphaSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AlphaSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlphaSenderInstance + */ + fetch(callback?: (error: Error | null, item?: AlphaSenderInstance) => any): Promise<AlphaSenderInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AlphaSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlphaSenderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AlphaSenderInstance>) => any): Promise<ApiResponse<AlphaSenderInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + alphaSender: this.alphaSender, + capabilities: this.capabilities, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AlphaSenderSolution { + serviceSid: string; +} + +export interface AlphaSenderListInstance { + _version: V1; + _solution: AlphaSenderSolution; + _uri: string; + + (sid: string, ): AlphaSenderContext; + get(sid: string, ): AlphaSenderContext; + + + + + + + /** + * Create a AlphaSenderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlphaSenderInstance + */ + create(params: AlphaSenderListInstanceCreateOptions, callback?: (error: Error | null, item?: AlphaSenderInstance) => any): Promise<AlphaSenderInstance>; + + /** + * Create a AlphaSenderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlphaSenderInstance with HTTP metadata + */ + createWithHttpInfo(params: AlphaSenderListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<AlphaSenderInstance>) => any): Promise<ApiResponse<AlphaSenderInstance>>; + + + + + /** + * Streams AlphaSenderInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlphaSenderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AlphaSenderInstance, done: (err?: Error) => void) => void): void; + each(params: AlphaSenderListInstanceEachOptions, callback?: (item: AlphaSenderInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AlphaSenderInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlphaSenderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AlphaSenderInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AlphaSenderListInstanceEachOptions, callback?: (item: AlphaSenderInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AlphaSenderInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AlphaSenderPage) => any): Promise<AlphaSenderPage>; + /** + * Retrieve a single target page of AlphaSenderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AlphaSenderPage>) => any): Promise<ApiResponse<AlphaSenderPage>>; + /** + * Lists AlphaSenderInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlphaSenderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AlphaSenderInstance[]) => any): Promise<AlphaSenderInstance[]>; + list(params: AlphaSenderListInstanceOptions, callback?: (error: Error | null, items: AlphaSenderInstance[]) => any): Promise<AlphaSenderInstance[]>; + /** + * Lists AlphaSenderInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlphaSenderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AlphaSenderInstance[]>) => any): Promise<ApiResponse<AlphaSenderInstance[]>>; + listWithHttpInfo(params: AlphaSenderListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AlphaSenderInstance[]>) => any): Promise<ApiResponse<AlphaSenderInstance[]>>; + /** + * Retrieve a single page of AlphaSenderInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlphaSenderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AlphaSenderPage) => any): Promise<AlphaSenderPage>; + page(params: AlphaSenderListInstancePageOptions, callback?: (error: Error | null, items: AlphaSenderPage) => any): Promise<AlphaSenderPage>; + /** + * Retrieve a single page of AlphaSenderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlphaSenderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AlphaSenderPage>) => any): Promise<ApiResponse<AlphaSenderPage>>; + pageWithHttpInfo(params: AlphaSenderListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AlphaSenderPage>) => any): Promise<ApiResponse<AlphaSenderPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AlphaSenderListInstance(version: V1, serviceSid: string): AlphaSenderListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as AlphaSenderListInstance; + + instance.get = function get(sid, ): AlphaSenderContext { + return new AlphaSenderContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/AlphaSenders`; + + instance.create = function create(params: AlphaSenderListInstanceCreateOptions, callback?: (error: Error | null, items: AlphaSenderInstance) => any): Promise<AlphaSenderInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["alphaSender"] === null || params["alphaSender"] === undefined) { + throw new Error('Required parameter "params[\'alphaSender\']" missing.'); + } + + let data: any = {}; + + + + data["AlphaSender"] = params["alphaSender"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AlphaSenderInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AlphaSenderListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<AlphaSenderInstance>) => any): Promise<ApiResponse<AlphaSenderInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["alphaSender"] === null || params["alphaSender"] === undefined) { + throw new Error('Required parameter "params[\'alphaSender\']" missing.'); + } + + let data: any = {}; + + + + data["AlphaSender"] = params["alphaSender"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<AlphaSenderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<AlphaSenderInstance> => ({ + ...response, + body: new AlphaSenderInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AlphaSenderListInstancePageOptions | ((error: Error | null, items: AlphaSenderPage) => any), callback?: (error: Error | null, items: AlphaSenderPage) => any): Promise<AlphaSenderPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AlphaSenderPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AlphaSenderPage) => any): Promise<AlphaSenderPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AlphaSenderPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AlphaSenderListInstancePageOptions | ((error: Error | null, items: ApiResponse<AlphaSenderPage>) => any), callback?: (error: Error | null, items: ApiResponse<AlphaSenderPage>) => any): Promise<ApiResponse<AlphaSenderPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AlphaSenderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AlphaSenderPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AlphaSenderPage>) => any): Promise<ApiResponse<AlphaSenderPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AlphaSenderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AlphaSenderPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AlphaSenderPage extends Page<V1, AlphaSenderPayload, AlphaSenderResource, AlphaSenderInstance> { +/** +* Initialize the AlphaSenderPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: AlphaSenderSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AlphaSenderInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AlphaSenderResource): AlphaSenderInstance { + + return new AlphaSenderInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v1/service/channelSender.ts b/rest/messaging/v1/service/channelSender.ts new file mode 100644 index 000000000..33a31c9c3 --- /dev/null +++ b/rest/messaging/v1/service/channelSender.ts @@ -0,0 +1,760 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a ChannelSenderInstance + */ +export interface ChannelSenderListInstanceCreateOptions { + /** The SID of the Channel Sender being added to the Service. */ + "sid": string; +} + +/** + * Options to pass to each + */ +export interface ChannelSenderListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChannelSenderInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChannelSenderListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChannelSenderListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ChannelSenderContext { + + /** + * Remove a ChannelSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ChannelSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ChannelSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelSenderInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelSenderInstance) => any): Promise<ChannelSenderInstance> + + /** + * Fetch a ChannelSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelSenderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChannelSenderInstance>) => any): Promise<ApiResponse<ChannelSenderInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ChannelSenderContextSolution { + "messagingServiceSid": string; + "sid": string; +} + +export class ChannelSenderContextImpl implements ChannelSenderContext { + protected _solution: ChannelSenderContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, messagingServiceSid: string, sid: string) { + if (!isValidPathParam(messagingServiceSid)) { + throw new Error('Parameter \'messagingServiceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { messagingServiceSid, sid, }; + this._uri = `/Services/${messagingServiceSid}/ChannelSenders/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ChannelSenderInstance) => any): Promise<ChannelSenderInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ChannelSenderInstance(operationVersion, payload, instance._solution.messagingServiceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChannelSenderInstance>) => any): Promise<ApiResponse<ChannelSenderInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ChannelSenderResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ChannelSenderInstance> => ({ + ...response, + body: new ChannelSenderInstance(operationVersion, response.body, instance._solution.messagingServiceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ChannelSenderPayload extends TwilioResponsePayload { + senders: ChannelSenderResource[]; +} + +interface ChannelSenderResource { + account_sid: string; + messaging_service_sid: string; + sid: string; + sender: string; + sender_type: string; + country_code: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class ChannelSenderInstance { + protected _solution: ChannelSenderContextSolution; + protected _context?: ChannelSenderContext; + + constructor(protected _version: V1, payload: ChannelSenderResource, messagingServiceSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.messagingServiceSid = (payload.messaging_service_sid); + this.sid = (payload.sid); + this.sender = (payload.sender); + this.senderType = (payload.sender_type); + this.countryCode = (payload.country_code); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { messagingServiceSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ChannelSender resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/messaging/services) the resource is associated with. + */ + messagingServiceSid: string; + /** + * The unique string that we created to identify the ChannelSender resource. + */ + sid: string; + /** + * The unique string that identifies the sender e.g whatsapp:+123456XXXX. + */ + sender: string; + /** + * A string value that identifies the sender type e.g WhatsApp, Messenger. + */ + senderType: string; + /** + * The 2-character [ISO Country Code](https://www.iso.org/iso-3166-country-codes.html) of the number. + */ + countryCode: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the ChannelSender resource. + */ + url: string; + + private get _proxy(): ChannelSenderContext { + this._context = this._context || new ChannelSenderContextImpl(this._version, this._solution.messagingServiceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ChannelSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ChannelSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ChannelSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelSenderInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelSenderInstance) => any): Promise<ChannelSenderInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ChannelSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelSenderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChannelSenderInstance>) => any): Promise<ApiResponse<ChannelSenderInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + messagingServiceSid: this.messagingServiceSid, + sid: this.sid, + sender: this.sender, + senderType: this.senderType, + countryCode: this.countryCode, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ChannelSenderSolution { + messagingServiceSid: string; +} + +export interface ChannelSenderListInstance { + _version: V1; + _solution: ChannelSenderSolution; + _uri: string; + + (sid: string, ): ChannelSenderContext; + get(sid: string, ): ChannelSenderContext; + + + + + + + /** + * Create a ChannelSenderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelSenderInstance + */ + create(params: ChannelSenderListInstanceCreateOptions, callback?: (error: Error | null, item?: ChannelSenderInstance) => any): Promise<ChannelSenderInstance>; + + /** + * Create a ChannelSenderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelSenderInstance with HTTP metadata + */ + createWithHttpInfo(params: ChannelSenderListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ChannelSenderInstance>) => any): Promise<ApiResponse<ChannelSenderInstance>>; + + + + + /** + * Streams ChannelSenderInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelSenderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ChannelSenderInstance, done: (err?: Error) => void) => void): void; + each(params: ChannelSenderListInstanceEachOptions, callback?: (item: ChannelSenderInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChannelSenderInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelSenderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ChannelSenderInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ChannelSenderListInstanceEachOptions, callback?: (item: ChannelSenderInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChannelSenderInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelSenderPage) => any): Promise<ChannelSenderPage>; + /** + * Retrieve a single target page of ChannelSenderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ChannelSenderPage>) => any): Promise<ApiResponse<ChannelSenderPage>>; + /** + * Lists ChannelSenderInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelSenderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ChannelSenderInstance[]) => any): Promise<ChannelSenderInstance[]>; + list(params: ChannelSenderListInstanceOptions, callback?: (error: Error | null, items: ChannelSenderInstance[]) => any): Promise<ChannelSenderInstance[]>; + /** + * Lists ChannelSenderInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelSenderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ChannelSenderInstance[]>) => any): Promise<ApiResponse<ChannelSenderInstance[]>>; + listWithHttpInfo(params: ChannelSenderListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ChannelSenderInstance[]>) => any): Promise<ApiResponse<ChannelSenderInstance[]>>; + /** + * Retrieve a single page of ChannelSenderInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelSenderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ChannelSenderPage) => any): Promise<ChannelSenderPage>; + page(params: ChannelSenderListInstancePageOptions, callback?: (error: Error | null, items: ChannelSenderPage) => any): Promise<ChannelSenderPage>; + /** + * Retrieve a single page of ChannelSenderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelSenderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ChannelSenderPage>) => any): Promise<ApiResponse<ChannelSenderPage>>; + pageWithHttpInfo(params: ChannelSenderListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ChannelSenderPage>) => any): Promise<ApiResponse<ChannelSenderPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChannelSenderListInstance(version: V1, messagingServiceSid: string): ChannelSenderListInstance { + if (!isValidPathParam(messagingServiceSid)) { + throw new Error('Parameter \'messagingServiceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ChannelSenderListInstance; + + instance.get = function get(sid, ): ChannelSenderContext { + return new ChannelSenderContextImpl(version, messagingServiceSid, sid); + } + + instance._version = version; + instance._solution = { messagingServiceSid, }; + instance._uri = `/Services/${messagingServiceSid}/ChannelSenders`; + + instance.create = function create(params: ChannelSenderListInstanceCreateOptions, callback?: (error: Error | null, items: ChannelSenderInstance) => any): Promise<ChannelSenderInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["sid"] === null || params["sid"] === undefined) { + throw new Error('Required parameter "params[\'sid\']" missing.'); + } + + let data: any = {}; + + + + data["Sid"] = params["sid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelSenderInstance(operationVersion, payload, instance._solution.messagingServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ChannelSenderListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ChannelSenderInstance>) => any): Promise<ApiResponse<ChannelSenderInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["sid"] === null || params["sid"] === undefined) { + throw new Error('Required parameter "params[\'sid\']" missing.'); + } + + let data: any = {}; + + + + data["Sid"] = params["sid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ChannelSenderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ChannelSenderInstance> => ({ + ...response, + body: new ChannelSenderInstance(operationVersion, response.body, instance._solution.messagingServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ChannelSenderListInstancePageOptions | ((error: Error | null, items: ChannelSenderPage) => any), callback?: (error: Error | null, items: ChannelSenderPage) => any): Promise<ChannelSenderPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChannelSenderPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelSenderPage) => any): Promise<ChannelSenderPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChannelSenderPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ChannelSenderListInstancePageOptions | ((error: Error | null, items: ApiResponse<ChannelSenderPage>) => any), callback?: (error: Error | null, items: ApiResponse<ChannelSenderPage>) => any): Promise<ApiResponse<ChannelSenderPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ChannelSenderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelSenderPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ChannelSenderPage>) => any): Promise<ApiResponse<ChannelSenderPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ChannelSenderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelSenderPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ChannelSenderPage extends Page<V1, ChannelSenderPayload, ChannelSenderResource, ChannelSenderInstance> { +/** +* Initialize the ChannelSenderPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ChannelSenderSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ChannelSenderInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChannelSenderResource): ChannelSenderInstance { + + return new ChannelSenderInstance( + this._version, + payload, + this._solution.messagingServiceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v1/service/destinationAlphaSender.ts b/rest/messaging/v1/service/destinationAlphaSender.ts new file mode 100644 index 000000000..5b814fdd8 --- /dev/null +++ b/rest/messaging/v1/service/destinationAlphaSender.ts @@ -0,0 +1,776 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a DestinationAlphaSenderInstance + */ +export interface DestinationAlphaSenderListInstanceCreateOptions { + /** The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. */ + "alphaSender": string; + /** The Optional Two Character ISO Country Code the Alphanumeric Sender ID will be used for. If the IsoCountryCode is not provided, a default Alpha Sender will be created that can be used across all countries. */ + "isoCountryCode"?: string; +} + +/** + * Options to pass to each + */ +export interface DestinationAlphaSenderListInstanceEachOptions { + /** Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. */ + "isoCountryCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DestinationAlphaSenderInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DestinationAlphaSenderListInstanceOptions { + /** Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. */ + "isoCountryCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DestinationAlphaSenderListInstancePageOptions { + /** Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. */ + "isoCountryCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface DestinationAlphaSenderContext { + + /** + * Remove a DestinationAlphaSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a DestinationAlphaSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a DestinationAlphaSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DestinationAlphaSenderInstance + */ + fetch(callback?: (error: Error | null, item?: DestinationAlphaSenderInstance) => any): Promise<DestinationAlphaSenderInstance> + + /** + * Fetch a DestinationAlphaSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DestinationAlphaSenderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DestinationAlphaSenderInstance>) => any): Promise<ApiResponse<DestinationAlphaSenderInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DestinationAlphaSenderContextSolution { + "serviceSid": string; + "sid": string; +} + +export class DestinationAlphaSenderContextImpl implements DestinationAlphaSenderContext { + protected _solution: DestinationAlphaSenderContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/DestinationAlphaSenders/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: DestinationAlphaSenderInstance) => any): Promise<DestinationAlphaSenderInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DestinationAlphaSenderInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DestinationAlphaSenderInstance>) => any): Promise<ApiResponse<DestinationAlphaSenderInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DestinationAlphaSenderResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DestinationAlphaSenderInstance> => ({ + ...response, + body: new DestinationAlphaSenderInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DestinationAlphaSenderPayload extends TwilioResponsePayload { + alpha_senders: DestinationAlphaSenderResource[]; +} + +interface DestinationAlphaSenderResource { + sid: string; + account_sid: string; + service_sid: string; + date_created: Date; + date_updated: Date; + alpha_sender: string; + capabilities: Array<string>; + url: string; + iso_country_code: string; +} + +export class DestinationAlphaSenderInstance { + protected _solution: DestinationAlphaSenderContextSolution; + protected _context?: DestinationAlphaSenderContext; + + constructor(protected _version: V1, payload: DestinationAlphaSenderResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.alphaSender = (payload.alpha_sender); + this.capabilities = (payload.capabilities); + this.url = (payload.url); + this.isoCountryCode = (payload.iso_country_code); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the AlphaSender resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AlphaSender resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + */ + serviceSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The Alphanumeric Sender ID string. + */ + alphaSender: string; + /** + * An array of values that describe whether the number can receive calls or messages. Can be: `SMS`. + */ + capabilities: Array<string>; + /** + * The absolute URL of the AlphaSender resource. + */ + url: string; + /** + * The Two Character ISO Country Code the Alphanumeric Sender ID will be used for. For Default Alpha Senders that work across countries, this value will be an empty string + */ + isoCountryCode: string; + + private get _proxy(): DestinationAlphaSenderContext { + this._context = this._context || new DestinationAlphaSenderContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a DestinationAlphaSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a DestinationAlphaSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a DestinationAlphaSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DestinationAlphaSenderInstance + */ + fetch(callback?: (error: Error | null, item?: DestinationAlphaSenderInstance) => any): Promise<DestinationAlphaSenderInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DestinationAlphaSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DestinationAlphaSenderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DestinationAlphaSenderInstance>) => any): Promise<ApiResponse<DestinationAlphaSenderInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + alphaSender: this.alphaSender, + capabilities: this.capabilities, + url: this.url, + isoCountryCode: this.isoCountryCode, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DestinationAlphaSenderSolution { + serviceSid: string; +} + +export interface DestinationAlphaSenderListInstance { + _version: V1; + _solution: DestinationAlphaSenderSolution; + _uri: string; + + (sid: string, ): DestinationAlphaSenderContext; + get(sid: string, ): DestinationAlphaSenderContext; + + + + + + + /** + * Create a DestinationAlphaSenderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DestinationAlphaSenderInstance + */ + create(params: DestinationAlphaSenderListInstanceCreateOptions, callback?: (error: Error | null, item?: DestinationAlphaSenderInstance) => any): Promise<DestinationAlphaSenderInstance>; + + /** + * Create a DestinationAlphaSenderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DestinationAlphaSenderInstance with HTTP metadata + */ + createWithHttpInfo(params: DestinationAlphaSenderListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<DestinationAlphaSenderInstance>) => any): Promise<ApiResponse<DestinationAlphaSenderInstance>>; + + + + + /** + * Streams DestinationAlphaSenderInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DestinationAlphaSenderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DestinationAlphaSenderInstance, done: (err?: Error) => void) => void): void; + each(params: DestinationAlphaSenderListInstanceEachOptions, callback?: (item: DestinationAlphaSenderInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DestinationAlphaSenderInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DestinationAlphaSenderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DestinationAlphaSenderInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DestinationAlphaSenderListInstanceEachOptions, callback?: (item: DestinationAlphaSenderInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DestinationAlphaSenderInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DestinationAlphaSenderPage) => any): Promise<DestinationAlphaSenderPage>; + /** + * Retrieve a single target page of DestinationAlphaSenderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<DestinationAlphaSenderPage>) => any): Promise<ApiResponse<DestinationAlphaSenderPage>>; + /** + * Lists DestinationAlphaSenderInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DestinationAlphaSenderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DestinationAlphaSenderInstance[]) => any): Promise<DestinationAlphaSenderInstance[]>; + list(params: DestinationAlphaSenderListInstanceOptions, callback?: (error: Error | null, items: DestinationAlphaSenderInstance[]) => any): Promise<DestinationAlphaSenderInstance[]>; + /** + * Lists DestinationAlphaSenderInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DestinationAlphaSenderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DestinationAlphaSenderInstance[]>) => any): Promise<ApiResponse<DestinationAlphaSenderInstance[]>>; + listWithHttpInfo(params: DestinationAlphaSenderListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<DestinationAlphaSenderInstance[]>) => any): Promise<ApiResponse<DestinationAlphaSenderInstance[]>>; + /** + * Retrieve a single page of DestinationAlphaSenderInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DestinationAlphaSenderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DestinationAlphaSenderPage) => any): Promise<DestinationAlphaSenderPage>; + page(params: DestinationAlphaSenderListInstancePageOptions, callback?: (error: Error | null, items: DestinationAlphaSenderPage) => any): Promise<DestinationAlphaSenderPage>; + /** + * Retrieve a single page of DestinationAlphaSenderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DestinationAlphaSenderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DestinationAlphaSenderPage>) => any): Promise<ApiResponse<DestinationAlphaSenderPage>>; + pageWithHttpInfo(params: DestinationAlphaSenderListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<DestinationAlphaSenderPage>) => any): Promise<ApiResponse<DestinationAlphaSenderPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DestinationAlphaSenderListInstance(version: V1, serviceSid: string): DestinationAlphaSenderListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as DestinationAlphaSenderListInstance; + + instance.get = function get(sid, ): DestinationAlphaSenderContext { + return new DestinationAlphaSenderContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/DestinationAlphaSenders`; + + instance.create = function create(params: DestinationAlphaSenderListInstanceCreateOptions, callback?: (error: Error | null, items: DestinationAlphaSenderInstance) => any): Promise<DestinationAlphaSenderInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["alphaSender"] === null || params["alphaSender"] === undefined) { + throw new Error('Required parameter "params[\'alphaSender\']" missing.'); + } + + let data: any = {}; + + + + data["AlphaSender"] = params["alphaSender"]; + if (params["isoCountryCode"] !== undefined) + data["IsoCountryCode"] = params["isoCountryCode"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DestinationAlphaSenderInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: DestinationAlphaSenderListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<DestinationAlphaSenderInstance>) => any): Promise<ApiResponse<DestinationAlphaSenderInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["alphaSender"] === null || params["alphaSender"] === undefined) { + throw new Error('Required parameter "params[\'alphaSender\']" missing.'); + } + + let data: any = {}; + + + + data["AlphaSender"] = params["alphaSender"]; + if (params["isoCountryCode"] !== undefined) + data["IsoCountryCode"] = params["isoCountryCode"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<DestinationAlphaSenderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<DestinationAlphaSenderInstance> => ({ + ...response, + body: new DestinationAlphaSenderInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: DestinationAlphaSenderListInstancePageOptions | ((error: Error | null, items: DestinationAlphaSenderPage) => any), callback?: (error: Error | null, items: DestinationAlphaSenderPage) => any): Promise<DestinationAlphaSenderPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["isoCountryCode"] !== undefined) + data["IsoCountryCode"] = params["isoCountryCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DestinationAlphaSenderPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DestinationAlphaSenderPage) => any): Promise<DestinationAlphaSenderPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DestinationAlphaSenderPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DestinationAlphaSenderListInstancePageOptions | ((error: Error | null, items: ApiResponse<DestinationAlphaSenderPage>) => any), callback?: (error: Error | null, items: ApiResponse<DestinationAlphaSenderPage>) => any): Promise<ApiResponse<DestinationAlphaSenderPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["isoCountryCode"] !== undefined) + data["IsoCountryCode"] = params["isoCountryCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<DestinationAlphaSenderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DestinationAlphaSenderPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<DestinationAlphaSenderPage>) => any): Promise<ApiResponse<DestinationAlphaSenderPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<DestinationAlphaSenderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DestinationAlphaSenderPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class DestinationAlphaSenderPage extends Page<V1, DestinationAlphaSenderPayload, DestinationAlphaSenderResource, DestinationAlphaSenderInstance> { +/** +* Initialize the DestinationAlphaSenderPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: DestinationAlphaSenderSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DestinationAlphaSenderInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DestinationAlphaSenderResource): DestinationAlphaSenderInstance { + + return new DestinationAlphaSenderInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v1/service/phoneNumber.ts b/rest/messaging/v1/service/phoneNumber.ts new file mode 100644 index 000000000..52db933dd --- /dev/null +++ b/rest/messaging/v1/service/phoneNumber.ts @@ -0,0 +1,760 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a PhoneNumberInstance + */ +export interface PhoneNumberListInstanceCreateOptions { + /** The SID of the Phone Number being added to the Service. */ + "phoneNumberSid": string; +} + +/** + * Options to pass to each + */ +export interface PhoneNumberListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PhoneNumberListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PhoneNumberListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PhoneNumberContext { + + /** + * Remove a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PhoneNumberContextSolution { + "serviceSid": string; + "sid": string; +} + +export class PhoneNumberContextImpl implements PhoneNumberContext { + protected _solution: PhoneNumberContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/PhoneNumbers/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PhoneNumberPayload extends TwilioResponsePayload { + phone_numbers: PhoneNumberResource[]; +} + +interface PhoneNumberResource { + sid: string; + account_sid: string; + service_sid: string; + date_created: Date; + date_updated: Date; + phone_number: string; + country_code: string; + capabilities: Array<string>; + url: string; +} + +export class PhoneNumberInstance { + protected _solution: PhoneNumberContextSolution; + protected _context?: PhoneNumberContext; + + constructor(protected _version: V1, payload: PhoneNumberResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.phoneNumber = (payload.phone_number); + this.countryCode = (payload.country_code); + this.capabilities = (payload.capabilities); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the PhoneNumber resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + */ + serviceSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The 2-character [ISO Country Code](https://www.iso.org/iso-3166-country-codes.html) of the number. + */ + countryCode: string; + /** + * An array of values that describe whether the number can receive calls or messages. Can be: `Voice`, `SMS`, and `MMS`. + */ + capabilities: Array<string>; + /** + * The absolute URL of the PhoneNumber resource. + */ + url: string; + + private get _proxy(): PhoneNumberContext { + this._context = this._context || new PhoneNumberContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + phoneNumber: this.phoneNumber, + countryCode: this.countryCode, + capabilities: this.capabilities, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PhoneNumberSolution { + serviceSid: string; +} + +export interface PhoneNumberListInstance { + _version: V1; + _solution: PhoneNumberSolution; + _uri: string; + + (sid: string, ): PhoneNumberContext; + get(sid: string, ): PhoneNumberContext; + + + + + + + /** + * Create a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + create(params: PhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + /** + * Create a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + createWithHttpInfo(params: PhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + + + + /** + * Streams PhoneNumberInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + each(params: PhoneNumberListInstanceEachOptions, callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PhoneNumberInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PhoneNumberListInstanceEachOptions, callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PhoneNumberInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage>; + /** + * Retrieve a single target page of PhoneNumberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>>; + /** + * Lists PhoneNumberInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PhoneNumberInstance[]) => any): Promise<PhoneNumberInstance[]>; + list(params: PhoneNumberListInstanceOptions, callback?: (error: Error | null, items: PhoneNumberInstance[]) => any): Promise<PhoneNumberInstance[]>; + /** + * Lists PhoneNumberInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PhoneNumberInstance[]>) => any): Promise<ApiResponse<PhoneNumberInstance[]>>; + listWithHttpInfo(params: PhoneNumberListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<PhoneNumberInstance[]>) => any): Promise<ApiResponse<PhoneNumberInstance[]>>; + /** + * Retrieve a single page of PhoneNumberInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage>; + page(params: PhoneNumberListInstancePageOptions, callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage>; + /** + * Retrieve a single page of PhoneNumberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>>; + pageWithHttpInfo(params: PhoneNumberListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PhoneNumberListInstance(version: V1, serviceSid: string): PhoneNumberListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as PhoneNumberListInstance; + + instance.get = function get(sid, ): PhoneNumberContext { + return new PhoneNumberContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/PhoneNumbers`; + + instance.create = function create(params: PhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, items: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumberSid"] === null || params["phoneNumberSid"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumberSid\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumberSid"] = params["phoneNumberSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: PhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumberSid"] === null || params["phoneNumberSid"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumberSid\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumberSid"] = params["phoneNumberSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: PhoneNumberListInstancePageOptions | ((error: Error | null, items: PhoneNumberPage) => any), callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PhoneNumberPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PhoneNumberPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PhoneNumberListInstancePageOptions | ((error: Error | null, items: ApiResponse<PhoneNumberPage>) => any), callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<PhoneNumberPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PhoneNumberPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<PhoneNumberPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PhoneNumberPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PhoneNumberPage extends Page<V1, PhoneNumberPayload, PhoneNumberResource, PhoneNumberInstance> { +/** +* Initialize the PhoneNumberPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: PhoneNumberSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PhoneNumberInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PhoneNumberResource): PhoneNumberInstance { + + return new PhoneNumberInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v1/service/shortCode.ts b/rest/messaging/v1/service/shortCode.ts new file mode 100644 index 000000000..8504c0ab7 --- /dev/null +++ b/rest/messaging/v1/service/shortCode.ts @@ -0,0 +1,760 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a ShortCodeInstance + */ +export interface ShortCodeListInstanceCreateOptions { + /** The SID of the ShortCode resource being added to the Service. */ + "shortCodeSid": string; +} + +/** + * Options to pass to each + */ +export interface ShortCodeListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ShortCodeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ShortCodeListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ShortCodeListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ShortCodeContext { + + /** + * Remove a ShortCodeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ShortCodeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ShortCodeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance + */ + fetch(callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise<ShortCodeInstance> + + /** + * Fetch a ShortCodeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ShortCodeInstance>) => any): Promise<ApiResponse<ShortCodeInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ShortCodeContextSolution { + "serviceSid": string; + "sid": string; +} + +export class ShortCodeContextImpl implements ShortCodeContext { + protected _solution: ShortCodeContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/ShortCodes/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise<ShortCodeInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ShortCodeInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ShortCodeInstance>) => any): Promise<ApiResponse<ShortCodeInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ShortCodeResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ShortCodeInstance> => ({ + ...response, + body: new ShortCodeInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ShortCodePayload extends TwilioResponsePayload { + short_codes: ShortCodeResource[]; +} + +interface ShortCodeResource { + sid: string; + account_sid: string; + service_sid: string; + date_created: Date; + date_updated: Date; + short_code: string; + country_code: string; + capabilities: Array<string>; + url: string; +} + +export class ShortCodeInstance { + protected _solution: ShortCodeContextSolution; + protected _context?: ShortCodeContext; + + constructor(protected _version: V1, payload: ShortCodeResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.shortCode = (payload.short_code); + this.countryCode = (payload.country_code); + this.capabilities = (payload.capabilities); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the ShortCode resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + */ + serviceSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The [E.164](https://www.twilio.com/docs/glossary/what-e164) format of the short code. + */ + shortCode: string; + /** + * The 2-character [ISO Country Code](https://www.iso.org/iso-3166-country-codes.html) of the number. + */ + countryCode: string; + /** + * An array of values that describe whether the number can receive calls or messages. Can be: `SMS` and `MMS`. + */ + capabilities: Array<string>; + /** + * The absolute URL of the ShortCode resource. + */ + url: string; + + private get _proxy(): ShortCodeContext { + this._context = this._context || new ShortCodeContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ShortCodeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ShortCodeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ShortCodeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance + */ + fetch(callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise<ShortCodeInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ShortCodeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ShortCodeInstance>) => any): Promise<ApiResponse<ShortCodeInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + shortCode: this.shortCode, + countryCode: this.countryCode, + capabilities: this.capabilities, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ShortCodeSolution { + serviceSid: string; +} + +export interface ShortCodeListInstance { + _version: V1; + _solution: ShortCodeSolution; + _uri: string; + + (sid: string, ): ShortCodeContext; + get(sid: string, ): ShortCodeContext; + + + + + + + /** + * Create a ShortCodeInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance + */ + create(params: ShortCodeListInstanceCreateOptions, callback?: (error: Error | null, item?: ShortCodeInstance) => any): Promise<ShortCodeInstance>; + + /** + * Create a ShortCodeInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ShortCodeInstance with HTTP metadata + */ + createWithHttpInfo(params: ShortCodeListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ShortCodeInstance>) => any): Promise<ApiResponse<ShortCodeInstance>>; + + + + + /** + * Streams ShortCodeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ShortCodeInstance, done: (err?: Error) => void) => void): void; + each(params: ShortCodeListInstanceEachOptions, callback?: (item: ShortCodeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ShortCodeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ShortCodeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ShortCodeListInstanceEachOptions, callback?: (item: ShortCodeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ShortCodeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ShortCodePage) => any): Promise<ShortCodePage>; + /** + * Retrieve a single target page of ShortCodeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ShortCodePage>) => any): Promise<ApiResponse<ShortCodePage>>; + /** + * Lists ShortCodeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ShortCodeInstance[]) => any): Promise<ShortCodeInstance[]>; + list(params: ShortCodeListInstanceOptions, callback?: (error: Error | null, items: ShortCodeInstance[]) => any): Promise<ShortCodeInstance[]>; + /** + * Lists ShortCodeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ShortCodeInstance[]>) => any): Promise<ApiResponse<ShortCodeInstance[]>>; + listWithHttpInfo(params: ShortCodeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ShortCodeInstance[]>) => any): Promise<ApiResponse<ShortCodeInstance[]>>; + /** + * Retrieve a single page of ShortCodeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ShortCodePage) => any): Promise<ShortCodePage>; + page(params: ShortCodeListInstancePageOptions, callback?: (error: Error | null, items: ShortCodePage) => any): Promise<ShortCodePage>; + /** + * Retrieve a single page of ShortCodeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ShortCodeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ShortCodePage>) => any): Promise<ApiResponse<ShortCodePage>>; + pageWithHttpInfo(params: ShortCodeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ShortCodePage>) => any): Promise<ApiResponse<ShortCodePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ShortCodeListInstance(version: V1, serviceSid: string): ShortCodeListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ShortCodeListInstance; + + instance.get = function get(sid, ): ShortCodeContext { + return new ShortCodeContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/ShortCodes`; + + instance.create = function create(params: ShortCodeListInstanceCreateOptions, callback?: (error: Error | null, items: ShortCodeInstance) => any): Promise<ShortCodeInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["shortCodeSid"] === null || params["shortCodeSid"] === undefined) { + throw new Error('Required parameter "params[\'shortCodeSid\']" missing.'); + } + + let data: any = {}; + + + + data["ShortCodeSid"] = params["shortCodeSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ShortCodeInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ShortCodeListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ShortCodeInstance>) => any): Promise<ApiResponse<ShortCodeInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["shortCodeSid"] === null || params["shortCodeSid"] === undefined) { + throw new Error('Required parameter "params[\'shortCodeSid\']" missing.'); + } + + let data: any = {}; + + + + data["ShortCodeSid"] = params["shortCodeSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ShortCodeResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ShortCodeInstance> => ({ + ...response, + body: new ShortCodeInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ShortCodeListInstancePageOptions | ((error: Error | null, items: ShortCodePage) => any), callback?: (error: Error | null, items: ShortCodePage) => any): Promise<ShortCodePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ShortCodePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ShortCodePage) => any): Promise<ShortCodePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ShortCodePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ShortCodeListInstancePageOptions | ((error: Error | null, items: ApiResponse<ShortCodePage>) => any), callback?: (error: Error | null, items: ApiResponse<ShortCodePage>) => any): Promise<ApiResponse<ShortCodePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ShortCodePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ShortCodePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ShortCodePage>) => any): Promise<ApiResponse<ShortCodePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ShortCodePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ShortCodePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ShortCodePage extends Page<V1, ShortCodePayload, ShortCodeResource, ShortCodeInstance> { +/** +* Initialize the ShortCodePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ShortCodeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ShortCodeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ShortCodeResource): ShortCodeInstance { + + return new ShortCodeInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v1/service/usAppToPerson.ts b/rest/messaging/v1/service/usAppToPerson.ts new file mode 100644 index 000000000..186e0bb99 --- /dev/null +++ b/rest/messaging/v1/service/usAppToPerson.ts @@ -0,0 +1,1375 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to fetch a UsAppToPersonInstance + */ +export interface UsAppToPersonContextFetchOptions { + /** The version of the Messaging API to use for this request */ + "xTwilioApiVersion"?: string; +} + +/** + * Options to pass to update a UsAppToPersonInstance + */ +export interface UsAppToPersonContextUpdateOptions { + /** Indicates that this SMS campaign will send messages that contain links. */ + "hasEmbeddedLinks": boolean; + /** Indicates that this SMS campaign will send messages that contain phone numbers. */ + "hasEmbeddedPhone": boolean; + /** An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. */ + "messageSamples": Array<string>; + /** Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. */ + "messageFlow": string; + /** A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. */ + "description": string; + /** A boolean that specifies whether campaign requires age gate for federally legal content. */ + "ageGated": boolean; + /** A boolean that specifies whether campaign allows direct lending or not. */ + "directLending": boolean; + /** The version of the Messaging API to use for this request */ + "xTwilioApiVersion"?: string; + /** The URL of the privacy policy for the campaign. */ + "privacyPolicyUrl"?: string; + /** The URL of the terms and conditions for the campaign. */ + "termsAndConditionsUrl"?: string; +} + +/** + * Options to pass to create a UsAppToPersonInstance + */ +export interface UsAppToPersonListInstanceCreateOptions { + /** A2P Brand Registration SID */ + "brandRegistrationSid": string; + /** A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. */ + "description": string; + /** Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. */ + "messageFlow": string; + /** An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. */ + "messageSamples": Array<string>; + /** A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] */ + "usAppToPersonUsecase": string; + /** Indicates that this SMS campaign will send messages that contain links. */ + "hasEmbeddedLinks": boolean; + /** Indicates that this SMS campaign will send messages that contain phone numbers. */ + "hasEmbeddedPhone": boolean; + /** The version of the Messaging API to use for this request */ + "xTwilioApiVersion"?: string; + /** If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. */ + "optInMessage"?: string; + /** Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio\\\'s Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. */ + "optOutMessage"?: string; + /** When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio\\\'s Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. */ + "helpMessage"?: string; + /** If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. */ + "optInKeywords"?: Array<string>; + /** End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio\\\'s Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. */ + "optOutKeywords"?: Array<string>; + /** End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio\\\'s Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. */ + "helpKeywords"?: Array<string>; + /** A boolean that specifies whether campaign has Subscriber Optin or not. */ + "subscriberOptIn"?: boolean; + /** A boolean that specifies whether campaign is age gated or not. */ + "ageGated"?: boolean; + /** A boolean that specifies whether campaign allows direct lending or not. */ + "directLending"?: boolean; + /** The URL of the privacy policy for the campaign. */ + "privacyPolicyUrl"?: string; + /** The URL of the terms and conditions for the campaign. */ + "termsAndConditionsUrl"?: string; +} + +/** + * Options to pass to each + */ +export interface UsAppToPersonListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** The version of the Messaging API to use for this request */ + "xTwilioApiVersion"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UsAppToPersonInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UsAppToPersonListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** The version of the Messaging API to use for this request */ + "xTwilioApiVersion"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UsAppToPersonListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** The version of the Messaging API to use for this request */ + "xTwilioApiVersion"?: string; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UsAppToPersonContext { + + /** + * Remove a UsAppToPersonInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a UsAppToPersonInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a UsAppToPersonInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance + */ + fetch(callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance>; + /** + * Fetch a UsAppToPersonInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance + */ + fetch(params: UsAppToPersonContextFetchOptions, callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance>; + + /** + * Fetch a UsAppToPersonInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>>; + /** + * Fetch a UsAppToPersonInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance with HTTP metadata + */ + fetchWithHttpInfo(params: UsAppToPersonContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>>; + + /** + * Update a UsAppToPersonInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance + */ + update(params: UsAppToPersonContextUpdateOptions, callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance>; + + /** + * Update a UsAppToPersonInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance with HTTP metadata + */ + updateWithHttpInfo(params: UsAppToPersonContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UsAppToPersonContextSolution { + "messagingServiceSid": string; + "sid": string; +} + +export class UsAppToPersonContextImpl implements UsAppToPersonContext { + protected _solution: UsAppToPersonContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, messagingServiceSid: string, sid: string) { + if (!isValidPathParam(messagingServiceSid)) { + throw new Error('Parameter \'messagingServiceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { messagingServiceSid, sid, }; + this._uri = `/Services/${messagingServiceSid}/Compliance/Usa2p/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(params?: UsAppToPersonContextFetchOptions | ((error: Error | null, item?: UsAppToPersonInstance) => any),callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["xTwilioApiVersion"] !== undefined) headers["X-Twilio-Api-Version"] = params["xTwilioApiVersion"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new UsAppToPersonInstance(operationVersion, payload, instance._solution.messagingServiceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: UsAppToPersonContextFetchOptions | ((error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["xTwilioApiVersion"] !== undefined) headers["X-Twilio-Api-Version"] = params["xTwilioApiVersion"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<UsAppToPersonResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<UsAppToPersonInstance> => ({ + ...response, + body: new UsAppToPersonInstance(operationVersion, response.body, instance._solution.messagingServiceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: UsAppToPersonContextUpdateOptions,callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["hasEmbeddedLinks"] === null || params["hasEmbeddedLinks"] === undefined) { + throw new Error('Required parameter "params[\'hasEmbeddedLinks\']" missing.'); + } + + if (params["hasEmbeddedPhone"] === null || params["hasEmbeddedPhone"] === undefined) { + throw new Error('Required parameter "params[\'hasEmbeddedPhone\']" missing.'); + } + + if (params["messageSamples"] === null || params["messageSamples"] === undefined) { + throw new Error('Required parameter "params[\'messageSamples\']" missing.'); + } + + if (params["messageFlow"] === null || params["messageFlow"] === undefined) { + throw new Error('Required parameter "params[\'messageFlow\']" missing.'); + } + + if (params["description"] === null || params["description"] === undefined) { + throw new Error('Required parameter "params[\'description\']" missing.'); + } + + if (params["ageGated"] === null || params["ageGated"] === undefined) { + throw new Error('Required parameter "params[\'ageGated\']" missing.'); + } + + if (params["directLending"] === null || params["directLending"] === undefined) { + throw new Error('Required parameter "params[\'directLending\']" missing.'); + } + + let data: any = {}; + + + + data["HasEmbeddedLinks"] = serialize.bool(params["hasEmbeddedLinks"]); + + data["HasEmbeddedPhone"] = serialize.bool(params["hasEmbeddedPhone"]); + + data["MessageSamples"] = serialize.map(params["messageSamples"], (e: string) => (e)); + + data["MessageFlow"] = params["messageFlow"]; + + data["Description"] = params["description"]; + + data["AgeGated"] = serialize.bool(params["ageGated"]); + + data["DirectLending"] = serialize.bool(params["directLending"]); + if (params["privacyPolicyUrl"] !== undefined) + data["PrivacyPolicyUrl"] = params["privacyPolicyUrl"]; + if (params["termsAndConditionsUrl"] !== undefined) + data["TermsAndConditionsUrl"] = params["termsAndConditionsUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioApiVersion"] !== undefined) headers["X-Twilio-Api-Version"] = params["xTwilioApiVersion"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UsAppToPersonInstance(operationVersion, payload, instance._solution.messagingServiceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: UsAppToPersonContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["hasEmbeddedLinks"] === null || params["hasEmbeddedLinks"] === undefined) { + throw new Error('Required parameter "params[\'hasEmbeddedLinks\']" missing.'); + } + + if (params["hasEmbeddedPhone"] === null || params["hasEmbeddedPhone"] === undefined) { + throw new Error('Required parameter "params[\'hasEmbeddedPhone\']" missing.'); + } + + if (params["messageSamples"] === null || params["messageSamples"] === undefined) { + throw new Error('Required parameter "params[\'messageSamples\']" missing.'); + } + + if (params["messageFlow"] === null || params["messageFlow"] === undefined) { + throw new Error('Required parameter "params[\'messageFlow\']" missing.'); + } + + if (params["description"] === null || params["description"] === undefined) { + throw new Error('Required parameter "params[\'description\']" missing.'); + } + + if (params["ageGated"] === null || params["ageGated"] === undefined) { + throw new Error('Required parameter "params[\'ageGated\']" missing.'); + } + + if (params["directLending"] === null || params["directLending"] === undefined) { + throw new Error('Required parameter "params[\'directLending\']" missing.'); + } + + let data: any = {}; + + + + data["HasEmbeddedLinks"] = serialize.bool(params["hasEmbeddedLinks"]); + + data["HasEmbeddedPhone"] = serialize.bool(params["hasEmbeddedPhone"]); + + data["MessageSamples"] = serialize.map(params["messageSamples"], (e: string) => (e)); + + data["MessageFlow"] = params["messageFlow"]; + + data["Description"] = params["description"]; + + data["AgeGated"] = serialize.bool(params["ageGated"]); + + data["DirectLending"] = serialize.bool(params["directLending"]); + if (params["privacyPolicyUrl"] !== undefined) + data["PrivacyPolicyUrl"] = params["privacyPolicyUrl"]; + if (params["termsAndConditionsUrl"] !== undefined) + data["TermsAndConditionsUrl"] = params["termsAndConditionsUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioApiVersion"] !== undefined) headers["X-Twilio-Api-Version"] = params["xTwilioApiVersion"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<UsAppToPersonResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<UsAppToPersonInstance> => ({ + ...response, + body: new UsAppToPersonInstance(operationVersion, response.body, instance._solution.messagingServiceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UsAppToPersonPayload extends TwilioResponsePayload { + compliance: UsAppToPersonResource[]; +} + +interface UsAppToPersonResource { + sid: string; + account_sid: string; + brand_registration_sid: string; + messaging_service_sid: string; + description: string; + message_samples: Array<string>; + us_app_to_person_usecase: string; + has_embedded_links: boolean; + has_embedded_phone: boolean; + subscriber_opt_in: boolean; + age_gated: boolean; + direct_lending: boolean; + campaign_status: string; + campaign_id: string; + is_externally_registered: boolean; + rate_limits: any; + message_flow: string; + opt_in_message: string; + opt_out_message: string; + help_message: string; + opt_in_keywords: Array<string>; + opt_out_keywords: Array<string>; + help_keywords: Array<string>; + date_created: Date; + date_updated: Date; + url: string; + mock: boolean; + errors: Array<Record<string, object>>; + privacy_policy_url: string; + terms_and_conditions_url: string; +} + +export class UsAppToPersonInstance { + protected _solution: UsAppToPersonContextSolution; + protected _context?: UsAppToPersonContext; + + constructor(protected _version: V1, payload: UsAppToPersonResource, messagingServiceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.brandRegistrationSid = (payload.brand_registration_sid); + this.messagingServiceSid = (payload.messaging_service_sid); + this.description = (payload.description); + this.messageSamples = (payload.message_samples); + this.usAppToPersonUsecase = (payload.us_app_to_person_usecase); + this.hasEmbeddedLinks = (payload.has_embedded_links); + this.hasEmbeddedPhone = (payload.has_embedded_phone); + this.subscriberOptIn = (payload.subscriber_opt_in); + this.ageGated = (payload.age_gated); + this.directLending = (payload.direct_lending); + this.campaignStatus = (payload.campaign_status); + this.campaignId = (payload.campaign_id); + this.isExternallyRegistered = (payload.is_externally_registered); + this.rateLimits = (payload.rate_limits); + this.messageFlow = (payload.message_flow); + this.optInMessage = (payload.opt_in_message); + this.optOutMessage = (payload.opt_out_message); + this.helpMessage = (payload.help_message); + this.optInKeywords = (payload.opt_in_keywords); + this.optOutKeywords = (payload.opt_out_keywords); + this.helpKeywords = (payload.help_keywords); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.mock = (payload.mock); + this.errors = (payload.errors); + this.privacyPolicyUrl = (payload.privacy_policy_url); + this.termsAndConditionsUrl = (payload.terms_and_conditions_url); + + this._solution = { messagingServiceSid, sid: sid, }; + } + + /** + * The unique string that identifies a US A2P Compliance resource `QE2c6890da8086d771620e9b13fadeba0b`. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Campaign belongs to. + */ + accountSid: string; + /** + * The unique string to identify the A2P brand. + */ + brandRegistrationSid: string; + /** + * The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + */ + messagingServiceSid: string; + /** + * A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + */ + description: string; + /** + * An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + */ + messageSamples: Array<string>; + /** + * A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING, SOLE_PROPRIETOR...]. SOLE_PROPRIETOR campaign use cases can only be created by SOLE_PROPRIETOR Brands, and there can only be one SOLE_PROPRIETOR campaign created per SOLE_PROPRIETOR Brand. + */ + usAppToPersonUsecase: string; + /** + * Indicate that this SMS campaign will send messages that contain links. + */ + hasEmbeddedLinks: boolean; + /** + * Indicates that this SMS campaign will send messages that contain phone numbers. + */ + hasEmbeddedPhone: boolean; + /** + * A boolean that specifies whether campaign has Subscriber Optin or not. + */ + subscriberOptIn: boolean; + /** + * A boolean that specifies whether campaign is age gated or not. + */ + ageGated: boolean; + /** + * A boolean that specifies whether campaign allows direct lending or not. + */ + directLending: boolean; + /** + * Campaign status. Examples: IN_PROGRESS, VERIFIED, FAILED. + */ + campaignStatus: string; + /** + * The Campaign Registry (TCR) Campaign ID. + */ + campaignId: string; + /** + * Indicates whether the campaign was registered externally or not. + */ + isExternallyRegistered: boolean; + /** + * Rate limit and/or classification set by each carrier, Ex. AT&T or T-Mobile. + */ + rateLimits: any; + /** + * Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + */ + messageFlow: string; + /** + * If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + */ + optInMessage: string; + /** + * Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio\'s Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + */ + optOutMessage: string; + /** + * When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio\'s Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + */ + helpMessage: string; + /** + * If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + */ + optInKeywords: Array<string>; + /** + * End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio\'s Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + */ + optOutKeywords: Array<string>; + /** + * End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio\'s Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + */ + helpKeywords: Array<string>; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the US App to Person resource. + */ + url: string; + /** + * A boolean that specifies whether campaign is a mock or not. Mock campaigns will be automatically created if using a mock brand. Mock campaigns should only be used for testing purposes. + */ + mock: boolean; + /** + * Details indicating why a campaign registration failed. These errors can indicate one or more fields that were incorrect or did not meet review requirements. + */ + errors: Array<Record<string, object>>; + /** + * The URL of the privacy policy for the campaign. + */ + privacyPolicyUrl: string; + /** + * The URL of the terms and conditions for the campaign. + */ + termsAndConditionsUrl: string; + + private get _proxy(): UsAppToPersonContext { + this._context = this._context || new UsAppToPersonContextImpl(this._version, this._solution.messagingServiceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a UsAppToPersonInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UsAppToPersonInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UsAppToPersonInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance + */ + fetch(callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance>; + /** + * Fetch a UsAppToPersonInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance + */ + fetch(params: UsAppToPersonContextFetchOptions, callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a UsAppToPersonInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>>; + /** + * Fetch a UsAppToPersonInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance with HTTP metadata + */ + fetchWithHttpInfo(params: UsAppToPersonContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Update a UsAppToPersonInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance + */ + update(params: UsAppToPersonContextUpdateOptions, callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance>; + + update(params?: any, callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a UsAppToPersonInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance with HTTP metadata + */ + updateWithHttpInfo(params: UsAppToPersonContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + brandRegistrationSid: this.brandRegistrationSid, + messagingServiceSid: this.messagingServiceSid, + description: this.description, + messageSamples: this.messageSamples, + usAppToPersonUsecase: this.usAppToPersonUsecase, + hasEmbeddedLinks: this.hasEmbeddedLinks, + hasEmbeddedPhone: this.hasEmbeddedPhone, + subscriberOptIn: this.subscriberOptIn, + ageGated: this.ageGated, + directLending: this.directLending, + campaignStatus: this.campaignStatus, + campaignId: this.campaignId, + isExternallyRegistered: this.isExternallyRegistered, + rateLimits: this.rateLimits, + messageFlow: this.messageFlow, + optInMessage: this.optInMessage, + optOutMessage: this.optOutMessage, + helpMessage: this.helpMessage, + optInKeywords: this.optInKeywords, + optOutKeywords: this.optOutKeywords, + helpKeywords: this.helpKeywords, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + mock: this.mock, + errors: this.errors, + privacyPolicyUrl: this.privacyPolicyUrl, + termsAndConditionsUrl: this.termsAndConditionsUrl, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UsAppToPersonSolution { + messagingServiceSid: string; +} + +export interface UsAppToPersonListInstance { + _version: V1; + _solution: UsAppToPersonSolution; + _uri: string; + + (sid: string, ): UsAppToPersonContext; + get(sid: string, ): UsAppToPersonContext; + + + + + + + + + /** + * Create a UsAppToPersonInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance + */ + create(params: UsAppToPersonListInstanceCreateOptions, callback?: (error: Error | null, item?: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance>; + + /** + * Create a UsAppToPersonInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonInstance with HTTP metadata + */ + createWithHttpInfo(params: UsAppToPersonListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>>; + + + + + /** + * Streams UsAppToPersonInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsAppToPersonListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UsAppToPersonInstance, done: (err?: Error) => void) => void): void; + each(params: UsAppToPersonListInstanceEachOptions, callback?: (item: UsAppToPersonInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UsAppToPersonInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsAppToPersonListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UsAppToPersonInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UsAppToPersonListInstanceEachOptions, callback?: (item: UsAppToPersonInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UsAppToPersonInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UsAppToPersonPage) => any): Promise<UsAppToPersonPage>; + /** + * Retrieve a single target page of UsAppToPersonInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<UsAppToPersonPage>) => any): Promise<ApiResponse<UsAppToPersonPage>>; + /** + * Lists UsAppToPersonInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsAppToPersonListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UsAppToPersonInstance[]) => any): Promise<UsAppToPersonInstance[]>; + list(params: UsAppToPersonListInstanceOptions, callback?: (error: Error | null, items: UsAppToPersonInstance[]) => any): Promise<UsAppToPersonInstance[]>; + /** + * Lists UsAppToPersonInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsAppToPersonListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UsAppToPersonInstance[]>) => any): Promise<ApiResponse<UsAppToPersonInstance[]>>; + listWithHttpInfo(params: UsAppToPersonListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<UsAppToPersonInstance[]>) => any): Promise<ApiResponse<UsAppToPersonInstance[]>>; + /** + * Retrieve a single page of UsAppToPersonInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsAppToPersonListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UsAppToPersonPage) => any): Promise<UsAppToPersonPage>; + page(params: UsAppToPersonListInstancePageOptions, callback?: (error: Error | null, items: UsAppToPersonPage) => any): Promise<UsAppToPersonPage>; + /** + * Retrieve a single page of UsAppToPersonInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsAppToPersonListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UsAppToPersonPage>) => any): Promise<ApiResponse<UsAppToPersonPage>>; + pageWithHttpInfo(params: UsAppToPersonListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<UsAppToPersonPage>) => any): Promise<ApiResponse<UsAppToPersonPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UsAppToPersonListInstance(version: V1, messagingServiceSid: string): UsAppToPersonListInstance { + if (!isValidPathParam(messagingServiceSid)) { + throw new Error('Parameter \'messagingServiceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as UsAppToPersonListInstance; + + instance.get = function get(sid, ): UsAppToPersonContext { + return new UsAppToPersonContextImpl(version, messagingServiceSid, sid); + } + + instance._version = version; + instance._solution = { messagingServiceSid, }; + instance._uri = `/Services/${messagingServiceSid}/Compliance/Usa2p`; + + instance.create = function create(params: UsAppToPersonListInstanceCreateOptions, callback?: (error: Error | null, items: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["brandRegistrationSid"] === null || params["brandRegistrationSid"] === undefined) { + throw new Error('Required parameter "params[\'brandRegistrationSid\']" missing.'); + } + + if (params["description"] === null || params["description"] === undefined) { + throw new Error('Required parameter "params[\'description\']" missing.'); + } + + if (params["messageFlow"] === null || params["messageFlow"] === undefined) { + throw new Error('Required parameter "params[\'messageFlow\']" missing.'); + } + + if (params["messageSamples"] === null || params["messageSamples"] === undefined) { + throw new Error('Required parameter "params[\'messageSamples\']" missing.'); + } + + if (params["usAppToPersonUsecase"] === null || params["usAppToPersonUsecase"] === undefined) { + throw new Error('Required parameter "params[\'usAppToPersonUsecase\']" missing.'); + } + + if (params["hasEmbeddedLinks"] === null || params["hasEmbeddedLinks"] === undefined) { + throw new Error('Required parameter "params[\'hasEmbeddedLinks\']" missing.'); + } + + if (params["hasEmbeddedPhone"] === null || params["hasEmbeddedPhone"] === undefined) { + throw new Error('Required parameter "params[\'hasEmbeddedPhone\']" missing.'); + } + + let data: any = {}; + + + + data["BrandRegistrationSid"] = params["brandRegistrationSid"]; + + data["Description"] = params["description"]; + + data["MessageFlow"] = params["messageFlow"]; + + data["MessageSamples"] = serialize.map(params["messageSamples"], (e: string) => (e)); + + data["UsAppToPersonUsecase"] = params["usAppToPersonUsecase"]; + + data["HasEmbeddedLinks"] = serialize.bool(params["hasEmbeddedLinks"]); + + data["HasEmbeddedPhone"] = serialize.bool(params["hasEmbeddedPhone"]); + if (params["optInMessage"] !== undefined) + data["OptInMessage"] = params["optInMessage"]; + if (params["optOutMessage"] !== undefined) + data["OptOutMessage"] = params["optOutMessage"]; + if (params["helpMessage"] !== undefined) + data["HelpMessage"] = params["helpMessage"]; + if (params["optInKeywords"] !== undefined) + data["OptInKeywords"] = serialize.map(params["optInKeywords"], (e: string) => (e)); + if (params["optOutKeywords"] !== undefined) + data["OptOutKeywords"] = serialize.map(params["optOutKeywords"], (e: string) => (e)); + if (params["helpKeywords"] !== undefined) + data["HelpKeywords"] = serialize.map(params["helpKeywords"], (e: string) => (e)); + if (params["subscriberOptIn"] !== undefined) + data["SubscriberOptIn"] = serialize.bool(params["subscriberOptIn"]); + if (params["ageGated"] !== undefined) + data["AgeGated"] = serialize.bool(params["ageGated"]); + if (params["directLending"] !== undefined) + data["DirectLending"] = serialize.bool(params["directLending"]); + if (params["privacyPolicyUrl"] !== undefined) + data["PrivacyPolicyUrl"] = params["privacyPolicyUrl"]; + if (params["termsAndConditionsUrl"] !== undefined) + data["TermsAndConditionsUrl"] = params["termsAndConditionsUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioApiVersion"] !== undefined) headers["X-Twilio-Api-Version"] = params["xTwilioApiVersion"]; + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UsAppToPersonInstance(operationVersion, payload, instance._solution.messagingServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: UsAppToPersonListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<UsAppToPersonInstance>) => any): Promise<ApiResponse<UsAppToPersonInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["brandRegistrationSid"] === null || params["brandRegistrationSid"] === undefined) { + throw new Error('Required parameter "params[\'brandRegistrationSid\']" missing.'); + } + + if (params["description"] === null || params["description"] === undefined) { + throw new Error('Required parameter "params[\'description\']" missing.'); + } + + if (params["messageFlow"] === null || params["messageFlow"] === undefined) { + throw new Error('Required parameter "params[\'messageFlow\']" missing.'); + } + + if (params["messageSamples"] === null || params["messageSamples"] === undefined) { + throw new Error('Required parameter "params[\'messageSamples\']" missing.'); + } + + if (params["usAppToPersonUsecase"] === null || params["usAppToPersonUsecase"] === undefined) { + throw new Error('Required parameter "params[\'usAppToPersonUsecase\']" missing.'); + } + + if (params["hasEmbeddedLinks"] === null || params["hasEmbeddedLinks"] === undefined) { + throw new Error('Required parameter "params[\'hasEmbeddedLinks\']" missing.'); + } + + if (params["hasEmbeddedPhone"] === null || params["hasEmbeddedPhone"] === undefined) { + throw new Error('Required parameter "params[\'hasEmbeddedPhone\']" missing.'); + } + + let data: any = {}; + + + + data["BrandRegistrationSid"] = params["brandRegistrationSid"]; + + data["Description"] = params["description"]; + + data["MessageFlow"] = params["messageFlow"]; + + data["MessageSamples"] = serialize.map(params["messageSamples"], (e: string) => (e)); + + data["UsAppToPersonUsecase"] = params["usAppToPersonUsecase"]; + + data["HasEmbeddedLinks"] = serialize.bool(params["hasEmbeddedLinks"]); + + data["HasEmbeddedPhone"] = serialize.bool(params["hasEmbeddedPhone"]); + if (params["optInMessage"] !== undefined) + data["OptInMessage"] = params["optInMessage"]; + if (params["optOutMessage"] !== undefined) + data["OptOutMessage"] = params["optOutMessage"]; + if (params["helpMessage"] !== undefined) + data["HelpMessage"] = params["helpMessage"]; + if (params["optInKeywords"] !== undefined) + data["OptInKeywords"] = serialize.map(params["optInKeywords"], (e: string) => (e)); + if (params["optOutKeywords"] !== undefined) + data["OptOutKeywords"] = serialize.map(params["optOutKeywords"], (e: string) => (e)); + if (params["helpKeywords"] !== undefined) + data["HelpKeywords"] = serialize.map(params["helpKeywords"], (e: string) => (e)); + if (params["subscriberOptIn"] !== undefined) + data["SubscriberOptIn"] = serialize.bool(params["subscriberOptIn"]); + if (params["ageGated"] !== undefined) + data["AgeGated"] = serialize.bool(params["ageGated"]); + if (params["directLending"] !== undefined) + data["DirectLending"] = serialize.bool(params["directLending"]); + if (params["privacyPolicyUrl"] !== undefined) + data["PrivacyPolicyUrl"] = params["privacyPolicyUrl"]; + if (params["termsAndConditionsUrl"] !== undefined) + data["TermsAndConditionsUrl"] = params["termsAndConditionsUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["xTwilioApiVersion"] !== undefined) headers["X-Twilio-Api-Version"] = params["xTwilioApiVersion"]; + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<UsAppToPersonResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<UsAppToPersonInstance> => ({ + ...response, + body: new UsAppToPersonInstance(operationVersion, response.body, instance._solution.messagingServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: UsAppToPersonListInstancePageOptions | ((error: Error | null, items: UsAppToPersonPage) => any), callback?: (error: Error | null, items: UsAppToPersonPage) => any): Promise<UsAppToPersonPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["xTwilioApiVersion"] !== undefined) headers["X-Twilio-Api-Version"] = params["xTwilioApiVersion"]; + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UsAppToPersonPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UsAppToPersonPage) => any): Promise<UsAppToPersonPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UsAppToPersonPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UsAppToPersonListInstancePageOptions | ((error: Error | null, items: ApiResponse<UsAppToPersonPage>) => any), callback?: (error: Error | null, items: ApiResponse<UsAppToPersonPage>) => any): Promise<ApiResponse<UsAppToPersonPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + if (params["xTwilioApiVersion"] !== undefined) headers["X-Twilio-Api-Version"] = params["xTwilioApiVersion"]; + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<UsAppToPersonPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UsAppToPersonPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<UsAppToPersonPage>) => any): Promise<ApiResponse<UsAppToPersonPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<UsAppToPersonPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UsAppToPersonPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UsAppToPersonPage extends Page<V1, UsAppToPersonPayload, UsAppToPersonResource, UsAppToPersonInstance> { +/** +* Initialize the UsAppToPersonPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: UsAppToPersonSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UsAppToPersonInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UsAppToPersonResource): UsAppToPersonInstance { + + return new UsAppToPersonInstance( + this._version, + payload, + this._solution.messagingServiceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v1/service/usAppToPersonUsecase.ts b/rest/messaging/v1/service/usAppToPersonUsecase.ts new file mode 100644 index 000000000..773777a81 --- /dev/null +++ b/rest/messaging/v1/service/usAppToPersonUsecase.ts @@ -0,0 +1,212 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a UsAppToPersonUsecaseInstance + */ +export interface UsAppToPersonUsecaseListInstanceFetchOptions { + /** The unique string to identify the A2P brand. */ + "brandRegistrationSid"?: string; +} + + +export interface UsAppToPersonUsecaseSolution { + messagingServiceSid: string; +} + +export interface UsAppToPersonUsecaseListInstance { + _version: V1; + _solution: UsAppToPersonUsecaseSolution; + _uri: string; + + + + /** + * Fetch a UsAppToPersonUsecaseInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonUsecaseInstance + */ + fetch(callback?: (error: Error | null, item?: UsAppToPersonUsecaseInstance) => any): Promise<UsAppToPersonUsecaseInstance>; + /** + * Fetch a UsAppToPersonUsecaseInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonUsecaseInstance + */ + fetch(params: UsAppToPersonUsecaseListInstanceFetchOptions, callback?: (error: Error | null, item?: UsAppToPersonUsecaseInstance) => any): Promise<UsAppToPersonUsecaseInstance>; + + /** + * Fetch a UsAppToPersonUsecaseInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonUsecaseInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonUsecaseInstance>) => any): Promise<ApiResponse<UsAppToPersonUsecaseInstance>>; + /** + * Fetch a UsAppToPersonUsecaseInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsAppToPersonUsecaseInstance with HTTP metadata + */ + fetchWithHttpInfo(params: UsAppToPersonUsecaseListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse<UsAppToPersonUsecaseInstance>) => any): Promise<ApiResponse<UsAppToPersonUsecaseInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UsAppToPersonUsecaseListInstance(version: V1, messagingServiceSid: string): UsAppToPersonUsecaseListInstance { + if (!isValidPathParam(messagingServiceSid)) { + throw new Error('Parameter \'messagingServiceSid\' is not valid.'); + } + + const instance = {} as UsAppToPersonUsecaseListInstance; + + instance._version = version; + instance._solution = { messagingServiceSid, }; + instance._uri = `/Services/${messagingServiceSid}/Compliance/Usa2p/Usecases`; + + instance.fetch = function fetch(params?: UsAppToPersonUsecaseListInstanceFetchOptions | ((error: Error | null, items: UsAppToPersonUsecaseInstance) => any), callback?: (error: Error | null, items: UsAppToPersonUsecaseInstance) => any): Promise<UsAppToPersonUsecaseInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["brandRegistrationSid"] !== undefined) + data["BrandRegistrationSid"] = params["brandRegistrationSid"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new UsAppToPersonUsecaseInstance(operationVersion, payload, instance._solution.messagingServiceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params?: UsAppToPersonUsecaseListInstanceFetchOptions | ((error: Error | null, items: ApiResponse<UsAppToPersonUsecaseInstance>) => any), callback?: (error: Error | null, items: ApiResponse<UsAppToPersonUsecaseInstance>) => any): Promise<ApiResponse<UsAppToPersonUsecaseInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["brandRegistrationSid"] !== undefined) + data["BrandRegistrationSid"] = params["brandRegistrationSid"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<UsAppToPersonUsecaseResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<UsAppToPersonUsecaseInstance> => ({ + ...response, + body: new UsAppToPersonUsecaseInstance(operationVersion, response.body, instance._solution.messagingServiceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface UsAppToPersonUsecasePayload extends UsAppToPersonUsecaseResource {} + +interface UsAppToPersonUsecaseResource { + us_app_to_person_usecases: Array<any>; +} + +export class UsAppToPersonUsecaseInstance { + + constructor(protected _version: V1, payload: UsAppToPersonUsecaseResource, messagingServiceSid: string) { + + this.usAppToPersonUsecases = (payload.us_app_to_person_usecases); + + } + + /** + * Human readable name, code, description and post_approval_required (indicates whether or not post approval is required for this Use Case) of A2P Campaign Use Cases. + */ + usAppToPersonUsecases: Array<any>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + usAppToPersonUsecases: this.usAppToPersonUsecases, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/messaging/v1/tollfreeVerification.ts b/rest/messaging/v1/tollfreeVerification.ts new file mode 100644 index 000000000..07b7b2078 --- /dev/null +++ b/rest/messaging/v1/tollfreeVerification.ts @@ -0,0 +1,1764 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The organizational authority for business registrations. Required for all business types except SOLE_PROPRIETOR. + */ +export type TollfreeVerificationBusinessRegistrationAuthority = 'EIN'|'CBN'|'CRN'|'PROVINCIAL_NUMBER'|'VAT'|'ACN'|'ABN'|'BRN'|'SIREN'|'SIRET'|'NZBN'|'USt-IdNr'|'CIF'|'NIF'|'CNPJ'|'UID'|'NEQ'|'OTHER'; + +/** + * The type of business, valid values are PRIVATE_PROFIT, PUBLIC_PROFIT, NON_PROFIT, SOLE_PROPRIETOR, GOVERNMENT. Required field. + */ +export type TollfreeVerificationBusinessType = 'PRIVATE_PROFIT'|'PUBLIC_PROFIT'|'SOLE_PROPRIETOR'|'NON_PROFIT'|'GOVERNMENT'; + +/** + * Describe how a user opts-in to text messages. + */ +export type TollfreeVerificationOptInType = 'VERBAL'|'WEB_FORM'|'PAPER_FORM'|'VIA_TEXT'|'MOBILE_QR_CODE'|'IMPORT'|'IMPORT_PLEASE_REPLACE'; + +/** + * The compliance status of the Tollfree Verification record. + */ +export type TollfreeVerificationStatus = 'PENDING_REVIEW'|'IN_REVIEW'|'TWILIO_APPROVED'|'TWILIO_REJECTED'; + +/** + * The third-party political vetting provider. + */ +export type TollfreeVerificationVettingProvider = 'CAMPAIGN_VERIFY'; + + + + +/** + * Options to pass to update a TollfreeVerificationInstance + */ +export interface TollfreeVerificationContextUpdateOptions { + /** The name of the business or organization using the Tollfree number. */ + "businessName"?: string; + /** The website of the business or organization using the Tollfree number. */ + "businessWebsite"?: string; + /** The email address to receive the notification about the verification result. . */ + "notificationEmail"?: string; + /** The category of the use case for the Tollfree Number. List as many as are applicable. */ + "useCaseCategories"?: Array<string>; + /** Use this to further explain how messaging is used by the business or organization. */ + "useCaseSummary"?: string; + /** An example of message content, i.e. a sample message. */ + "productionMessageSample"?: string; + /** Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. */ + "optInImageUrls"?: Array<string>; + /** */ + "optInType"?: TollfreeVerificationOptInType; + /** Estimate monthly volume of messages from the Tollfree Number. */ + "messageVolume"?: string; + /** The address of the business or organization using the Tollfree number. */ + "businessStreetAddress"?: string; + /** The address of the business or organization using the Tollfree number. */ + "businessStreetAddress2"?: string; + /** The city of the business or organization using the Tollfree number. */ + "businessCity"?: string; + /** The state/province/region of the business or organization using the Tollfree number. */ + "businessStateProvinceRegion"?: string; + /** The postal code of the business or organization using the Tollfree number. */ + "businessPostalCode"?: string; + /** The country of the business or organization using the Tollfree number. */ + "businessCountry"?: string; + /** Additional information to be provided for verification. */ + "additionalInformation"?: string; + /** The first name of the contact for the business or organization using the Tollfree number. */ + "businessContactFirstName"?: string; + /** The last name of the contact for the business or organization using the Tollfree number. */ + "businessContactLastName"?: string; + /** The email address of the contact for the business or organization using the Tollfree number. */ + "businessContactEmail"?: string; + /** The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. */ + "businessContactPhone"?: string; + /** Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to \\\'Website fixed\\\'. */ + "editReason"?: string; + /** A legally recognized business registration number */ + "businessRegistrationNumber"?: string; + /** */ + "businessRegistrationAuthority"?: TollfreeVerificationBusinessRegistrationAuthority; + /** Country business is registered in */ + "businessRegistrationCountry"?: string; + /** */ + "businessType"?: TollfreeVerificationBusinessType; + /** The E.164 formatted number associated with the business. */ + "businessRegistrationPhoneNumber"?: string; + /** Trade name, sub entity, or downstream business name of business being submitted for verification */ + "doingBusinessAs"?: string; + /** The confirmation message sent to users when they opt in to receive messages. */ + "optInConfirmationMessage"?: string; + /** A sample help message provided to users. */ + "helpMessageSample"?: string; + /** The URL to the privacy policy for the business or organization. */ + "privacyPolicyUrl"?: string; + /** The URL to the terms and conditions for the business or organization. */ + "termsAndConditionsUrl"?: string; + /** Indicates if the content is age gated. */ + "ageGatedContent"?: boolean; + /** List of keywords that users can text in to opt in to receive messages. */ + "optInKeywords"?: Array<string>; + /** */ + "vettingProvider"?: TollfreeVerificationVettingProvider; + /** The unique ID of the vetting */ + "vettingId"?: string; +} + +/** + * Options to pass to create a TollfreeVerificationInstance + */ +export interface TollfreeVerificationListInstanceCreateOptions { + /** The name of the business or organization using the Tollfree number. */ + "businessName": string; + /** The website of the business or organization using the Tollfree number. */ + "businessWebsite": string; + /** The email address to receive the notification about the verification result. . */ + "notificationEmail": string; + /** The category of the use case for the Tollfree Number. List as many as are applicable. */ + "useCaseCategories": Array<string>; + /** Use this to further explain how messaging is used by the business or organization. */ + "useCaseSummary": string; + /** An example of message content, i.e. a sample message. */ + "productionMessageSample": string; + /** Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. */ + "optInImageUrls": Array<string>; + /** */ + "optInType": TollfreeVerificationOptInType; + /** Estimate monthly volume of messages from the Tollfree Number. */ + "messageVolume": string; + /** The SID of the Phone Number associated with the Tollfree Verification. */ + "tollfreePhoneNumberSid": string; + /** Customer\\\'s Profile Bundle BundleSid. */ + "customerProfileSid"?: string; + /** The address of the business or organization using the Tollfree number. */ + "businessStreetAddress"?: string; + /** The address of the business or organization using the Tollfree number. */ + "businessStreetAddress2"?: string; + /** The city of the business or organization using the Tollfree number. */ + "businessCity"?: string; + /** The state/province/region of the business or organization using the Tollfree number. */ + "businessStateProvinceRegion"?: string; + /** The postal code of the business or organization using the Tollfree number. */ + "businessPostalCode"?: string; + /** The country of the business or organization using the Tollfree number. */ + "businessCountry"?: string; + /** Additional information to be provided for verification. */ + "additionalInformation"?: string; + /** The first name of the contact for the business or organization using the Tollfree number. */ + "businessContactFirstName"?: string; + /** The last name of the contact for the business or organization using the Tollfree number. */ + "businessContactLastName"?: string; + /** The email address of the contact for the business or organization using the Tollfree number. */ + "businessContactEmail"?: string; + /** The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. */ + "businessContactPhone"?: string; + /** An optional external reference ID supplied by customer and echoed back on status retrieval. */ + "externalReferenceId"?: string; + /** A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. */ + "businessRegistrationNumber"?: string; + /** */ + "businessRegistrationAuthority"?: TollfreeVerificationBusinessRegistrationAuthority; + /** The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. */ + "businessRegistrationCountry"?: string; + /** */ + "businessType"?: TollfreeVerificationBusinessType; + /** The E.164 formatted number associated with the business. */ + "businessRegistrationPhoneNumber"?: string; + /** Trade name, sub entity, or downstream business name of business being submitted for verification */ + "doingBusinessAs"?: string; + /** The confirmation message sent to users when they opt in to receive messages. */ + "optInConfirmationMessage"?: string; + /** A sample help message provided to users. */ + "helpMessageSample"?: string; + /** The URL to the privacy policy for the business or organization. */ + "privacyPolicyUrl"?: string; + /** The URL to the terms and conditions for the business or organization. */ + "termsAndConditionsUrl"?: string; + /** Indicates if the content is age gated. */ + "ageGatedContent"?: boolean; + /** List of keywords that users can text in to opt in to receive messages. */ + "optInKeywords"?: Array<string>; + /** */ + "vettingProvider"?: TollfreeVerificationVettingProvider; + /** The unique ID of the vetting */ + "vettingId"?: string; +} + +/** + * Options to pass to each + */ +export interface TollfreeVerificationListInstanceEachOptions { + /** The SID of the Phone Number associated with the Tollfree Verification. */ + "tollfreePhoneNumberSid"?: string; + /** The compliance status of the Tollfree Verification record. */ + "status"?: TollfreeVerificationStatus; + /** Customer supplied reference id for the Tollfree Verification record. */ + "externalReferenceId"?: string; + /** Whether to include Tollfree Verifications from sub accounts in list response. */ + "includeSubAccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** The trust product sids / tollfree bundle sids of tollfree verifications */ + "trustProductSid"?: Array<string>; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TollfreeVerificationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TollfreeVerificationListInstanceOptions { + /** The SID of the Phone Number associated with the Tollfree Verification. */ + "tollfreePhoneNumberSid"?: string; + /** The compliance status of the Tollfree Verification record. */ + "status"?: TollfreeVerificationStatus; + /** Customer supplied reference id for the Tollfree Verification record. */ + "externalReferenceId"?: string; + /** Whether to include Tollfree Verifications from sub accounts in list response. */ + "includeSubAccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** The trust product sids / tollfree bundle sids of tollfree verifications */ + "trustProductSid"?: Array<string>; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TollfreeVerificationListInstancePageOptions { + /** The SID of the Phone Number associated with the Tollfree Verification. */ + "tollfreePhoneNumberSid"?: string; + /** The compliance status of the Tollfree Verification record. */ + "status"?: TollfreeVerificationStatus; + /** Customer supplied reference id for the Tollfree Verification record. */ + "externalReferenceId"?: string; + /** Whether to include Tollfree Verifications from sub accounts in list response. */ + "includeSubAccounts"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** The trust product sids / tollfree bundle sids of tollfree verifications */ + "trustProductSid"?: Array<string>; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TollfreeVerificationContext { + + /** + * Remove a TollfreeVerificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a TollfreeVerificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a TollfreeVerificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance + */ + fetch(callback?: (error: Error | null, item?: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance> + + /** + * Fetch a TollfreeVerificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>> + + /** + * Update a TollfreeVerificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance + */ + update(callback?: (error: Error | null, item?: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance>; + /** + * Update a TollfreeVerificationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance + */ + update(params: TollfreeVerificationContextUpdateOptions, callback?: (error: Error | null, item?: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance>; + + /** + * Update a TollfreeVerificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>>; + /** + * Update a TollfreeVerificationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance with HTTP metadata + */ + updateWithHttpInfo(params: TollfreeVerificationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TollfreeVerificationContextSolution { + "sid": string; +} + +export class TollfreeVerificationContextImpl implements TollfreeVerificationContext { + protected _solution: TollfreeVerificationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Tollfree/Verifications/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TollfreeVerificationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TollfreeVerificationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TollfreeVerificationInstance> => ({ + ...response, + body: new TollfreeVerificationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: TollfreeVerificationContextUpdateOptions | ((error: Error | null, item?: TollfreeVerificationInstance) => any),callback?: (error: Error | null, item?: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["businessName"] !== undefined) + data["BusinessName"] = params["businessName"]; + if (params["businessWebsite"] !== undefined) + data["BusinessWebsite"] = params["businessWebsite"]; + if (params["notificationEmail"] !== undefined) + data["NotificationEmail"] = params["notificationEmail"]; + if (params["useCaseCategories"] !== undefined) + data["UseCaseCategories"] = serialize.map(params["useCaseCategories"], (e: string) => (e)); + if (params["useCaseSummary"] !== undefined) + data["UseCaseSummary"] = params["useCaseSummary"]; + if (params["productionMessageSample"] !== undefined) + data["ProductionMessageSample"] = params["productionMessageSample"]; + if (params["optInImageUrls"] !== undefined) + data["OptInImageUrls"] = serialize.map(params["optInImageUrls"], (e: string) => (e)); + if (params["optInType"] !== undefined) + data["OptInType"] = params["optInType"]; + if (params["messageVolume"] !== undefined) + data["MessageVolume"] = params["messageVolume"]; + if (params["businessStreetAddress"] !== undefined) + data["BusinessStreetAddress"] = params["businessStreetAddress"]; + if (params["businessStreetAddress2"] !== undefined) + data["BusinessStreetAddress2"] = params["businessStreetAddress2"]; + if (params["businessCity"] !== undefined) + data["BusinessCity"] = params["businessCity"]; + if (params["businessStateProvinceRegion"] !== undefined) + data["BusinessStateProvinceRegion"] = params["businessStateProvinceRegion"]; + if (params["businessPostalCode"] !== undefined) + data["BusinessPostalCode"] = params["businessPostalCode"]; + if (params["businessCountry"] !== undefined) + data["BusinessCountry"] = params["businessCountry"]; + if (params["additionalInformation"] !== undefined) + data["AdditionalInformation"] = params["additionalInformation"]; + if (params["businessContactFirstName"] !== undefined) + data["BusinessContactFirstName"] = params["businessContactFirstName"]; + if (params["businessContactLastName"] !== undefined) + data["BusinessContactLastName"] = params["businessContactLastName"]; + if (params["businessContactEmail"] !== undefined) + data["BusinessContactEmail"] = params["businessContactEmail"]; + if (params["businessContactPhone"] !== undefined) + data["BusinessContactPhone"] = params["businessContactPhone"]; + if (params["editReason"] !== undefined) + data["EditReason"] = params["editReason"]; + if (params["businessRegistrationNumber"] !== undefined) + data["BusinessRegistrationNumber"] = params["businessRegistrationNumber"]; + if (params["businessRegistrationAuthority"] !== undefined) + data["BusinessRegistrationAuthority"] = params["businessRegistrationAuthority"]; + if (params["businessRegistrationCountry"] !== undefined) + data["BusinessRegistrationCountry"] = params["businessRegistrationCountry"]; + if (params["businessType"] !== undefined) + data["BusinessType"] = params["businessType"]; + if (params["businessRegistrationPhoneNumber"] !== undefined) + data["BusinessRegistrationPhoneNumber"] = params["businessRegistrationPhoneNumber"]; + if (params["doingBusinessAs"] !== undefined) + data["DoingBusinessAs"] = params["doingBusinessAs"]; + if (params["optInConfirmationMessage"] !== undefined) + data["OptInConfirmationMessage"] = params["optInConfirmationMessage"]; + if (params["helpMessageSample"] !== undefined) + data["HelpMessageSample"] = params["helpMessageSample"]; + if (params["privacyPolicyUrl"] !== undefined) + data["PrivacyPolicyUrl"] = params["privacyPolicyUrl"]; + if (params["termsAndConditionsUrl"] !== undefined) + data["TermsAndConditionsUrl"] = params["termsAndConditionsUrl"]; + if (params["ageGatedContent"] !== undefined) + data["AgeGatedContent"] = serialize.bool(params["ageGatedContent"]); + if (params["optInKeywords"] !== undefined) + data["OptInKeywords"] = serialize.map(params["optInKeywords"], (e: string) => (e)); + if (params["vettingProvider"] !== undefined) + data["VettingProvider"] = params["vettingProvider"]; + if (params["vettingId"] !== undefined) + data["VettingId"] = params["vettingId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TollfreeVerificationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: TollfreeVerificationContextUpdateOptions | ((error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["businessName"] !== undefined) + data["BusinessName"] = params["businessName"]; + if (params["businessWebsite"] !== undefined) + data["BusinessWebsite"] = params["businessWebsite"]; + if (params["notificationEmail"] !== undefined) + data["NotificationEmail"] = params["notificationEmail"]; + if (params["useCaseCategories"] !== undefined) + data["UseCaseCategories"] = serialize.map(params["useCaseCategories"], (e: string) => (e)); + if (params["useCaseSummary"] !== undefined) + data["UseCaseSummary"] = params["useCaseSummary"]; + if (params["productionMessageSample"] !== undefined) + data["ProductionMessageSample"] = params["productionMessageSample"]; + if (params["optInImageUrls"] !== undefined) + data["OptInImageUrls"] = serialize.map(params["optInImageUrls"], (e: string) => (e)); + if (params["optInType"] !== undefined) + data["OptInType"] = params["optInType"]; + if (params["messageVolume"] !== undefined) + data["MessageVolume"] = params["messageVolume"]; + if (params["businessStreetAddress"] !== undefined) + data["BusinessStreetAddress"] = params["businessStreetAddress"]; + if (params["businessStreetAddress2"] !== undefined) + data["BusinessStreetAddress2"] = params["businessStreetAddress2"]; + if (params["businessCity"] !== undefined) + data["BusinessCity"] = params["businessCity"]; + if (params["businessStateProvinceRegion"] !== undefined) + data["BusinessStateProvinceRegion"] = params["businessStateProvinceRegion"]; + if (params["businessPostalCode"] !== undefined) + data["BusinessPostalCode"] = params["businessPostalCode"]; + if (params["businessCountry"] !== undefined) + data["BusinessCountry"] = params["businessCountry"]; + if (params["additionalInformation"] !== undefined) + data["AdditionalInformation"] = params["additionalInformation"]; + if (params["businessContactFirstName"] !== undefined) + data["BusinessContactFirstName"] = params["businessContactFirstName"]; + if (params["businessContactLastName"] !== undefined) + data["BusinessContactLastName"] = params["businessContactLastName"]; + if (params["businessContactEmail"] !== undefined) + data["BusinessContactEmail"] = params["businessContactEmail"]; + if (params["businessContactPhone"] !== undefined) + data["BusinessContactPhone"] = params["businessContactPhone"]; + if (params["editReason"] !== undefined) + data["EditReason"] = params["editReason"]; + if (params["businessRegistrationNumber"] !== undefined) + data["BusinessRegistrationNumber"] = params["businessRegistrationNumber"]; + if (params["businessRegistrationAuthority"] !== undefined) + data["BusinessRegistrationAuthority"] = params["businessRegistrationAuthority"]; + if (params["businessRegistrationCountry"] !== undefined) + data["BusinessRegistrationCountry"] = params["businessRegistrationCountry"]; + if (params["businessType"] !== undefined) + data["BusinessType"] = params["businessType"]; + if (params["businessRegistrationPhoneNumber"] !== undefined) + data["BusinessRegistrationPhoneNumber"] = params["businessRegistrationPhoneNumber"]; + if (params["doingBusinessAs"] !== undefined) + data["DoingBusinessAs"] = params["doingBusinessAs"]; + if (params["optInConfirmationMessage"] !== undefined) + data["OptInConfirmationMessage"] = params["optInConfirmationMessage"]; + if (params["helpMessageSample"] !== undefined) + data["HelpMessageSample"] = params["helpMessageSample"]; + if (params["privacyPolicyUrl"] !== undefined) + data["PrivacyPolicyUrl"] = params["privacyPolicyUrl"]; + if (params["termsAndConditionsUrl"] !== undefined) + data["TermsAndConditionsUrl"] = params["termsAndConditionsUrl"]; + if (params["ageGatedContent"] !== undefined) + data["AgeGatedContent"] = serialize.bool(params["ageGatedContent"]); + if (params["optInKeywords"] !== undefined) + data["OptInKeywords"] = serialize.map(params["optInKeywords"], (e: string) => (e)); + if (params["vettingProvider"] !== undefined) + data["VettingProvider"] = params["vettingProvider"]; + if (params["vettingId"] !== undefined) + data["VettingId"] = params["vettingId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<TollfreeVerificationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TollfreeVerificationInstance> => ({ + ...response, + body: new TollfreeVerificationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TollfreeVerificationPayload extends TwilioResponsePayload { + verifications: TollfreeVerificationResource[]; +} + +interface TollfreeVerificationResource { + sid: string; + account_sid: string; + customer_profile_sid: string; + trust_product_sid: string; + date_created: Date; + date_updated: Date; + regulated_item_sid: string; + business_name: string; + business_street_address: string; + business_street_address2: string; + business_city: string; + business_state_province_region: string; + business_postal_code: string; + business_country: string; + business_website: string; + business_contact_first_name: string; + business_contact_last_name: string; + business_contact_email: string; + business_contact_phone: string; + notification_email: string; + use_case_categories: Array<string>; + use_case_summary: string; + production_message_sample: string; + opt_in_image_urls: Array<string>; + opt_in_type: TollfreeVerificationOptInType; + message_volume: string; + additional_information: string; + tollfree_phone_number_sid: string; + tollfree_phone_number: string; + status: TollfreeVerificationStatus; + url: string; + rejection_reason: string; + error_code: number; + edit_expiration: Date; + edit_allowed: boolean; + business_registration_number: string; + business_registration_authority: TollfreeVerificationBusinessRegistrationAuthority; + business_registration_country: string; + business_type: TollfreeVerificationBusinessType; + business_registration_phone_number: string; + doing_business_as: string; + opt_in_confirmation_message: string; + help_message_sample: string; + privacy_policy_url: string; + terms_and_conditions_url: string; + age_gated_content: boolean; + opt_in_keywords: Array<string>; + rejection_reasons: Array<any>; + resource_links: any; + external_reference_id: string; + vetting_id: string; + vetting_provider: TollfreeVerificationVettingProvider; + vetting_id_expiration: Date; +} + +export class TollfreeVerificationInstance { + protected _solution: TollfreeVerificationContextSolution; + protected _context?: TollfreeVerificationContext; + + constructor(protected _version: V1, payload: TollfreeVerificationResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.customerProfileSid = (payload.customer_profile_sid); + this.trustProductSid = (payload.trust_product_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.regulatedItemSid = (payload.regulated_item_sid); + this.businessName = (payload.business_name); + this.businessStreetAddress = (payload.business_street_address); + this.businessStreetAddress2 = (payload.business_street_address2); + this.businessCity = (payload.business_city); + this.businessStateProvinceRegion = (payload.business_state_province_region); + this.businessPostalCode = (payload.business_postal_code); + this.businessCountry = (payload.business_country); + this.businessWebsite = (payload.business_website); + this.businessContactFirstName = (payload.business_contact_first_name); + this.businessContactLastName = (payload.business_contact_last_name); + this.businessContactEmail = (payload.business_contact_email); + this.businessContactPhone = (payload.business_contact_phone); + this.notificationEmail = (payload.notification_email); + this.useCaseCategories = (payload.use_case_categories); + this.useCaseSummary = (payload.use_case_summary); + this.productionMessageSample = (payload.production_message_sample); + this.optInImageUrls = (payload.opt_in_image_urls); + this.optInType = payload.opt_in_type; + this.messageVolume = (payload.message_volume); + this.additionalInformation = (payload.additional_information); + this.tollfreePhoneNumberSid = (payload.tollfree_phone_number_sid); + this.tollfreePhoneNumber = (payload.tollfree_phone_number); + this.status = payload.status; + this.url = (payload.url); + this.rejectionReason = (payload.rejection_reason); + this.errorCode = deserialize.integer(payload.error_code); + this.editExpiration = deserialize.iso8601DateTime(payload.edit_expiration); + this.editAllowed = (payload.edit_allowed); + this.businessRegistrationNumber = (payload.business_registration_number); + this.businessRegistrationAuthority = payload.business_registration_authority; + this.businessRegistrationCountry = (payload.business_registration_country); + this.businessType = payload.business_type; + this.businessRegistrationPhoneNumber = (payload.business_registration_phone_number); + this.doingBusinessAs = (payload.doing_business_as); + this.optInConfirmationMessage = (payload.opt_in_confirmation_message); + this.helpMessageSample = (payload.help_message_sample); + this.privacyPolicyUrl = (payload.privacy_policy_url); + this.termsAndConditionsUrl = (payload.terms_and_conditions_url); + this.ageGatedContent = (payload.age_gated_content); + this.optInKeywords = (payload.opt_in_keywords); + this.rejectionReasons = (payload.rejection_reasons); + this.resourceLinks = (payload.resource_links); + this.externalReferenceId = (payload.external_reference_id); + this.vettingId = (payload.vetting_id); + this.vettingProvider = payload.vetting_provider; + this.vettingIdExpiration = deserialize.iso8601DateTime(payload.vetting_id_expiration); + + this._solution = { sid: sid, }; + } + + /** + * The unique string to identify Tollfree Verification. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tollfree Verification resource. + */ + accountSid: string; + /** + * Customer\'s Profile Bundle BundleSid. + */ + customerProfileSid: string; + /** + * Tollfree TrustProduct Bundle BundleSid. + */ + trustProductSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The SID of the Regulated Item. + */ + regulatedItemSid: string; + /** + * The name of the business or organization using the Tollfree number. + */ + businessName: string; + /** + * The address of the business or organization using the Tollfree number. + */ + businessStreetAddress: string; + /** + * The address of the business or organization using the Tollfree number. + */ + businessStreetAddress2: string; + /** + * The city of the business or organization using the Tollfree number. + */ + businessCity: string; + /** + * The state/province/region of the business or organization using the Tollfree number. + */ + businessStateProvinceRegion: string; + /** + * The postal code of the business or organization using the Tollfree number. + */ + businessPostalCode: string; + /** + * The country of the business or organization using the Tollfree number. + */ + businessCountry: string; + /** + * The website of the business or organization using the Tollfree number. + */ + businessWebsite: string; + /** + * The first name of the contact for the business or organization using the Tollfree number. + */ + businessContactFirstName: string; + /** + * The last name of the contact for the business or organization using the Tollfree number. + */ + businessContactLastName: string; + /** + * The email address of the contact for the business or organization using the Tollfree number. + */ + businessContactEmail: string; + /** + * The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + */ + businessContactPhone: string; + /** + * The email address to receive the notification about the verification result. . + */ + notificationEmail: string; + /** + * The category of the use case for the Tollfree Number. List as many as are applicable. + */ + useCaseCategories: Array<string>; + /** + * Use this to further explain how messaging is used by the business or organization. + */ + useCaseSummary: string; + /** + * An example of message content, i.e. a sample message. + */ + productionMessageSample: string; + /** + * Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + */ + optInImageUrls: Array<string>; + optInType: TollfreeVerificationOptInType; + /** + * Estimate monthly volume of messages from the Tollfree Number. + */ + messageVolume: string; + /** + * Additional information to be provided for verification. + */ + additionalInformation: string; + /** + * The SID of the Phone Number associated with the Tollfree Verification. + */ + tollfreePhoneNumberSid: string; + /** + * The E.164 formatted toll-free phone number associated with the verification. + */ + tollfreePhoneNumber: string; + status: TollfreeVerificationStatus; + /** + * The absolute URL of the Tollfree Verification resource. + */ + url: string; + /** + * The rejection reason given when a Tollfree Verification has been rejected. + */ + rejectionReason: string; + /** + * The error code given when a Tollfree Verification has been rejected. + */ + errorCode: number; + /** + * The date and time when the ability to edit a rejected verification expires. + */ + editExpiration: Date; + /** + * If a rejected verification is allowed to be edited/resubmitted. Some rejection reasons allow editing and some do not. + */ + editAllowed: boolean; + /** + * A legally recognized business registration number + */ + businessRegistrationNumber: string; + businessRegistrationAuthority: TollfreeVerificationBusinessRegistrationAuthority; + /** + * Country business is registered in + */ + businessRegistrationCountry: string; + businessType: TollfreeVerificationBusinessType; + /** + * The E.164 formatted number associated with the business. + */ + businessRegistrationPhoneNumber: string; + /** + * Trade name, sub entity, or downstream business name of business being submitted for verification + */ + doingBusinessAs: string; + /** + * The confirmation message sent to users when they opt in to receive messages. + */ + optInConfirmationMessage: string; + /** + * A sample help message provided to users. + */ + helpMessageSample: string; + /** + * The URL to the privacy policy for the business or organization. + */ + privacyPolicyUrl: string; + /** + * The URL of the terms and conditions for the business or organization. + */ + termsAndConditionsUrl: string; + /** + * Indicates if the content is age gated. + */ + ageGatedContent: boolean; + /** + * List of keywords that users can send to opt in or out of messages. + */ + optInKeywords: Array<string>; + /** + * A list of rejection reasons and codes describing why a Tollfree Verification has been rejected. + */ + rejectionReasons: Array<any>; + /** + * The URLs of the documents associated with the Tollfree Verification resource. + */ + resourceLinks: any; + /** + * An optional external reference ID supplied by customer and echoed back on status retrieval. + */ + externalReferenceId: string; + vettingId: string; + vettingProvider: TollfreeVerificationVettingProvider; + vettingIdExpiration: Date; + + private get _proxy(): TollfreeVerificationContext { + this._context = this._context || new TollfreeVerificationContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a TollfreeVerificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TollfreeVerificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TollfreeVerificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance + */ + fetch(callback?: (error: Error | null, item?: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TollfreeVerificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TollfreeVerificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance + */ + update(callback?: (error: Error | null, item?: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance>; + /** + * Update a TollfreeVerificationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance + */ + update(params: TollfreeVerificationContextUpdateOptions, callback?: (error: Error | null, item?: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance>; + + update(params?: any, callback?: (error: Error | null, item?: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a TollfreeVerificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>>; + /** + * Update a TollfreeVerificationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance with HTTP metadata + */ + updateWithHttpInfo(params: TollfreeVerificationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + customerProfileSid: this.customerProfileSid, + trustProductSid: this.trustProductSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + regulatedItemSid: this.regulatedItemSid, + businessName: this.businessName, + businessStreetAddress: this.businessStreetAddress, + businessStreetAddress2: this.businessStreetAddress2, + businessCity: this.businessCity, + businessStateProvinceRegion: this.businessStateProvinceRegion, + businessPostalCode: this.businessPostalCode, + businessCountry: this.businessCountry, + businessWebsite: this.businessWebsite, + businessContactFirstName: this.businessContactFirstName, + businessContactLastName: this.businessContactLastName, + businessContactEmail: this.businessContactEmail, + businessContactPhone: this.businessContactPhone, + notificationEmail: this.notificationEmail, + useCaseCategories: this.useCaseCategories, + useCaseSummary: this.useCaseSummary, + productionMessageSample: this.productionMessageSample, + optInImageUrls: this.optInImageUrls, + optInType: this.optInType, + messageVolume: this.messageVolume, + additionalInformation: this.additionalInformation, + tollfreePhoneNumberSid: this.tollfreePhoneNumberSid, + tollfreePhoneNumber: this.tollfreePhoneNumber, + status: this.status, + url: this.url, + rejectionReason: this.rejectionReason, + errorCode: this.errorCode, + editExpiration: this.editExpiration, + editAllowed: this.editAllowed, + businessRegistrationNumber: this.businessRegistrationNumber, + businessRegistrationAuthority: this.businessRegistrationAuthority, + businessRegistrationCountry: this.businessRegistrationCountry, + businessType: this.businessType, + businessRegistrationPhoneNumber: this.businessRegistrationPhoneNumber, + doingBusinessAs: this.doingBusinessAs, + optInConfirmationMessage: this.optInConfirmationMessage, + helpMessageSample: this.helpMessageSample, + privacyPolicyUrl: this.privacyPolicyUrl, + termsAndConditionsUrl: this.termsAndConditionsUrl, + ageGatedContent: this.ageGatedContent, + optInKeywords: this.optInKeywords, + rejectionReasons: this.rejectionReasons, + resourceLinks: this.resourceLinks, + externalReferenceId: this.externalReferenceId, + vettingId: this.vettingId, + vettingProvider: this.vettingProvider, + vettingIdExpiration: this.vettingIdExpiration, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TollfreeVerificationSolution { +} + +export interface TollfreeVerificationListInstance { + _version: V1; + _solution: TollfreeVerificationSolution; + _uri: string; + + (sid: string, ): TollfreeVerificationContext; + get(sid: string, ): TollfreeVerificationContext; + + + + + + + + + /** + * Create a TollfreeVerificationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance + */ + create(params: TollfreeVerificationListInstanceCreateOptions, callback?: (error: Error | null, item?: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance>; + + /** + * Create a TollfreeVerificationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TollfreeVerificationInstance with HTTP metadata + */ + createWithHttpInfo(params: TollfreeVerificationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>>; + + + + + /** + * Streams TollfreeVerificationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollfreeVerificationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TollfreeVerificationInstance, done: (err?: Error) => void) => void): void; + each(params: TollfreeVerificationListInstanceEachOptions, callback?: (item: TollfreeVerificationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TollfreeVerificationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollfreeVerificationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TollfreeVerificationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TollfreeVerificationListInstanceEachOptions, callback?: (item: TollfreeVerificationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TollfreeVerificationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TollfreeVerificationPage) => any): Promise<TollfreeVerificationPage>; + /** + * Retrieve a single target page of TollfreeVerificationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TollfreeVerificationPage>) => any): Promise<ApiResponse<TollfreeVerificationPage>>; + /** + * Lists TollfreeVerificationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollfreeVerificationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TollfreeVerificationInstance[]) => any): Promise<TollfreeVerificationInstance[]>; + list(params: TollfreeVerificationListInstanceOptions, callback?: (error: Error | null, items: TollfreeVerificationInstance[]) => any): Promise<TollfreeVerificationInstance[]>; + /** + * Lists TollfreeVerificationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollfreeVerificationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TollfreeVerificationInstance[]>) => any): Promise<ApiResponse<TollfreeVerificationInstance[]>>; + listWithHttpInfo(params: TollfreeVerificationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TollfreeVerificationInstance[]>) => any): Promise<ApiResponse<TollfreeVerificationInstance[]>>; + /** + * Retrieve a single page of TollfreeVerificationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollfreeVerificationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TollfreeVerificationPage) => any): Promise<TollfreeVerificationPage>; + page(params: TollfreeVerificationListInstancePageOptions, callback?: (error: Error | null, items: TollfreeVerificationPage) => any): Promise<TollfreeVerificationPage>; + /** + * Retrieve a single page of TollfreeVerificationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TollfreeVerificationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TollfreeVerificationPage>) => any): Promise<ApiResponse<TollfreeVerificationPage>>; + pageWithHttpInfo(params: TollfreeVerificationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TollfreeVerificationPage>) => any): Promise<ApiResponse<TollfreeVerificationPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TollfreeVerificationListInstance(version: V1): TollfreeVerificationListInstance { + const instance = ((sid, ) => instance.get(sid, )) as TollfreeVerificationListInstance; + + instance.get = function get(sid, ): TollfreeVerificationContext { + return new TollfreeVerificationContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Tollfree/Verifications`; + + instance.create = function create(params: TollfreeVerificationListInstanceCreateOptions, callback?: (error: Error | null, items: TollfreeVerificationInstance) => any): Promise<TollfreeVerificationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["businessName"] === null || params["businessName"] === undefined) { + throw new Error('Required parameter "params[\'businessName\']" missing.'); + } + + if (params["businessWebsite"] === null || params["businessWebsite"] === undefined) { + throw new Error('Required parameter "params[\'businessWebsite\']" missing.'); + } + + if (params["notificationEmail"] === null || params["notificationEmail"] === undefined) { + throw new Error('Required parameter "params[\'notificationEmail\']" missing.'); + } + + if (params["useCaseCategories"] === null || params["useCaseCategories"] === undefined) { + throw new Error('Required parameter "params[\'useCaseCategories\']" missing.'); + } + + if (params["useCaseSummary"] === null || params["useCaseSummary"] === undefined) { + throw new Error('Required parameter "params[\'useCaseSummary\']" missing.'); + } + + if (params["productionMessageSample"] === null || params["productionMessageSample"] === undefined) { + throw new Error('Required parameter "params[\'productionMessageSample\']" missing.'); + } + + if (params["optInImageUrls"] === null || params["optInImageUrls"] === undefined) { + throw new Error('Required parameter "params[\'optInImageUrls\']" missing.'); + } + + if (params["optInType"] === null || params["optInType"] === undefined) { + throw new Error('Required parameter "params[\'optInType\']" missing.'); + } + + if (params["messageVolume"] === null || params["messageVolume"] === undefined) { + throw new Error('Required parameter "params[\'messageVolume\']" missing.'); + } + + if (params["tollfreePhoneNumberSid"] === null || params["tollfreePhoneNumberSid"] === undefined) { + throw new Error('Required parameter "params[\'tollfreePhoneNumberSid\']" missing.'); + } + + let data: any = {}; + + + + data["BusinessName"] = params["businessName"]; + + data["BusinessWebsite"] = params["businessWebsite"]; + + data["NotificationEmail"] = params["notificationEmail"]; + + data["UseCaseCategories"] = serialize.map(params["useCaseCategories"], (e: string) => (e)); + + data["UseCaseSummary"] = params["useCaseSummary"]; + + data["ProductionMessageSample"] = params["productionMessageSample"]; + + data["OptInImageUrls"] = serialize.map(params["optInImageUrls"], (e: string) => (e)); + + data["OptInType"] = params["optInType"]; + + data["MessageVolume"] = params["messageVolume"]; + + data["TollfreePhoneNumberSid"] = params["tollfreePhoneNumberSid"]; + if (params["customerProfileSid"] !== undefined) + data["CustomerProfileSid"] = params["customerProfileSid"]; + if (params["businessStreetAddress"] !== undefined) + data["BusinessStreetAddress"] = params["businessStreetAddress"]; + if (params["businessStreetAddress2"] !== undefined) + data["BusinessStreetAddress2"] = params["businessStreetAddress2"]; + if (params["businessCity"] !== undefined) + data["BusinessCity"] = params["businessCity"]; + if (params["businessStateProvinceRegion"] !== undefined) + data["BusinessStateProvinceRegion"] = params["businessStateProvinceRegion"]; + if (params["businessPostalCode"] !== undefined) + data["BusinessPostalCode"] = params["businessPostalCode"]; + if (params["businessCountry"] !== undefined) + data["BusinessCountry"] = params["businessCountry"]; + if (params["additionalInformation"] !== undefined) + data["AdditionalInformation"] = params["additionalInformation"]; + if (params["businessContactFirstName"] !== undefined) + data["BusinessContactFirstName"] = params["businessContactFirstName"]; + if (params["businessContactLastName"] !== undefined) + data["BusinessContactLastName"] = params["businessContactLastName"]; + if (params["businessContactEmail"] !== undefined) + data["BusinessContactEmail"] = params["businessContactEmail"]; + if (params["businessContactPhone"] !== undefined) + data["BusinessContactPhone"] = params["businessContactPhone"]; + if (params["externalReferenceId"] !== undefined) + data["ExternalReferenceId"] = params["externalReferenceId"]; + if (params["businessRegistrationNumber"] !== undefined) + data["BusinessRegistrationNumber"] = params["businessRegistrationNumber"]; + if (params["businessRegistrationAuthority"] !== undefined) + data["BusinessRegistrationAuthority"] = params["businessRegistrationAuthority"]; + if (params["businessRegistrationCountry"] !== undefined) + data["BusinessRegistrationCountry"] = params["businessRegistrationCountry"]; + if (params["businessType"] !== undefined) + data["BusinessType"] = params["businessType"]; + if (params["businessRegistrationPhoneNumber"] !== undefined) + data["BusinessRegistrationPhoneNumber"] = params["businessRegistrationPhoneNumber"]; + if (params["doingBusinessAs"] !== undefined) + data["DoingBusinessAs"] = params["doingBusinessAs"]; + if (params["optInConfirmationMessage"] !== undefined) + data["OptInConfirmationMessage"] = params["optInConfirmationMessage"]; + if (params["helpMessageSample"] !== undefined) + data["HelpMessageSample"] = params["helpMessageSample"]; + if (params["privacyPolicyUrl"] !== undefined) + data["PrivacyPolicyUrl"] = params["privacyPolicyUrl"]; + if (params["termsAndConditionsUrl"] !== undefined) + data["TermsAndConditionsUrl"] = params["termsAndConditionsUrl"]; + if (params["ageGatedContent"] !== undefined) + data["AgeGatedContent"] = serialize.bool(params["ageGatedContent"]); + if (params["optInKeywords"] !== undefined) + data["OptInKeywords"] = serialize.map(params["optInKeywords"], (e: string) => (e)); + if (params["vettingProvider"] !== undefined) + data["VettingProvider"] = params["vettingProvider"]; + if (params["vettingId"] !== undefined) + data["VettingId"] = params["vettingId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TollfreeVerificationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TollfreeVerificationListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<TollfreeVerificationInstance>) => any): Promise<ApiResponse<TollfreeVerificationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["businessName"] === null || params["businessName"] === undefined) { + throw new Error('Required parameter "params[\'businessName\']" missing.'); + } + + if (params["businessWebsite"] === null || params["businessWebsite"] === undefined) { + throw new Error('Required parameter "params[\'businessWebsite\']" missing.'); + } + + if (params["notificationEmail"] === null || params["notificationEmail"] === undefined) { + throw new Error('Required parameter "params[\'notificationEmail\']" missing.'); + } + + if (params["useCaseCategories"] === null || params["useCaseCategories"] === undefined) { + throw new Error('Required parameter "params[\'useCaseCategories\']" missing.'); + } + + if (params["useCaseSummary"] === null || params["useCaseSummary"] === undefined) { + throw new Error('Required parameter "params[\'useCaseSummary\']" missing.'); + } + + if (params["productionMessageSample"] === null || params["productionMessageSample"] === undefined) { + throw new Error('Required parameter "params[\'productionMessageSample\']" missing.'); + } + + if (params["optInImageUrls"] === null || params["optInImageUrls"] === undefined) { + throw new Error('Required parameter "params[\'optInImageUrls\']" missing.'); + } + + if (params["optInType"] === null || params["optInType"] === undefined) { + throw new Error('Required parameter "params[\'optInType\']" missing.'); + } + + if (params["messageVolume"] === null || params["messageVolume"] === undefined) { + throw new Error('Required parameter "params[\'messageVolume\']" missing.'); + } + + if (params["tollfreePhoneNumberSid"] === null || params["tollfreePhoneNumberSid"] === undefined) { + throw new Error('Required parameter "params[\'tollfreePhoneNumberSid\']" missing.'); + } + + let data: any = {}; + + + + data["BusinessName"] = params["businessName"]; + + data["BusinessWebsite"] = params["businessWebsite"]; + + data["NotificationEmail"] = params["notificationEmail"]; + + data["UseCaseCategories"] = serialize.map(params["useCaseCategories"], (e: string) => (e)); + + data["UseCaseSummary"] = params["useCaseSummary"]; + + data["ProductionMessageSample"] = params["productionMessageSample"]; + + data["OptInImageUrls"] = serialize.map(params["optInImageUrls"], (e: string) => (e)); + + data["OptInType"] = params["optInType"]; + + data["MessageVolume"] = params["messageVolume"]; + + data["TollfreePhoneNumberSid"] = params["tollfreePhoneNumberSid"]; + if (params["customerProfileSid"] !== undefined) + data["CustomerProfileSid"] = params["customerProfileSid"]; + if (params["businessStreetAddress"] !== undefined) + data["BusinessStreetAddress"] = params["businessStreetAddress"]; + if (params["businessStreetAddress2"] !== undefined) + data["BusinessStreetAddress2"] = params["businessStreetAddress2"]; + if (params["businessCity"] !== undefined) + data["BusinessCity"] = params["businessCity"]; + if (params["businessStateProvinceRegion"] !== undefined) + data["BusinessStateProvinceRegion"] = params["businessStateProvinceRegion"]; + if (params["businessPostalCode"] !== undefined) + data["BusinessPostalCode"] = params["businessPostalCode"]; + if (params["businessCountry"] !== undefined) + data["BusinessCountry"] = params["businessCountry"]; + if (params["additionalInformation"] !== undefined) + data["AdditionalInformation"] = params["additionalInformation"]; + if (params["businessContactFirstName"] !== undefined) + data["BusinessContactFirstName"] = params["businessContactFirstName"]; + if (params["businessContactLastName"] !== undefined) + data["BusinessContactLastName"] = params["businessContactLastName"]; + if (params["businessContactEmail"] !== undefined) + data["BusinessContactEmail"] = params["businessContactEmail"]; + if (params["businessContactPhone"] !== undefined) + data["BusinessContactPhone"] = params["businessContactPhone"]; + if (params["externalReferenceId"] !== undefined) + data["ExternalReferenceId"] = params["externalReferenceId"]; + if (params["businessRegistrationNumber"] !== undefined) + data["BusinessRegistrationNumber"] = params["businessRegistrationNumber"]; + if (params["businessRegistrationAuthority"] !== undefined) + data["BusinessRegistrationAuthority"] = params["businessRegistrationAuthority"]; + if (params["businessRegistrationCountry"] !== undefined) + data["BusinessRegistrationCountry"] = params["businessRegistrationCountry"]; + if (params["businessType"] !== undefined) + data["BusinessType"] = params["businessType"]; + if (params["businessRegistrationPhoneNumber"] !== undefined) + data["BusinessRegistrationPhoneNumber"] = params["businessRegistrationPhoneNumber"]; + if (params["doingBusinessAs"] !== undefined) + data["DoingBusinessAs"] = params["doingBusinessAs"]; + if (params["optInConfirmationMessage"] !== undefined) + data["OptInConfirmationMessage"] = params["optInConfirmationMessage"]; + if (params["helpMessageSample"] !== undefined) + data["HelpMessageSample"] = params["helpMessageSample"]; + if (params["privacyPolicyUrl"] !== undefined) + data["PrivacyPolicyUrl"] = params["privacyPolicyUrl"]; + if (params["termsAndConditionsUrl"] !== undefined) + data["TermsAndConditionsUrl"] = params["termsAndConditionsUrl"]; + if (params["ageGatedContent"] !== undefined) + data["AgeGatedContent"] = serialize.bool(params["ageGatedContent"]); + if (params["optInKeywords"] !== undefined) + data["OptInKeywords"] = serialize.map(params["optInKeywords"], (e: string) => (e)); + if (params["vettingProvider"] !== undefined) + data["VettingProvider"] = params["vettingProvider"]; + if (params["vettingId"] !== undefined) + data["VettingId"] = params["vettingId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TollfreeVerificationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TollfreeVerificationInstance> => ({ + ...response, + body: new TollfreeVerificationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TollfreeVerificationListInstancePageOptions | ((error: Error | null, items: TollfreeVerificationPage) => any), callback?: (error: Error | null, items: TollfreeVerificationPage) => any): Promise<TollfreeVerificationPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["tollfreePhoneNumberSid"] !== undefined) + data["TollfreePhoneNumberSid"] = params["tollfreePhoneNumberSid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["externalReferenceId"] !== undefined) + data["ExternalReferenceId"] = params["externalReferenceId"]; + if (params["includeSubAccounts"] !== undefined) + data["IncludeSubAccounts"] = serialize.bool(params["includeSubAccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["trustProductSid"] !== undefined) + data["TrustProductSid"] = serialize.map(params["trustProductSid"], (e: string) => (e)); + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TollfreeVerificationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TollfreeVerificationPage) => any): Promise<TollfreeVerificationPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TollfreeVerificationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TollfreeVerificationListInstancePageOptions | ((error: Error | null, items: ApiResponse<TollfreeVerificationPage>) => any), callback?: (error: Error | null, items: ApiResponse<TollfreeVerificationPage>) => any): Promise<ApiResponse<TollfreeVerificationPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["tollfreePhoneNumberSid"] !== undefined) + data["TollfreePhoneNumberSid"] = params["tollfreePhoneNumberSid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["externalReferenceId"] !== undefined) + data["ExternalReferenceId"] = params["externalReferenceId"]; + if (params["includeSubAccounts"] !== undefined) + data["IncludeSubAccounts"] = serialize.bool(params["includeSubAccounts"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["trustProductSid"] !== undefined) + data["TrustProductSid"] = serialize.map(params["trustProductSid"], (e: string) => (e)); + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TollfreeVerificationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TollfreeVerificationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TollfreeVerificationPage>) => any): Promise<ApiResponse<TollfreeVerificationPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TollfreeVerificationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TollfreeVerificationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TollfreeVerificationPage extends Page<V1, TollfreeVerificationPayload, TollfreeVerificationResource, TollfreeVerificationInstance> { +/** +* Initialize the TollfreeVerificationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TollfreeVerificationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TollfreeVerificationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TollfreeVerificationResource): TollfreeVerificationInstance { + + return new TollfreeVerificationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v1/usecase.ts b/rest/messaging/v1/usecase.ts new file mode 100644 index 000000000..cc8fdb108 --- /dev/null +++ b/rest/messaging/v1/usecase.ts @@ -0,0 +1,150 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface UsecaseSolution { +} + +export interface UsecaseListInstance { + _version: V1; + _solution: UsecaseSolution; + _uri: string; + + + + /** + * Fetch a UsecaseInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsecaseInstance + */ + fetch(callback?: (error: Error | null, item?: UsecaseInstance) => any): Promise<UsecaseInstance> + + /** + * Fetch a UsecaseInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsecaseInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UsecaseInstance>) => any): Promise<ApiResponse<UsecaseInstance>> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UsecaseListInstance(version: V1): UsecaseListInstance { + const instance = {} as UsecaseListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services/Usecases`; + + instance.fetch = function fetch( callback?: (error: Error | null, items: UsecaseInstance) => any): Promise<UsecaseInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UsecaseInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<UsecaseInstance>) => any): Promise<ApiResponse<UsecaseInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<UsecaseResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<UsecaseInstance> => ({ + ...response, + body: new UsecaseInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface UsecasePayload extends UsecaseResource {} + +interface UsecaseResource { + usecases: Array<any>; +} + +export class UsecaseInstance { + + constructor(protected _version: V1, payload: UsecaseResource) { + + this.usecases = (payload.usecases); + + } + + /** + * Human readable use case details (usecase, description and purpose) of Messaging Service Use Cases. + */ + usecases: Array<any>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + usecases: this.usecases, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/messaging/v2/channelsSender.ts b/rest/messaging/v2/channelsSender.ts new file mode 100644 index 000000000..cd10ca67c --- /dev/null +++ b/rest/messaging/v2/channelsSender.ts @@ -0,0 +1,1339 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The status of the sender. + */ +export type ChannelsSenderStatus = 'CREATING'|'ONLINE'|'OFFLINE'|'PENDING_VERIFICATION'|'VERIFYING'|'ONLINE:UPDATING'|'TWILIO_REVIEW'|'DRAFT'|'STUBBED'; + +/** + * The configuration settings for creating a sender. + */ +export class MessagingV2ChannelsSenderConfiguration { + /** + * The ID of the WhatsApp Business Account (WABA) to use for this sender. + */ + "wabaId"?: string | null; + /** + * The verification method. + */ + "verificationMethod"?: string | null; + /** + * The verification code. + */ + "verificationCode"?: string | null; + /** + * The SID of the Twilio Voice application. + */ + "voiceApplicationSid"?: string | null; + /** + * The account type for ISV Account Type Migration. Set to \'ISV\' or \'ISVSubAccount\' to configure, empty string to clear, or omit to preserve the existing value. + */ + "accountType"?: string | null; + + constructor(payload) { + this.wabaId = payload["waba_id"]; + this.verificationMethod = payload["verification_method"]; + this.verificationCode = payload["verification_code"]; + this.voiceApplicationSid = payload["voice_application_sid"]; + this.accountType = payload["account_type"]; + } +} + + +export class MessagingV2ChannelsSenderOfflineReasonsItems { + /** + * The error code. + */ + "code"?: string | null; + /** + * The error message. + */ + "message"?: string | null; + /** + * The URL to get more information about the error. + */ + "moreInfo"?: string | null; + + constructor(payload) { + this.code = payload["code"]; + this.message = payload["message"]; + this.moreInfo = payload["more_info"]; + } +} + + +/** + * The profile information for the sender. + */ +export class MessagingV2ChannelsSenderProfile { + /** + * The name of the sender. Required for WhatsApp senders and must follow [Meta\'s display name guidelines](https://www.facebook.com/business/help/757569725593362). + */ + "name"?: string | null; + /** + * The profile about text for the sender. + */ + "about"?: string | null; + /** + * The address of the sender. + */ + "address"?: string | null; + /** + * The description of the sender. + */ + "description"?: string | null; + /** + * The logo URL of the sender. + */ + "logoUrl"?: string | null; + /** + * The banner URL of the sender. + */ + "bannerUrl"?: string | null; + /** + * The privacy URL of the sender. Must be a publicly accessible HTTP or HTTPS URI associated with the sender. + */ + "privacyUrl"?: string | null; + /** + * The terms of service URL of the sender. + */ + "termsOfServiceUrl"?: string | null; + /** + * The color theme of the sender. Must be in hex format and have at least a 4:5:1 contrast ratio against white. + */ + "accentColor"?: string | null; + /** + * The messaging use case type for the RCS sender. Allowed values are `PROMOTIONAL`, `TRANSACTIONAL`, `OTP`, `MULTI_USE`. Defaults to `MULTI_USE` if not provided. Cannot be modified after launch. + */ + "useCase"?: string | null; + /** + * The vertical of the sender. Allowed values are: - `Alcohol` - `Automotive` - `Beauty, Spa and Salon` - `Clothing and Apparel` - `Education` - `Entertainment` - `Event Planning and Service` - `Finance and Banking` - `Food and Grocery` - `Hotel and Lodging` - `Matrimony Service` - `Medical and Health` - `Non-profit` - `Online Gambling` - `OTC Drugs` - `Other` - `Physical Gambling` - `Professional Services` - `Public Service` - `Restaurant` - `Shopping and Retail` - `Travel and Transportation` + */ + "vertical"?: string | null; + /** + * The websites of the sender. + */ + "websites"?: any | null; + /** + * The emails of the sender. + */ + "emails"?: any | null; + /** + * The phone numbers of the sender. + */ + "phoneNumbers"?: any | null; + + constructor(payload) { + this.name = payload["name"]; + this.about = payload["about"]; + this.address = payload["address"]; + this.description = payload["description"]; + this.logoUrl = payload["logo_url"]; + this.bannerUrl = payload["banner_url"]; + this.privacyUrl = payload["privacy_url"]; + this.termsOfServiceUrl = payload["terms_of_service_url"]; + this.accentColor = payload["accent_color"]; + this.useCase = payload["use_case"]; + this.vertical = payload["vertical"]; + this.websites = payload["websites"]; + this.emails = payload["emails"]; + this.phoneNumbers = payload["phone_numbers"]; + } +} + + +/** + * The profile information for the sender. + */ +export class MessagingV2ChannelsSenderProfileGenericResponse { + /** + * The name of the sender. + */ + "name"?: string | null; + /** + * The profile about text for the sender. + */ + "about"?: string | null; + /** + * The address of the sender. + */ + "address"?: string | null; + /** + * The description of the sender. + */ + "description"?: string | null; + /** + * The logo URL of the sender. + */ + "logoUrl"?: string | null; + /** + * The banner URL of the sender. + */ + "bannerUrl"?: string | null; + /** + * The privacy URL of the sender. Must be a publicly accessible HTTP or HTTPS URI associated with the sender. + */ + "privacyUrl"?: string | null; + /** + * The terms of service URL of the sender. + */ + "termsOfServiceUrl"?: string | null; + /** + * The color theme of the sender. Must be in hex format and have at least a 4:5:1 contrast ratio against white. + */ + "accentColor"?: string | null; + /** + * The messaging use case type for the RCS sender. Allowed values are `PROMOTIONAL`, `TRANSACTIONAL`, `OTP`, `MULTI_USE`. Defaults to `MULTI_USE` if not provided. Cannot be modified after launch. + */ + "useCase"?: string | null; + /** + * The vertical of the sender. Allowed values are: - `Alcohol` - `Automotive` - `Beauty, Spa and Salon` - `Clothing and Apparel` - `Education` - `Entertainment` - `Event Planning and Service` - `Finance and Banking` - `Food and Grocery` - `Hotel and Lodging` - `Matrimony Service` - `Medical and Health` - `Non-profit` - `Online Gambling` - `OTC Drugs` - `Other` - `Physical Gambling` - `Professional Services` - `Public Service` - `Restaurant` - `Shopping and Retail` - `Travel and Transportation` + */ + "vertical"?: string | null; + /** + * The websites of the sender. + */ + "websites"?: Array<MessagingV2ChannelsSenderProfileGenericResponseWebsites> | null; + /** + * The emails of the sender. + */ + "emails"?: Array<MessagingV2ChannelsSenderProfileGenericResponseEmails> | null; + /** + * The phone numbers of the sender. + */ + "phoneNumbers"?: Array<MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers> | null; + + constructor(payload) { + this.name = payload["name"]; + this.about = payload["about"]; + this.address = payload["address"]; + this.description = payload["description"]; + this.logoUrl = payload["logo_url"]; + this.bannerUrl = payload["banner_url"]; + this.privacyUrl = payload["privacy_url"]; + this.termsOfServiceUrl = payload["terms_of_service_url"]; + this.accentColor = payload["accent_color"]; + this.useCase = payload["use_case"]; + this.vertical = payload["vertical"]; + this.websites = payload["websites"]; + this.emails = payload["emails"]; + this.phoneNumbers = payload["phone_numbers"]; + } +} + + +export class MessagingV2ChannelsSenderProfileGenericResponseEmails { + "email"?: string; + "label"?: string; + + constructor(payload) { + this.email = payload["email"]; + this.label = payload["label"]; + } +} + + +export class MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers { + "phoneNumber"?: string; + "label"?: string; + + constructor(payload) { + this.phoneNumber = payload["phone_number"]; + this.label = payload["label"]; + } +} + + +export class MessagingV2ChannelsSenderProfileGenericResponseWebsites { + "website"?: string; + "label"?: string; + + constructor(payload) { + this.website = payload["website"]; + this.label = payload["label"]; + } +} + + +/** + * The additional properties for the sender. + */ +export class MessagingV2ChannelsSenderProperties { + /** + * The quality rating of the sender. + */ + "qualityRating"?: string | null; + /** + * The messaging limit of the sender. + */ + "messagingLimit"?: string | null; + + constructor(payload) { + this.qualityRating = payload["quality_rating"]; + this.messagingLimit = payload["messaging_limit"]; + } +} + + +export class MessagingV2ChannelsSenderRequestsCreate { + /** + * The ID of the sender in `whatsapp:<E.164_PHONE_NUMBER>` format. + */ + "senderId": string | null; + /** + * Optional display label for the sender in the Twilio Console. + */ + "friendlyName"?: string | null; + "configuration"?: MessagingV2ChannelsSenderConfiguration | null; + "webhook"?: MessagingV2ChannelsSenderWebhook | null; + "profile"?: MessagingV2ChannelsSenderProfile | null; + + constructor(payload) { + this.senderId = payload["sender_id"]; + this.friendlyName = payload["friendly_name"]; + this.configuration = payload["configuration"]; + this.webhook = payload["webhook"]; + this.profile = payload["profile"]; + } +} + + +export class MessagingV2ChannelsSenderRequestsUpdate { + /** + * Optional display label for the sender in the Twilio Console. + */ + "friendlyName"?: string | null; + "configuration"?: MessagingV2ChannelsSenderConfiguration | null; + "webhook"?: MessagingV2ChannelsSenderWebhook | null; + "profile"?: MessagingV2ChannelsSenderProfile | null; + + constructor(payload) { + this.friendlyName = payload["friendly_name"]; + this.configuration = payload["configuration"]; + this.webhook = payload["webhook"]; + this.profile = payload["profile"]; + } +} + + +/** + * The configuration settings for webhooks. + */ +export class MessagingV2ChannelsSenderWebhook { + /** + * The URL to send the webhook to. + */ + "callbackUrl"?: string | null; + /** + * The HTTP method for the webhook. + */ + "callbackMethod"?: string | null; + /** + * The URL to send the fallback webhook to. + */ + "fallbackUrl"?: string | null; + /** + * The HTTP method for the fallback webhook. + */ + "fallbackMethod"?: string | null; + /** + * The URL to send the status callback to. + */ + "statusCallbackUrl"?: string | null; + /** + * The HTTP method for the status callback. + */ + "statusCallbackMethod"?: string | null; + + constructor(payload) { + this.callbackUrl = payload["callback_url"]; + this.callbackMethod = payload["callback_method"]; + this.fallbackUrl = payload["fallback_url"]; + this.fallbackMethod = payload["fallback_method"]; + this.statusCallbackUrl = payload["status_callback_url"]; + this.statusCallbackMethod = payload["status_callback_method"]; + } +} + + +export class MessagingV2RcsCarrier { + /** + * The name of the carrier. For example, `Verizon` or `AT&T` for US. + */ + "name"?: string; + "status"?: MessagingV2RcsCarrierStatus; + + constructor(payload) { + this.name = payload["name"]; + this.status = payload["status"]; + } +} + + +/** + * The carrier-level status. + */ +export type MessagingV2RcsCarrierStatus = 'UNKNOWN'|'UNLAUNCHED'|'CARRIER_REVIEW'|'APPROVED'|'REJECTED'|'SUSPENDED'; + +export class MessagingV2RcsComplianceCountryResponse { + /** + * The ISO 3166-1 alpha-2 country code. + */ + "country": string; + /** + * The default compliance registration SID (e.g., from CR-Google) that applies to all countries unless overridden in the `countries` array. + */ + "registrationSid"?: string; + "status"?: MessagingV2RcsCountryStatus; + "carriers"?: Array<MessagingV2RcsCarrier>; + + constructor(payload) { + this.country = payload["country"]; + this.registrationSid = payload["registration_sid"]; + this.status = payload["status"]; + this.carriers = payload["carriers"]; + } +} + + +/** + * The KYC compliance information. This section consists of response to the request launch. + */ +export class MessagingV2RcsComplianceResponse { + /** + * The default compliance registration SID (e.g., from CR-Google) that applies to all countries unless overridden in the `countries` array. + */ + "registrationSid": string; + /** + * A list of country-specific compliance details. + */ + "countries"?: Array<MessagingV2RcsComplianceCountryResponse>; + + constructor(payload) { + this.registrationSid = payload["registration_sid"]; + this.countries = payload["countries"]; + } +} + + +/** + * The country-level status. Based on the aggregation of the carrier-level status. + */ +export type MessagingV2RcsCountryStatus = 'ONLINE'|'OFFLINE'|'TWILIO_REVIEW'|'PENDING_VERIFICATION'; + + + + +/** + * Options to pass to update a ChannelsSenderInstance + */ +export interface ChannelsSenderContextUpdateOptions { + /** */ + "messagingV2ChannelsSenderRequestsUpdate"?: MessagingV2ChannelsSenderRequestsUpdate; +} + +/** + * Options to pass to create a ChannelsSenderInstance + */ +export interface ChannelsSenderListInstanceCreateOptions { + /** */ + "messagingV2ChannelsSenderRequestsCreate": MessagingV2ChannelsSenderRequestsCreate; +} + +/** + * Options to pass to each + */ +export interface ChannelsSenderListInstanceEachOptions { + /** */ + "channel": string; + /** The number of items to return per page. For WhatsApp, the default is `20`. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChannelsSenderInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChannelsSenderListInstanceOptions { + /** */ + "channel": string; + /** The number of items to return per page. For WhatsApp, the default is `20`. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChannelsSenderListInstancePageOptions { + /** */ + "channel": string; + /** The number of items to return per page. For WhatsApp, the default is `20`. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ChannelsSenderContext { + + /** + * Remove a ChannelsSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ChannelsSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ChannelsSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance> + + /** + * Fetch a ChannelsSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>> + + /** + * Update a ChannelsSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance + */ + update(callback?: (error: Error | null, item?: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance>; + /** + * Update a ChannelsSenderInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance + */ + update(params: MessagingV2ChannelsSenderRequestsUpdate, headers?: any, callback?: (error: Error | null, item?: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance>; + + /** + * Update a ChannelsSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>>; + /** + * Update a ChannelsSenderInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessagingV2ChannelsSenderRequestsUpdate, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ChannelsSenderContextSolution { + "sid": string; +} + +export class ChannelsSenderContextImpl implements ChannelsSenderContext { + protected _solution: ChannelsSenderContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Channels/Senders/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ChannelsSenderInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ChannelsSenderResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ChannelsSenderInstance> => ({ + ...response, + body: new ChannelsSenderInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: MessagingV2ChannelsSenderRequestsUpdate | ((error: Error | null, item?: ChannelsSenderInstance) => any), headers?: any,callback?: (error: Error | null, item?: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<MessagingV2ChannelsSenderRequestsUpdate> as MessagingV2ChannelsSenderRequestsUpdate; + } else { + params = params || {} as Partial<MessagingV2ChannelsSenderRequestsUpdate> as MessagingV2ChannelsSenderRequestsUpdate; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelsSenderInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: MessagingV2ChannelsSenderRequestsUpdate | ((error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<MessagingV2ChannelsSenderRequestsUpdate> as MessagingV2ChannelsSenderRequestsUpdate; + } else { + params = params || {} as Partial<MessagingV2ChannelsSenderRequestsUpdate> as MessagingV2ChannelsSenderRequestsUpdate; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ChannelsSenderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ChannelsSenderInstance> => ({ + ...response, + body: new ChannelsSenderInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ChannelsSenderPayload extends TwilioResponsePayload { + senders: ChannelsSenderResource[]; +} + +interface ChannelsSenderResource { + sid: string; + status: ChannelsSenderStatus; + sender_id: string; + friendly_name: string; + configuration: MessagingV2ChannelsSenderConfiguration; + webhook: MessagingV2ChannelsSenderWebhook; + profile: MessagingV2ChannelsSenderProfileGenericResponse; + properties: MessagingV2ChannelsSenderProperties; + offline_reasons: Array<MessagingV2ChannelsSenderOfflineReasonsItems>; + compliance: MessagingV2RcsComplianceResponse; + url: string; +} + +export class ChannelsSenderInstance { + protected _solution: ChannelsSenderContextSolution; + protected _context?: ChannelsSenderContext; + + constructor(protected _version: V2, payload: ChannelsSenderResource, sid?: string) { + + this.sid = (payload.sid); + this.status = payload.status; + this.senderId = (payload.sender_id); + this.friendlyName = (payload.friendly_name); + this.configuration = payload.configuration !== null && payload.configuration !== undefined ? new MessagingV2ChannelsSenderConfiguration(payload.configuration) : null; + this.webhook = payload.webhook !== null && payload.webhook !== undefined ? new MessagingV2ChannelsSenderWebhook(payload.webhook) : null; + this.profile = payload.profile !== null && payload.profile !== undefined ? new MessagingV2ChannelsSenderProfileGenericResponse(payload.profile) : null; + this.properties = payload.properties !== null && payload.properties !== undefined ? new MessagingV2ChannelsSenderProperties(payload.properties) : null; + this.offlineReasons = payload.offline_reasons !== null && payload.offline_reasons !== undefined ? payload.offline_reasons.map( + (payload: any) => new MessagingV2ChannelsSenderOfflineReasonsItems(payload) + ) : null; + this.compliance = payload.compliance !== null && payload.compliance !== undefined ? new MessagingV2RcsComplianceResponse(payload.compliance) : null; + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the sender. + */ + sid: string; + status: ChannelsSenderStatus; + /** + * The ID of the sender in `whatsapp:<E.164_PHONE_NUMBER>` format. + */ + senderId: string; + /** + * Optional display label for the sender in the Twilio Console. + */ + friendlyName: string; + configuration: MessagingV2ChannelsSenderConfiguration; + webhook: MessagingV2ChannelsSenderWebhook; + profile: MessagingV2ChannelsSenderProfileGenericResponse; + properties: MessagingV2ChannelsSenderProperties; + /** + * The reasons why the sender is offline. + */ + offlineReasons: Array<MessagingV2ChannelsSenderOfflineReasonsItems>; + compliance: MessagingV2RcsComplianceResponse; + /** + * The URL of the resource. + */ + url: string; + + private get _proxy(): ChannelsSenderContext { + this._context = this._context || new ChannelsSenderContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ChannelsSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ChannelsSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ChannelsSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance + */ + fetch(callback?: (error: Error | null, item?: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ChannelsSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ChannelsSenderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance + */ + update(callback?: (error: Error | null, item?: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance>; + /** + * Update a ChannelsSenderInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance + */ + update(params: MessagingV2ChannelsSenderRequestsUpdate, headers?: any, callback?: (error: Error | null, item?: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ChannelsSenderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>>; + /** + * Update a ChannelsSenderInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessagingV2ChannelsSenderRequestsUpdate, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + status: this.status, + senderId: this.senderId, + friendlyName: this.friendlyName, + configuration: this.configuration, + webhook: this.webhook, + profile: this.profile, + properties: this.properties, + offlineReasons: this.offlineReasons, + compliance: this.compliance, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ChannelsSenderSolution { +} + +export interface ChannelsSenderListInstance { + _version: V2; + _solution: ChannelsSenderSolution; + _uri: string; + + (sid: string, ): ChannelsSenderContext; + get(sid: string, ): ChannelsSenderContext; + + + + + + + + + /** + * Create a ChannelsSenderInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance + */ + create(params: MessagingV2ChannelsSenderRequestsCreate, headers?: any, callback?: (error: Error | null, item?: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance>; + + /** + * Create a ChannelsSenderInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChannelsSenderInstance with HTTP metadata + */ + createWithHttpInfo(params: MessagingV2ChannelsSenderRequestsCreate, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>>; + + + + + /** + * Streams ChannelsSenderInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelsSenderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + + each(params: ChannelsSenderListInstanceEachOptions, callback?: (item: ChannelsSenderInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChannelsSenderInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelsSenderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + + eachWithHttpInfo(params: ChannelsSenderListInstanceEachOptions, callback?: (item: ChannelsSenderInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChannelsSenderInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelsSenderPage) => any): Promise<ChannelsSenderPage>; + /** + * Retrieve a single target page of ChannelsSenderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ChannelsSenderPage>) => any): Promise<ApiResponse<ChannelsSenderPage>>; + /** + * Lists ChannelsSenderInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelsSenderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + + list(params: ChannelsSenderListInstanceOptions, callback?: (error: Error | null, items: ChannelsSenderInstance[]) => any): Promise<ChannelsSenderInstance[]>; + /** + * Lists ChannelsSenderInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelsSenderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + + listWithHttpInfo(params: ChannelsSenderListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ChannelsSenderInstance[]>) => any): Promise<ApiResponse<ChannelsSenderInstance[]>>; + /** + * Retrieve a single page of ChannelsSenderInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelsSenderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + + page(params: ChannelsSenderListInstancePageOptions, callback?: (error: Error | null, items: ChannelsSenderPage) => any): Promise<ChannelsSenderPage>; + /** + * Retrieve a single page of ChannelsSenderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChannelsSenderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + + pageWithHttpInfo(params: ChannelsSenderListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ChannelsSenderPage>) => any): Promise<ApiResponse<ChannelsSenderPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChannelsSenderListInstance(version: V2): ChannelsSenderListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ChannelsSenderListInstance; + + instance.get = function get(sid, ): ChannelsSenderContext { + return new ChannelsSenderContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Channels/Senders`; + + instance.create = function create(params: MessagingV2ChannelsSenderRequestsCreate, headers?: any, callback?: (error: Error | null, items: ChannelsSenderInstance) => any): Promise<ChannelsSenderInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChannelsSenderInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MessagingV2ChannelsSenderRequestsCreate, headers?: any, callback?: (error: Error | null, items: ApiResponse<ChannelsSenderInstance>) => any): Promise<ApiResponse<ChannelsSenderInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ChannelsSenderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ChannelsSenderInstance> => ({ + ...response, + body: new ChannelsSenderInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params: ChannelsSenderListInstancePageOptions, callback?: (error: Error | null, items: ChannelsSenderPage) => any): Promise<ChannelsSenderPage> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["channel"] === null || params["channel"] === undefined) { + throw new Error('Required parameter "params[\'channel\']" missing.'); + } + + let data: any = {}; + + + data["Channel"] = params["channel"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChannelsSenderPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChannelsSenderPage) => any): Promise<ChannelsSenderPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChannelsSenderPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params: ChannelsSenderListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ChannelsSenderPage>) => any): Promise<ApiResponse<ChannelsSenderPage>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["channel"] === null || params["channel"] === undefined) { + throw new Error('Required parameter "params[\'channel\']" missing.'); + } + + let data: any = {}; + + + data["Channel"] = params["channel"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ChannelsSenderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelsSenderPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ChannelsSenderPage>) => any): Promise<ApiResponse<ChannelsSenderPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ChannelsSenderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChannelsSenderPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ChannelsSenderPage extends Page<V2, ChannelsSenderPayload, ChannelsSenderResource, ChannelsSenderInstance> { +/** +* Initialize the ChannelsSenderPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: ChannelsSenderSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ChannelsSenderInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChannelsSenderResource): ChannelsSenderInstance { + + return new ChannelsSenderInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/messaging/v2/domainCerts.ts b/rest/messaging/v2/domainCerts.ts new file mode 100644 index 000000000..c6b0f5c72 --- /dev/null +++ b/rest/messaging/v2/domainCerts.ts @@ -0,0 +1,294 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +export interface DomainCertsContext { + + /** + * Fetch a DomainCertsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance + */ + fetch(callback?: (error: Error | null, item?: DomainCertsInstance) => any): Promise<DomainCertsInstance> + + /** + * Fetch a DomainCertsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainCertsInstance>) => any): Promise<ApiResponse<DomainCertsInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DomainCertsContextSolution { + "domainSid": string; +} + +export class DomainCertsContextImpl implements DomainCertsContext { + protected _solution: DomainCertsContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, domainSid: string) { + if (!isValidPathParam(domainSid)) { + throw new Error('Parameter \'domainSid\' is not valid.'); + } + + this._solution = { domainSid, }; + this._uri = `/LinkShortening/Domains/${domainSid}/Certificate`; + } + + fetch(callback?: (error: Error | null, item?: DomainCertsInstance) => any): Promise<DomainCertsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DomainCertsInstance(operationVersion, payload, instance._solution.domainSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainCertsInstance>) => any): Promise<ApiResponse<DomainCertsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DomainCertsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DomainCertsInstance> => ({ + ...response, + body: new DomainCertsInstance(operationVersion, response.body, instance._solution.domainSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DomainCertsPayload extends DomainCertsResource {} + +interface DomainCertsResource { + domain_sid: string; + date_updated: Date; + date_expires: Date; + date_created: Date; + domain_name: string; + certificate_sid: string; + managed: boolean; + requesting: boolean; + url: string; + cert_in_validation: any; +} + +export class DomainCertsInstance { + protected _solution: DomainCertsContextSolution; + protected _context?: DomainCertsContext; + + constructor(protected _version: V2, payload: DomainCertsResource, domainSid?: string) { + + this.domainSid = (payload.domain_sid); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.dateExpires = deserialize.iso8601DateTime(payload.date_expires); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.domainName = (payload.domain_name); + this.certificateSid = (payload.certificate_sid); + this.managed = (payload.managed); + this.requesting = (payload.requesting); + this.url = (payload.url); + this.certInValidation = (payload.cert_in_validation); + + this._solution = { domainSid: domainSid, }; + } + + /** + * The unique string that we created to identify the Domain resource. + */ + domainSid: string; + /** + * Date that this Domain was last updated. + */ + dateUpdated: Date; + /** + * Date that the private certificate associated with this domain expires. You will need to update the certificate before that date to ensure your shortened links will continue to work. + */ + dateExpires: Date; + /** + * Date that this Domain was registered to the Twilio platform to create a new Domain object. + */ + dateCreated: Date; + /** + * Full url path for this domain. + */ + domainName: string; + /** + * The unique string that we created to identify this Certificate resource. + */ + certificateSid: string; + /** + * Boolean field that indicates whether the certificate is managed by Twilio or uploaded by the customer. + */ + managed: boolean; + /** + * Boolean field that indicates whether a Twilio managed cert request is in progress or completed. True indicates a request is in progress and false indicates the request has completed or not requested yet. + */ + requesting: boolean; + url: string; + /** + * Optional JSON field describing the status and upload date of a new certificate in the process of validation + */ + certInValidation: any; + + private get _proxy(): DomainCertsContext { + this._context = this._context || new DomainCertsContextImpl(this._version, this._solution.domainSid); + return this._context; + } + + /** + * Fetch a DomainCertsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance + */ + fetch(callback?: (error: Error | null, item?: DomainCertsInstance) => any): Promise<DomainCertsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DomainCertsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DomainCertsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DomainCertsInstance>) => any): Promise<ApiResponse<DomainCertsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + domainSid: this.domainSid, + dateUpdated: this.dateUpdated, + dateExpires: this.dateExpires, + dateCreated: this.dateCreated, + domainName: this.domainName, + certificateSid: this.certificateSid, + managed: this.managed, + requesting: this.requesting, + url: this.url, + certInValidation: this.certInValidation, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DomainCertsSolution { +} + +export interface DomainCertsListInstance { + _version: V2; + _solution: DomainCertsSolution; + _uri: string; + + (domainSid: string, ): DomainCertsContext; + get(domainSid: string, ): DomainCertsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DomainCertsListInstance(version: V2): DomainCertsListInstance { + const instance = ((domainSid, ) => instance.get(domainSid, )) as DomainCertsListInstance; + + instance.get = function get(domainSid, ): DomainCertsContext { + return new DomainCertsContextImpl(version, domainSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/messaging/v2/typingIndicator.ts b/rest/messaging/v2/typingIndicator.ts new file mode 100644 index 000000000..b2a9ca7d9 --- /dev/null +++ b/rest/messaging/v2/typingIndicator.ts @@ -0,0 +1,209 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a TypingIndicatorInstance + */ +export interface TypingIndicatorListInstanceCreateOptions { + /** Shared channel identifier */ + "channel": string; + /** Message SID that identifies the conversation thread for the typing indicator. Must be a valid Twilio Message SID (SM*) or Media SID (MM*) from an existing WhatsApp conversation. */ + "messageId": string; +} + + +export interface TypingIndicatorSolution { +} + +export interface TypingIndicatorListInstance { + _version: V2; + _solution: TypingIndicatorSolution; + _uri: string; + + + + /** + * Create a TypingIndicatorInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypingIndicatorInstance + */ + create(params: TypingIndicatorListInstanceCreateOptions, callback?: (error: Error | null, item?: TypingIndicatorInstance) => any): Promise<TypingIndicatorInstance>; + + /** + * Create a TypingIndicatorInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypingIndicatorInstance with HTTP metadata + */ + createWithHttpInfo(params: TypingIndicatorListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TypingIndicatorInstance>) => any): Promise<ApiResponse<TypingIndicatorInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TypingIndicatorListInstance(version: V2): TypingIndicatorListInstance { + const instance = {} as TypingIndicatorListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Indicators/Typing.json`; + + instance.create = function create(params: TypingIndicatorListInstanceCreateOptions, callback?: (error: Error | null, items: TypingIndicatorInstance) => any): Promise<TypingIndicatorInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["channel"] === null || params["channel"] === undefined) { + throw new Error('Required parameter "params[\'channel\']" missing.'); + } + + if (params["messageId"] === null || params["messageId"] === undefined) { + throw new Error('Required parameter "params[\'messageId\']" missing.'); + } + + let data: any = {}; + + + + data["channel"] = params["channel"]; + + data["messageId"] = params["messageId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TypingIndicatorInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TypingIndicatorListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<TypingIndicatorInstance>) => any): Promise<ApiResponse<TypingIndicatorInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["channel"] === null || params["channel"] === undefined) { + throw new Error('Required parameter "params[\'channel\']" missing.'); + } + + if (params["messageId"] === null || params["messageId"] === undefined) { + throw new Error('Required parameter "params[\'messageId\']" missing.'); + } + + let data: any = {}; + + + + data["channel"] = params["channel"]; + + data["messageId"] = params["messageId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TypingIndicatorResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TypingIndicatorInstance> => ({ + ...response, + body: new TypingIndicatorInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TypingIndicatorPayload extends TypingIndicatorResource {} + +interface TypingIndicatorResource { + success: boolean; +} + +export class TypingIndicatorInstance { + + constructor(protected _version: V2, payload: TypingIndicatorResource) { + + this.success = (payload.success); + + } + + /** + * Indicates if the typing indicator was sent successfully. + */ + success: boolean; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + success: this.success, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/messaging/v3/typingIndicator.ts b/rest/messaging/v3/typingIndicator.ts new file mode 100644 index 000000000..c1e318917 --- /dev/null +++ b/rest/messaging/v3/typingIndicator.ts @@ -0,0 +1,224 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Messaging + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Request body for sending a typing indicator. The schema varies by channel. Use the `channel` field to determine which properties are required. + */ +export class TypingIndicatorRequest { + /** + * The messaging channel. Must be \"RCS\". + */ + "channel": string; + /** + * The SID of a recent inbound message from the recipient. Must be an SM or MM SID format. + */ + "messageId": string; + /** + * The RCS agent identifier of the sender (business). + */ + "from": string; + /** + * The RCS recipient identifier in E.164 format prefixed with \"rcs:\". + */ + "to": string; + /** + * The type of typing event. Currently only \"START\" is supported for RCS, indicating the agent began typing. Defaults to \"START\". + */ + "event"?: string; + + constructor(payload) { + this.channel = payload["channel"]; + this.messageId = payload["messageId"]; + this.from = payload["from"]; + this.to = payload["to"]; + this.event = payload["event"]; + } +} + + + +/** + * Options to pass to create a TypingIndicatorInstance + */ +export interface TypingIndicatorListInstanceCreateOptions { + /** */ + "typingIndicatorRequest": TypingIndicatorRequest; +} + + +export interface TypingIndicatorSolution { +} + +export interface TypingIndicatorListInstance { + _version: V3; + _solution: TypingIndicatorSolution; + _uri: string; + + + + /** + * Create a TypingIndicatorInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypingIndicatorInstance + */ + create(params: TypingIndicatorRequest, headers?: any, callback?: (error: Error | null, item?: TypingIndicatorInstance) => any): Promise<TypingIndicatorInstance>; + + /** + * Create a TypingIndicatorInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypingIndicatorInstance with HTTP metadata + */ + createWithHttpInfo(params: TypingIndicatorRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TypingIndicatorInstance>) => any): Promise<ApiResponse<TypingIndicatorInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TypingIndicatorListInstance(version: V3): TypingIndicatorListInstance { + const instance = {} as TypingIndicatorListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Indicators/Typing.json`; + + instance.create = function create(params: TypingIndicatorRequest, headers?: any, callback?: (error: Error | null, items: TypingIndicatorInstance) => any): Promise<TypingIndicatorInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TypingIndicatorInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TypingIndicatorRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<TypingIndicatorInstance>) => any): Promise<ApiResponse<TypingIndicatorInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TypingIndicatorResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TypingIndicatorInstance> => ({ + ...response, + body: new TypingIndicatorInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TypingIndicatorPayload extends TypingIndicatorResource {} + +interface TypingIndicatorResource { + success: boolean; +} + +export class TypingIndicatorInstance { + + constructor(protected _version: V3, payload: TypingIndicatorResource) { + + this.success = (payload.success); + + } + + /** + * Indicates if the typing indicator was sent successfully. + */ + success: boolean; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + success: this.success, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/monitor/V1.ts b/rest/monitor/V1.ts new file mode 100644 index 000000000..2ac99fb86 --- /dev/null +++ b/rest/monitor/V1.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Monitor + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import MonitorBase from "../MonitorBase"; +import Version from "../../base/Version"; +import { AlertListInstance } from "./v1/alert"; +import { EventListInstance } from "./v1/event"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Monitor + * + * @param domain - The Twilio (Twilio.Monitor) domain + */ + constructor(domain: MonitorBase) { + super(domain, "v1"); + } + + /** alerts - { Twilio.Monitor.V1.AlertListInstance } resource */ + protected _alerts?: AlertListInstance; + /** events - { Twilio.Monitor.V1.EventListInstance } resource */ + protected _events?: EventListInstance; + + /** Getter for alerts resource */ + get alerts(): AlertListInstance { + this._alerts = this._alerts || AlertListInstance(this); + return this._alerts; + } + + /** Getter for events resource */ + get events(): EventListInstance { + this._events = this._events || EventListInstance(this); + return this._events; + } + +} diff --git a/rest/monitor/V2.ts b/rest/monitor/V2.ts new file mode 100644 index 000000000..b1e06093b --- /dev/null +++ b/rest/monitor/V2.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Alarms + * Manages Twilio Alarms + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import MonitorBase from "../MonitorBase"; +import Version from "../../base/Version"; +import { AlarmListInstance } from "./v2/alarm"; +import { StatusListInstance } from "./v2/status"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Monitor + * + * @param domain - The Twilio (Twilio.Monitor) domain + */ + constructor(domain: MonitorBase) { + super(domain, "v2"); + } + + /** alarms - { Twilio.Monitor.V2.AlarmListInstance } resource */ + protected _alarms?: AlarmListInstance; + /** status - { Twilio.Monitor.V2.StatusListInstance } resource */ + protected _status?: StatusListInstance; + + /** Getter for alarms resource */ + get alarms(): AlarmListInstance { + this._alarms = this._alarms || AlarmListInstance(this); + return this._alarms; + } + + /** Getter for status resource */ + get status(): StatusListInstance { + this._status = this._status || StatusListInstance(this); + return this._status; + } + +} diff --git a/rest/monitor/v1/alert.ts b/rest/monitor/v1/alert.ts new file mode 100644 index 000000000..f48e3e977 --- /dev/null +++ b/rest/monitor/v1/alert.ts @@ -0,0 +1,672 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Monitor + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface AlertListInstanceEachOptions { + /** Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. */ + "logLevel"?: string; + /** Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. */ + "startDate"?: Date; + /** Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. */ + "endDate"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AlertInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AlertListInstanceOptions { + /** Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. */ + "logLevel"?: string; + /** Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. */ + "startDate"?: Date; + /** Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. */ + "endDate"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AlertListInstancePageOptions { + /** Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. */ + "logLevel"?: string; + /** Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. */ + "startDate"?: Date; + /** Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. */ + "endDate"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AlertContext { + + /** + * Fetch a AlertInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlertInstance + */ + fetch(callback?: (error: Error | null, item?: AlertInstance) => any): Promise<AlertInstance> + + /** + * Fetch a AlertInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlertInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AlertInstance>) => any): Promise<ApiResponse<AlertInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AlertContextSolution { + "sid": string; +} + +export class AlertContextImpl implements AlertContext { + protected _solution: AlertContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Alerts/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: AlertInstance) => any): Promise<AlertInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AlertInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AlertInstance>) => any): Promise<ApiResponse<AlertInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AlertResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AlertInstance> => ({ + ...response, + body: new AlertInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AlertPayload extends TwilioResponsePayload { + alerts: AlertResource[]; +} + +interface AlertResource { + account_sid: string; + alert_text: string; + api_version: string; + date_created: Date; + date_generated: Date; + date_updated: Date; + error_code: string; + log_level: string; + more_info: string; + request_method: string; + request_url: string; + request_variables: string; + resource_sid: string; + response_body: string; + response_headers: string; + sid: string; + url: string; + request_headers: string; + service_sid: string; +} + +export class AlertInstance { + protected _solution: AlertContextSolution; + protected _context?: AlertContext; + + constructor(protected _version: V1, payload: AlertResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.alertText = (payload.alert_text); + this.apiVersion = (payload.api_version); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateGenerated = deserialize.iso8601DateTime(payload.date_generated); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.errorCode = (payload.error_code); + this.logLevel = (payload.log_level); + this.moreInfo = (payload.more_info); + this.requestMethod = (payload.request_method); + this.requestUrl = (payload.request_url); + this.requestVariables = (payload.request_variables); + this.resourceSid = (payload.resource_sid); + this.responseBody = (payload.response_body); + this.responseHeaders = (payload.response_headers); + this.sid = (payload.sid); + this.url = (payload.url); + this.requestHeaders = (payload.request_headers); + this.serviceSid = (payload.service_sid); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Alert resource. + */ + accountSid: string; + /** + * The text of the alert. + */ + alertText: string; + /** + * The API version used when the alert was generated. Can be empty for events that don\'t have a specific API version. + */ + apiVersion: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the alert was generated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. Due to buffering, this can be different than `date_created`. + */ + dateGenerated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The error code for the condition that generated the alert. See the [Error Dictionary](https://www.twilio.com/docs/api/errors) for possible causes and solutions to the error. + */ + errorCode: string; + /** + * The log level. Can be: `error`, `warning`, `notice`, or `debug`. + */ + logLevel: string; + /** + * The URL of the page in our [Error Dictionary](https://www.twilio.com/docs/api/errors) with more information about the error condition. + */ + moreInfo: string; + /** + * The method used by the request that generated the alert. If the alert was generated by a request we made to your server, this is the method we used. If the alert was generated by a request from your application to our API, this is the method your application used. + */ + requestMethod: string; + /** + * The URL of the request that generated the alert. If the alert was generated by a request we made to your server, this is the URL on your server that generated the alert. If the alert was generated by a request from your application to our API, this is the URL of the resource requested. + */ + requestUrl: string; + /** + * The variables passed in the request that generated the alert. This value is only returned when a single Alert resource is fetched. + */ + requestVariables: string; + /** + * The SID of the resource for which the alert was generated. For instance, if your server failed to respond to an HTTP request during the flow of a particular call, this value would be the SID of the server. This value is empty if the alert was not generated for a particular resource. + */ + resourceSid: string; + /** + * The response body of the request that generated the alert. This value is only returned when a single Alert resource is fetched. + */ + responseBody: string; + /** + * The response headers of the request that generated the alert. This value is only returned when a single Alert resource is fetched. + */ + responseHeaders: string; + /** + * The unique string that we created to identify the Alert resource. + */ + sid: string; + /** + * The absolute URL of the Alert resource. + */ + url: string; + /** + * The request headers of the request that generated the alert. This value is only returned when a single Alert resource is fetched. + */ + requestHeaders: string; + /** + * The SID of the service or resource that generated the alert. Can be `null`. + */ + serviceSid: string; + + private get _proxy(): AlertContext { + this._context = this._context || new AlertContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a AlertInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlertInstance + */ + fetch(callback?: (error: Error | null, item?: AlertInstance) => any): Promise<AlertInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AlertInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlertInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AlertInstance>) => any): Promise<ApiResponse<AlertInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + alertText: this.alertText, + apiVersion: this.apiVersion, + dateCreated: this.dateCreated, + dateGenerated: this.dateGenerated, + dateUpdated: this.dateUpdated, + errorCode: this.errorCode, + logLevel: this.logLevel, + moreInfo: this.moreInfo, + requestMethod: this.requestMethod, + requestUrl: this.requestUrl, + requestVariables: this.requestVariables, + resourceSid: this.resourceSid, + responseBody: this.responseBody, + responseHeaders: this.responseHeaders, + sid: this.sid, + url: this.url, + requestHeaders: this.requestHeaders, + serviceSid: this.serviceSid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AlertSolution { +} + +export interface AlertListInstance { + _version: V1; + _solution: AlertSolution; + _uri: string; + + (sid: string, ): AlertContext; + get(sid: string, ): AlertContext; + + + + + + /** + * Streams AlertInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlertListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AlertInstance, done: (err?: Error) => void) => void): void; + each(params: AlertListInstanceEachOptions, callback?: (item: AlertInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AlertInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlertListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AlertInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AlertListInstanceEachOptions, callback?: (item: AlertInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AlertInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AlertPage) => any): Promise<AlertPage>; + /** + * Retrieve a single target page of AlertInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AlertPage>) => any): Promise<ApiResponse<AlertPage>>; + /** + * Lists AlertInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlertListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AlertInstance[]) => any): Promise<AlertInstance[]>; + list(params: AlertListInstanceOptions, callback?: (error: Error | null, items: AlertInstance[]) => any): Promise<AlertInstance[]>; + /** + * Lists AlertInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlertListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AlertInstance[]>) => any): Promise<ApiResponse<AlertInstance[]>>; + listWithHttpInfo(params: AlertListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AlertInstance[]>) => any): Promise<ApiResponse<AlertInstance[]>>; + /** + * Retrieve a single page of AlertInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlertListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AlertPage) => any): Promise<AlertPage>; + page(params: AlertListInstancePageOptions, callback?: (error: Error | null, items: AlertPage) => any): Promise<AlertPage>; + /** + * Retrieve a single page of AlertInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlertListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AlertPage>) => any): Promise<ApiResponse<AlertPage>>; + pageWithHttpInfo(params: AlertListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AlertPage>) => any): Promise<ApiResponse<AlertPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AlertListInstance(version: V1): AlertListInstance { + const instance = ((sid, ) => instance.get(sid, )) as AlertListInstance; + + instance.get = function get(sid, ): AlertContext { + return new AlertContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Alerts`; + + instance.page = function page(params?: AlertListInstancePageOptions | ((error: Error | null, items: AlertPage) => any), callback?: (error: Error | null, items: AlertPage) => any): Promise<AlertPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["logLevel"] !== undefined) + data["LogLevel"] = params["logLevel"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AlertPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AlertPage) => any): Promise<AlertPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AlertPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AlertListInstancePageOptions | ((error: Error | null, items: ApiResponse<AlertPage>) => any), callback?: (error: Error | null, items: ApiResponse<AlertPage>) => any): Promise<ApiResponse<AlertPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["logLevel"] !== undefined) + data["LogLevel"] = params["logLevel"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AlertPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AlertPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AlertPage>) => any): Promise<ApiResponse<AlertPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AlertPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AlertPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AlertPage extends Page<V1, AlertPayload, AlertResource, AlertInstance> { +/** +* Initialize the AlertPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: AlertSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AlertInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AlertResource): AlertInstance { + + return new AlertInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/monitor/v1/event.ts b/rest/monitor/v1/event.ts new file mode 100644 index 000000000..0ba5e2023 --- /dev/null +++ b/rest/monitor/v1/event.ts @@ -0,0 +1,667 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Monitor + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface EventListInstanceEachOptions { + /** Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. */ + "actorSid"?: string; + /** Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). */ + "eventType"?: string; + /** Only include events that refer to this resource. Useful for discovering the history of a specific resource. */ + "resourceSid"?: string; + /** Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. */ + "sourceIpAddress"?: string; + /** Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "endDate"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EventInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EventListInstanceOptions { + /** Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. */ + "actorSid"?: string; + /** Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). */ + "eventType"?: string; + /** Only include events that refer to this resource. Useful for discovering the history of a specific resource. */ + "resourceSid"?: string; + /** Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. */ + "sourceIpAddress"?: string; + /** Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "endDate"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EventListInstancePageOptions { + /** Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. */ + "actorSid"?: string; + /** Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). */ + "eventType"?: string; + /** Only include events that refer to this resource. Useful for discovering the history of a specific resource. */ + "resourceSid"?: string; + /** Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. */ + "sourceIpAddress"?: string; + /** Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "endDate"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EventContext { + + /** + * Fetch a EventInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventInstance + */ + fetch(callback?: (error: Error | null, item?: EventInstance) => any): Promise<EventInstance> + + /** + * Fetch a EventInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EventInstance>) => any): Promise<ApiResponse<EventInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EventContextSolution { + "sid": string; +} + +export class EventContextImpl implements EventContext { + protected _solution: EventContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Events/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: EventInstance) => any): Promise<EventInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EventInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EventInstance>) => any): Promise<ApiResponse<EventInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EventResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EventInstance> => ({ + ...response, + body: new EventInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EventPayload extends TwilioResponsePayload { + events: EventResource[]; +} + +interface EventResource { + account_sid: string; + actor_sid: string; + actor_type: string; + description: string; + event_data: any; + event_date: Date; + event_type: string; + resource_sid: string; + resource_type: string; + sid: string; + source: string; + source_ip_address: string; + url: string; + links: Record<string, string>; +} + +export class EventInstance { + protected _solution: EventContextSolution; + protected _context?: EventContext; + + constructor(protected _version: V1, payload: EventResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.actorSid = (payload.actor_sid); + this.actorType = (payload.actor_type); + this.description = (payload.description); + this.eventData = (payload.event_data); + this.eventDate = deserialize.iso8601DateTime(payload.event_date); + this.eventType = (payload.event_type); + this.resourceSid = (payload.resource_sid); + this.resourceType = (payload.resource_type); + this.sid = (payload.sid); + this.source = (payload.source); + this.sourceIpAddress = (payload.source_ip_address); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Event resource. + */ + accountSid: string; + /** + * The SID of the actor that caused the event, if available. This can be either a User ID (matching the pattern `^US[0-9a-fA-F]{32}$`) or an Account SID (matching the pattern `^AC[0-9a-fA-F]{32}$`). If the actor\'s SID isn\'t available, this field will be `null`. + */ + actorSid: string; + /** + * The type of actor that caused the event. Can be: `user` for a change made by a logged-in user in the Twilio Console, `account` for an event caused by an API request by an authenticating Account, `twilio-admin` for an event caused by a Twilio employee, and so on. + */ + actorType: string; + /** + * A description of the event. Can be `null`. + */ + description: string; + /** + * An object with additional data about the event. The contents depend on `event_type`. For example, event-types of the form `RESOURCE.updated`, this value contains a `resource_properties` dictionary that describes the previous and updated properties of the resource. + */ + eventData: any; + /** + * The date and time in GMT when the event was recorded specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + eventDate: Date; + /** + * The event\'s type. Event-types are typically in the form: `RESOURCE_TYPE.ACTION`, where `RESOURCE_TYPE` is the type of resource that was affected and `ACTION` is what happened to it. For example, `phone-number.created`. For a full list of all event-types, see the [Monitor Event Types](https://www.twilio.com/docs/usage/monitor-events#event-types). + */ + eventType: string; + /** + * The SID of the resource that was affected. + */ + resourceSid: string; + /** + * The type of resource that was affected. For a full list of all resource-types, see the [Monitor Event Types](https://www.twilio.com/docs/usage/monitor-events#event-types). + */ + resourceType: string; + /** + * The unique string that we created to identify the Event resource. + */ + sid: string; + /** + * The originating system or interface that caused the event. Can be: `web` for events caused by user action in the Twilio Console, `api` for events caused by a request to our API, or `twilio` for events caused by an automated or internal Twilio system. + */ + source: string; + /** + * The IP address of the source, if the source is outside the Twilio cloud. This value is `null` for events with `source` of `twilio` + */ + sourceIpAddress: string; + /** + * The absolute URL of the resource that was affected. Can be `null`. + */ + url: string; + /** + * The absolute URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): EventContext { + this._context = this._context || new EventContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a EventInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventInstance + */ + fetch(callback?: (error: Error | null, item?: EventInstance) => any): Promise<EventInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EventInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EventInstance>) => any): Promise<ApiResponse<EventInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + actorSid: this.actorSid, + actorType: this.actorType, + description: this.description, + eventData: this.eventData, + eventDate: this.eventDate, + eventType: this.eventType, + resourceSid: this.resourceSid, + resourceType: this.resourceType, + sid: this.sid, + source: this.source, + sourceIpAddress: this.sourceIpAddress, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EventSolution { +} + +export interface EventListInstance { + _version: V1; + _solution: EventSolution; + _uri: string; + + (sid: string, ): EventContext; + get(sid: string, ): EventContext; + + + + + + /** + * Streams EventInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + each(params: EventListInstanceEachOptions, callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EventInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EventListInstanceEachOptions, callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EventInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EventPage) => any): Promise<EventPage>; + /** + * Retrieve a single target page of EventInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EventPage>) => any): Promise<ApiResponse<EventPage>>; + /** + * Lists EventInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EventInstance[]) => any): Promise<EventInstance[]>; + list(params: EventListInstanceOptions, callback?: (error: Error | null, items: EventInstance[]) => any): Promise<EventInstance[]>; + /** + * Lists EventInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EventInstance[]>) => any): Promise<ApiResponse<EventInstance[]>>; + listWithHttpInfo(params: EventListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EventInstance[]>) => any): Promise<ApiResponse<EventInstance[]>>; + /** + * Retrieve a single page of EventInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EventPage) => any): Promise<EventPage>; + page(params: EventListInstancePageOptions, callback?: (error: Error | null, items: EventPage) => any): Promise<EventPage>; + /** + * Retrieve a single page of EventInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EventPage>) => any): Promise<ApiResponse<EventPage>>; + pageWithHttpInfo(params: EventListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EventPage>) => any): Promise<ApiResponse<EventPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EventListInstance(version: V1): EventListInstance { + const instance = ((sid, ) => instance.get(sid, )) as EventListInstance; + + instance.get = function get(sid, ): EventContext { + return new EventContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Events`; + + instance.page = function page(params?: EventListInstancePageOptions | ((error: Error | null, items: EventPage) => any), callback?: (error: Error | null, items: EventPage) => any): Promise<EventPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["actorSid"] !== undefined) + data["ActorSid"] = params["actorSid"]; + if (params["eventType"] !== undefined) + data["EventType"] = params["eventType"]; + if (params["resourceSid"] !== undefined) + data["ResourceSid"] = params["resourceSid"]; + if (params["sourceIpAddress"] !== undefined) + data["SourceIpAddress"] = params["sourceIpAddress"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EventPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EventPage) => any): Promise<EventPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EventPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EventListInstancePageOptions | ((error: Error | null, items: ApiResponse<EventPage>) => any), callback?: (error: Error | null, items: ApiResponse<EventPage>) => any): Promise<ApiResponse<EventPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["actorSid"] !== undefined) + data["ActorSid"] = params["actorSid"]; + if (params["eventType"] !== undefined) + data["EventType"] = params["eventType"]; + if (params["resourceSid"] !== undefined) + data["ResourceSid"] = params["resourceSid"]; + if (params["sourceIpAddress"] !== undefined) + data["SourceIpAddress"] = params["sourceIpAddress"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EventPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EventPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EventPage>) => any): Promise<ApiResponse<EventPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EventPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EventPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EventPage extends Page<V1, EventPayload, EventResource, EventInstance> { +/** +* Initialize the EventPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: EventSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EventInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EventResource): EventInstance { + + return new EventInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/monitor/v2/alarm.ts b/rest/monitor/v2/alarm.ts new file mode 100644 index 000000000..0335eec85 --- /dev/null +++ b/rest/monitor/v2/alarm.ts @@ -0,0 +1,1026 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Alarms + * Manages Twilio Alarms + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Alarm object + */ +export class MonitorV2AlarmCreateObject { + /** + * Friendly name for alarm + */ + "friendlyName": string; + "queryType": QueryType; + /** + * Value to query for + */ + "query"?: string; + /** + * Threshold to send customer alarm notification + */ + "triggerValue": number; + "timeWindow": TimeWindow; + /** + * Email notifications to send + */ + "email"?: Array<string>; + /** + * Webhook notification to send + */ + "webhook"?: string; + /** + * Whether to send console notifications + */ + "consoleIndicator"?: boolean; + /** + * Description for the alarm. + */ + "description": string; + /** + * Is alarm enbled? Default is true. + */ + "enabled": boolean; + + constructor(payload) { + this.friendlyName = payload["friendlyName"]; + this.queryType = payload["queryType"]; + this.query = payload["query"]; + this.triggerValue = payload["triggerValue"]; + this.timeWindow = payload["timeWindow"]; + this.email = payload["email"]; + this.webhook = payload["webhook"]; + this.consoleIndicator = payload["consoleIndicator"]; + this.description = payload["description"]; + this.enabled = payload["enabled"]; + } +} + + +/** + * Type of query + */ +export type QueryType = 'ERROR_CODE'|'LOG_LEVEL'|'ALL'; + +/** + * Time window for alarm to trigger + */ +export type TimeWindow = 'FIVE_MINS'|'FIFTEEN_MINS'|'ONE_HOUR'|'TWELVE_HOURS'|'ONE_DAY'; + + + + +/** + * Options to pass to update a AlarmInstance + */ +export interface AlarmContextUpdateOptions { + /** */ + "monitorV2AlarmCreateObject": MonitorV2AlarmCreateObject; +} + +/** + * Options to pass to create a AlarmInstance + */ +export interface AlarmListInstanceCreateOptions { + /** */ + "monitorV2AlarmCreateObject": MonitorV2AlarmCreateObject; +} + +/** + * Options to pass to each + */ +export interface AlarmListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** */ + "sortOrder"?: 'asc' | 'desc'; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AlarmInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AlarmListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** */ + "sortOrder"?: 'asc' | 'desc'; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AlarmListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** */ + "sortOrder"?: 'asc' | 'desc'; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AlarmContext { + + /** + * Remove a AlarmInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a AlarmInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a AlarmInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlarmInstance + */ + fetch(callback?: (error: Error | null, item?: AlarmInstance) => any): Promise<AlarmInstance> + + /** + * Fetch a AlarmInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlarmInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AlarmInstance>) => any): Promise<ApiResponse<AlarmInstance>> + + /** + * Update a AlarmInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlarmInstance + */ + update(params: MonitorV2AlarmCreateObject, headers?: any, callback?: (error: Error | null, item?: AlarmInstance) => any): Promise<AlarmInstance>; + + /** + * Update a AlarmInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlarmInstance with HTTP metadata + */ + updateWithHttpInfo(params: MonitorV2AlarmCreateObject, headers?: any, callback?: (error: Error | null, item?: ApiResponse<AlarmInstance>) => any): Promise<ApiResponse<AlarmInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AlarmContextSolution { + "sid": string; +} + +export class AlarmContextImpl implements AlarmContext { + protected _solution: AlarmContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Alarms/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AlarmInstance) => any): Promise<AlarmInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AlarmInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AlarmInstance>) => any): Promise<ApiResponse<AlarmInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AlarmResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AlarmInstance> => ({ + ...response, + body: new AlarmInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: MonitorV2AlarmCreateObject, headers?: any,callback?: (error: Error | null, item?: AlarmInstance) => any): Promise<AlarmInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new AlarmInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: MonitorV2AlarmCreateObject, headers?: any,callback?: (error: Error | null, item?: ApiResponse<AlarmInstance>) => any): Promise<ApiResponse<AlarmInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<AlarmResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<AlarmInstance> => ({ + ...response, + body: new AlarmInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AlarmPayload extends TwilioResponsePayload { + alarms: AlarmResource[]; +} + +interface AlarmResource { + sid: string; + message: string; + code: number; + user_error: boolean; + http_status_code: number; + params: { [key: string]: string; }; + more_info: string; + status: number; + friendlyName: string; + queryType: QueryType; + query: string; + triggerValue: number; + timeWindow: TimeWindow; + email: Array<string>; + webhook: string; + consoleIndicator: boolean; + description: string; + enabled: boolean; + product: string; + alertConfigSid: string; + dateUpdated: Date; + dateCreated: Date; +} + +/** + * Alarm sid + */ +export class AlarmInstance { + protected _solution: AlarmContextSolution; + protected _context?: AlarmContext; + + constructor(protected _version: V2, payload: AlarmResource, sid?: string) { + + this.sid = (payload.sid); + this.message = (payload.message); + this.code = deserialize.integer(payload.code); + this.userError = (payload.user_error); + this.httpStatusCode = deserialize.integer(payload.http_status_code); + this.params = (payload.params); + this.moreInfo = (payload.more_info); + this.status = deserialize.integer(payload.status); + this.friendlyName = (payload.friendlyName); + this.queryType = payload.queryType; + this.query = (payload.query); + this.triggerValue = deserialize.integer(payload.triggerValue); + this.timeWindow = payload.timeWindow; + this.email = (payload.email); + this.webhook = (payload.webhook); + this.consoleIndicator = (payload.consoleIndicator); + this.description = (payload.description); + this.enabled = (payload.enabled); + this.product = (payload.product); + this.alertConfigSid = (payload.alertConfigSid); + this.dateUpdated = deserialize.iso8601DateTime(payload.dateUpdated); + this.dateCreated = deserialize.iso8601DateTime(payload.dateCreated); + + this._solution = { sid: sid, }; + } + + sid: string; + /** + * Error message + */ + message: string; + /** + * Twilio error code + */ + code: number; + /** + * Indicates if it was a user error + */ + userError: boolean; + /** + * Http error code returned + */ + httpStatusCode: number; + params: { [key: string]: string; }; + /** + * More information link + */ + moreInfo: string; + /** + * HTTP status code + */ + status: number; + /** + * Friendly name for alarm + */ + friendlyName: string; + queryType: QueryType; + /** + * Value to query for + */ + query: string; + /** + * Threshold to send customer alarm notification + */ + triggerValue: number; + timeWindow: TimeWindow; + /** + * Email notifications to send + */ + email: Array<string>; + /** + * Webhook notification to send + */ + webhook: string; + /** + * Whether to send console notifications + */ + consoleIndicator: boolean; + /** + * Description for the alarm. + */ + description: string; + /** + * Is alarm enbled? Default is true. + */ + enabled: boolean; + /** + * Product the alarm is related to. + */ + product: string; + /** + * Sid for the alarm + */ + alertConfigSid: string; + /** + * The date and time in UTC when the alarm was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format + */ + dateUpdated: Date; + /** + * The date and time in UTC when the alarm was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + + private get _proxy(): AlarmContext { + this._context = this._context || new AlarmContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a AlarmInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AlarmInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AlarmInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlarmInstance + */ + fetch(callback?: (error: Error | null, item?: AlarmInstance) => any): Promise<AlarmInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AlarmInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlarmInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AlarmInstance>) => any): Promise<ApiResponse<AlarmInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a AlarmInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlarmInstance + */ + update(params: MonitorV2AlarmCreateObject, headers?: any, callback?: (error: Error | null, item?: AlarmInstance) => any): Promise<AlarmInstance>; + + update(params?: any, callback?: (error: Error | null, item?: AlarmInstance) => any): Promise<AlarmInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a AlarmInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlarmInstance with HTTP metadata + */ + updateWithHttpInfo(params: MonitorV2AlarmCreateObject, headers?: any, callback?: (error: Error | null, item?: ApiResponse<AlarmInstance>) => any): Promise<ApiResponse<AlarmInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<AlarmInstance>) => any): Promise<ApiResponse<AlarmInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + message: this.message, + code: this.code, + userError: this.userError, + httpStatusCode: this.httpStatusCode, + params: this.params, + moreInfo: this.moreInfo, + status: this.status, + friendlyName: this.friendlyName, + queryType: this.queryType, + query: this.query, + triggerValue: this.triggerValue, + timeWindow: this.timeWindow, + email: this.email, + webhook: this.webhook, + consoleIndicator: this.consoleIndicator, + description: this.description, + enabled: this.enabled, + product: this.product, + alertConfigSid: this.alertConfigSid, + dateUpdated: this.dateUpdated, + dateCreated: this.dateCreated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AlarmSolution { +} + +export interface AlarmListInstance { + _version: V2; + _solution: AlarmSolution; + _uri: string; + + (sid: string, ): AlarmContext; + get(sid: string, ): AlarmContext; + + + + + + + + + /** + * Create a AlarmInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlarmInstance + */ + create(params: MonitorV2AlarmCreateObject, headers?: any, callback?: (error: Error | null, item?: AlarmInstance) => any): Promise<AlarmInstance>; + + /** + * Create a AlarmInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AlarmInstance with HTTP metadata + */ + createWithHttpInfo(params: MonitorV2AlarmCreateObject, headers?: any, callback?: (error: Error | null, item?: ApiResponse<AlarmInstance>) => any): Promise<ApiResponse<AlarmInstance>>; + + + + + /** + * Streams AlarmInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlarmListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AlarmInstance, done: (err?: Error) => void) => void): void; + each(params: AlarmListInstanceEachOptions, callback?: (item: AlarmInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AlarmInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlarmListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AlarmInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AlarmListInstanceEachOptions, callback?: (item: AlarmInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AlarmInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AlarmPage) => any): Promise<AlarmPage>; + /** + * Retrieve a single target page of AlarmInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AlarmPage>) => any): Promise<ApiResponse<AlarmPage>>; + /** + * Lists AlarmInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlarmListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AlarmInstance[]) => any): Promise<AlarmInstance[]>; + list(params: AlarmListInstanceOptions, callback?: (error: Error | null, items: AlarmInstance[]) => any): Promise<AlarmInstance[]>; + /** + * Lists AlarmInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlarmListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AlarmInstance[]>) => any): Promise<ApiResponse<AlarmInstance[]>>; + listWithHttpInfo(params: AlarmListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AlarmInstance[]>) => any): Promise<ApiResponse<AlarmInstance[]>>; + /** + * Retrieve a single page of AlarmInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlarmListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AlarmPage) => any): Promise<AlarmPage>; + page(params: AlarmListInstancePageOptions, callback?: (error: Error | null, items: AlarmPage) => any): Promise<AlarmPage>; + /** + * Retrieve a single page of AlarmInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AlarmListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AlarmPage>) => any): Promise<ApiResponse<AlarmPage>>; + pageWithHttpInfo(params: AlarmListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AlarmPage>) => any): Promise<ApiResponse<AlarmPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AlarmListInstance(version: V2): AlarmListInstance { + const instance = ((sid, ) => instance.get(sid, )) as AlarmListInstance; + + instance.get = function get(sid, ): AlarmContext { + return new AlarmContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Alarms`; + + instance.create = function create(params: MonitorV2AlarmCreateObject, headers?: any, callback?: (error: Error | null, items: AlarmInstance) => any): Promise<AlarmInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AlarmInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MonitorV2AlarmCreateObject, headers?: any, callback?: (error: Error | null, items: ApiResponse<AlarmInstance>) => any): Promise<ApiResponse<AlarmInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<AlarmResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<AlarmInstance> => ({ + ...response, + body: new AlarmInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AlarmListInstancePageOptions | ((error: Error | null, items: AlarmPage) => any), callback?: (error: Error | null, items: AlarmPage) => any): Promise<AlarmPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["sortOrder"] !== undefined) + data["SortOrder"] = params["sortOrder"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AlarmPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AlarmPage) => any): Promise<AlarmPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AlarmPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AlarmListInstancePageOptions | ((error: Error | null, items: ApiResponse<AlarmPage>) => any), callback?: (error: Error | null, items: ApiResponse<AlarmPage>) => any): Promise<ApiResponse<AlarmPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["sortOrder"] !== undefined) + data["SortOrder"] = params["sortOrder"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AlarmPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AlarmPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AlarmPage>) => any): Promise<ApiResponse<AlarmPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AlarmPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AlarmPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AlarmPage extends Page<V2, AlarmPayload, AlarmResource, AlarmInstance> { +/** +* Initialize the AlarmPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: AlarmSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AlarmInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AlarmResource): AlarmInstance { + + return new AlarmInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/monitor/v2/status.ts b/rest/monitor/v2/status.ts new file mode 100644 index 000000000..489784a5d --- /dev/null +++ b/rest/monitor/v2/status.ts @@ -0,0 +1,251 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Alarms + * Manages Twilio Alarms + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Enable or disable alarm + */ +export class MonitorV2AlarmStatus { + /** + * status of alarm + */ + "enabled": boolean; + + constructor(payload) { + this.enabled = payload["enabled"]; + } +} + + + +/** + * Options to pass to update a StatusInstance + */ +export interface StatusListInstanceUpdateOptions { + /** */ + "monitorV2AlarmStatus": MonitorV2AlarmStatus; +} + + +export interface StatusSolution { + sid: string; +} + +export interface StatusListInstance { + _version: V2; + _solution: StatusSolution; + _uri: string; + + + + /** + * Update a StatusInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StatusInstance + */ + update(params: MonitorV2AlarmStatus, headers?: any, callback?: (error: Error | null, item?: StatusInstance) => any): Promise<StatusInstance>; + + /** + * Update a StatusInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StatusInstance with HTTP metadata + */ + updateWithHttpInfo(params: MonitorV2AlarmStatus, headers?: any, callback?: (error: Error | null, item?: ApiResponse<StatusInstance>) => any): Promise<ApiResponse<StatusInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function StatusListInstance(version: V2, sid: string): StatusListInstance { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + const instance = {} as StatusListInstance; + + instance._version = version; + instance._solution = { sid, }; + instance._uri = `/Alarms/${sid}/status`; + + instance.update = function update(params: MonitorV2AlarmStatus, headers?: any, callback?: (error: Error | null, items: StatusInstance) => any): Promise<StatusInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new StatusInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.updateWithHttpInfo = function updateWithHttpInfo(params: MonitorV2AlarmStatus, headers?: any, callback?: (error: Error | null, items: ApiResponse<StatusInstance>) => any): Promise<ApiResponse<StatusInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<StatusResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<StatusInstance> => ({ + ...response, + body: new StatusInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface StatusPayload extends StatusResource {} + +interface StatusResource { + message: string; + code: number; + user_error: boolean; + http_status_code: number; + params: { [key: string]: string; }; + more_info: string; + status: number; +} + +/** + * Twilio error response + */ +export class StatusInstance { + + constructor(protected _version: V2, payload: StatusResource, sid?: string) { + + this.message = (payload.message); + this.code = deserialize.integer(payload.code); + this.userError = (payload.user_error); + this.httpStatusCode = deserialize.integer(payload.http_status_code); + this.params = (payload.params); + this.moreInfo = (payload.more_info); + this.status = deserialize.integer(payload.status); + + } + + /** + * Error message + */ + message: string; + /** + * Twilio error code + */ + code: number; + /** + * Indicates if it was a user error + */ + userError: boolean; + /** + * Http error code returned + */ + httpStatusCode: number; + params: { [key: string]: string; }; + /** + * More information link + */ + moreInfo: string; + /** + * HTTP status code + */ + status: number; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + code: this.code, + userError: this.userError, + httpStatusCode: this.httpStatusCode, + params: this.params, + moreInfo: this.moreInfo, + status: this.status, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/notify/V1.ts b/rest/notify/V1.ts new file mode 100644 index 000000000..213722c26 --- /dev/null +++ b/rest/notify/V1.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Notify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import NotifyBase from "../NotifyBase"; +import Version from "../../base/Version"; +import { CredentialListInstance } from "./v1/credential"; +import { ServiceListInstance } from "./v1/service"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Notify + * + * @param domain - The Twilio (Twilio.Notify) domain + */ + constructor(domain: NotifyBase) { + super(domain, "v1"); + } + + /** credentials - { Twilio.Notify.V1.CredentialListInstance } resource */ + protected _credentials?: CredentialListInstance; + /** services - { Twilio.Notify.V1.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + + /** Getter for credentials resource */ + get credentials(): CredentialListInstance { + this._credentials = this._credentials || CredentialListInstance(this); + return this._credentials; + } + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + +} diff --git a/rest/notify/v1/credential.ts b/rest/notify/v1/credential.ts new file mode 100644 index 000000000..43d7f711a --- /dev/null +++ b/rest/notify/v1/credential.ts @@ -0,0 +1,971 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Notify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The Credential type. Can be: `gcm`, `fcm`, or `apn`. + */ +export type CredentialPushService = 'gcm'|'apn'|'fcm'; + + + + +/** + * Options to pass to update a CredentialInstance + */ +export interface CredentialContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` */ + "certificate"?: string; + /** [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` */ + "privateKey"?: string; + /** [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. */ + "sandbox"?: boolean; + /** [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. */ + "apiKey"?: string; + /** [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. */ + "secret"?: string; +} + +/** + * Options to pass to create a CredentialInstance + */ +export interface CredentialListInstanceCreateOptions { + /** */ + "type": CredentialPushService; + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` */ + "certificate"?: string; + /** [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` */ + "privateKey"?: string; + /** [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. */ + "sandbox"?: boolean; + /** [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. */ + "apiKey"?: string; + /** [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. */ + "secret"?: string; +} + +/** + * Options to pass to each + */ +export interface CredentialListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CredentialInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CredentialListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CredentialListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CredentialContext { + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise<CredentialInstance> + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>> + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise<CredentialInstance>; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise<CredentialInstance>; + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CredentialContextSolution { + "sid": string; +} + +export class CredentialContextImpl implements CredentialContext { + protected _solution: CredentialContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Credentials/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise<CredentialInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CredentialResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CredentialInstance> => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: CredentialInstance) => any),callback?: (error: Error | null, item?: CredentialInstance) => any): Promise<CredentialInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: CredentialContextUpdateOptions | ((error: Error | null, item?: ApiResponse<CredentialInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<CredentialResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CredentialInstance> => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CredentialPayload extends TwilioResponsePayload { + credentials: CredentialResource[]; +} + +interface CredentialResource { + sid: string; + account_sid: string; + friendly_name: string; + type: CredentialPushService; + sandbox: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CredentialInstance { + protected _solution: CredentialContextSolution; + protected _context?: CredentialContext; + + constructor(protected _version: V1, payload: CredentialResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.sandbox = (payload.sandbox); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Credential resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + type: CredentialPushService; + /** + * [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + */ + sandbox: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Credential resource. + */ + url: string; + + private get _proxy(): CredentialContext { + this._context = this._context || new CredentialContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise<CredentialInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CredentialInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(callback?: (error: Error | null, item?: CredentialInstance) => any): Promise<CredentialInstance>; + /** + * Update a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + update(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise<CredentialInstance>; + + update(params?: any, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise<CredentialInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a CredentialInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>>; + /** + * Update a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + updateWithHttpInfo(params: CredentialContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + type: this.type, + sandbox: this.sandbox, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CredentialSolution { +} + +export interface CredentialListInstance { + _version: V1; + _solution: CredentialSolution; + _uri: string; + + (sid: string, ): CredentialContext; + get(sid: string, ): CredentialContext; + + + + + + + + + /** + * Create a CredentialInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance + */ + create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: CredentialInstance) => any): Promise<CredentialInstance>; + + /** + * Create a CredentialInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialInstance with HTTP metadata + */ + createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>>; + + + + + /** + * Streams CredentialInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + each(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CredentialInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CredentialListInstanceEachOptions, callback?: (item: CredentialInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise<CredentialPage>; + /** + * Retrieve a single target page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CredentialPage>) => any): Promise<ApiResponse<CredentialPage>>; + /** + * Lists CredentialInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise<CredentialInstance[]>; + list(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: CredentialInstance[]) => any): Promise<CredentialInstance[]>; + /** + * Lists CredentialInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CredentialInstance[]>) => any): Promise<ApiResponse<CredentialInstance[]>>; + listWithHttpInfo(params: CredentialListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CredentialInstance[]>) => any): Promise<ApiResponse<CredentialInstance[]>>; + /** + * Retrieve a single page of CredentialInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CredentialPage) => any): Promise<CredentialPage>; + page(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: CredentialPage) => any): Promise<CredentialPage>; + /** + * Retrieve a single page of CredentialInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CredentialPage>) => any): Promise<ApiResponse<CredentialPage>>; + pageWithHttpInfo(params: CredentialListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CredentialPage>) => any): Promise<ApiResponse<CredentialPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CredentialListInstance(version: V1): CredentialListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CredentialListInstance; + + instance.get = function get(sid, ): CredentialContext { + return new CredentialContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Credentials`; + + instance.create = function create(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: CredentialInstance) => any): Promise<CredentialInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CredentialListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<CredentialInstance>) => any): Promise<ApiResponse<CredentialInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["Type"] = params["type"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["certificate"] !== undefined) + data["Certificate"] = params["certificate"]; + if (params["privateKey"] !== undefined) + data["PrivateKey"] = params["privateKey"]; + if (params["sandbox"] !== undefined) + data["Sandbox"] = serialize.bool(params["sandbox"]); + if (params["apiKey"] !== undefined) + data["ApiKey"] = params["apiKey"]; + if (params["secret"] !== undefined) + data["Secret"] = params["secret"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CredentialResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CredentialInstance> => ({ + ...response, + body: new CredentialInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CredentialListInstancePageOptions | ((error: Error | null, items: CredentialPage) => any), callback?: (error: Error | null, items: CredentialPage) => any): Promise<CredentialPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CredentialPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialPage) => any): Promise<CredentialPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CredentialPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CredentialListInstancePageOptions | ((error: Error | null, items: ApiResponse<CredentialPage>) => any), callback?: (error: Error | null, items: ApiResponse<CredentialPage>) => any): Promise<ApiResponse<CredentialPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CredentialPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CredentialPage>) => any): Promise<ApiResponse<CredentialPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CredentialPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CredentialPage extends Page<V1, CredentialPayload, CredentialResource, CredentialInstance> { +/** +* Initialize the CredentialPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CredentialSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CredentialInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CredentialResource): CredentialInstance { + + return new CredentialInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/notify/v1/service.ts b/rest/notify/v1/service.ts new file mode 100644 index 000000000..5a0067679 --- /dev/null +++ b/rest/notify/v1/service.ts @@ -0,0 +1,1197 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Notify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { BindingListInstance } from "./service/binding"; +import { NotificationListInstance } from "./service/notification"; + + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. */ + "apnCredentialSid"?: string; + /** The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. */ + "gcmCredentialSid"?: string; + /** The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. */ + "messagingServiceSid"?: string; + /** Deprecated. */ + "facebookMessengerPageId"?: string; + /** The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. */ + "defaultApnNotificationProtocolVersion"?: string; + /** The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. */ + "defaultGcmNotificationProtocolVersion"?: string; + /** The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. */ + "fcmCredentialSid"?: string; + /** The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. */ + "defaultFcmNotificationProtocolVersion"?: string; + /** Whether to log notifications. Can be: `true` or `false` and the default is `true`. */ + "logEnabled"?: boolean; + /** Deprecated. */ + "alexaSkillId"?: string; + /** Deprecated. */ + "defaultAlexaNotificationProtocolVersion"?: string; + /** URL to send delivery status callback. */ + "deliveryCallbackUrl"?: string; + /** Callback configuration that enables delivery callbacks, default false */ + "deliveryCallbackEnabled"?: boolean; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. */ + "apnCredentialSid"?: string; + /** The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. */ + "gcmCredentialSid"?: string; + /** The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. */ + "messagingServiceSid"?: string; + /** Deprecated. */ + "facebookMessengerPageId"?: string; + /** The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. */ + "defaultApnNotificationProtocolVersion"?: string; + /** The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. */ + "defaultGcmNotificationProtocolVersion"?: string; + /** The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. */ + "fcmCredentialSid"?: string; + /** The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. */ + "defaultFcmNotificationProtocolVersion"?: string; + /** Whether to log notifications. Can be: `true` or `false` and the default is `true`. */ + "logEnabled"?: boolean; + /** Deprecated. */ + "alexaSkillId"?: string; + /** Deprecated. */ + "defaultAlexaNotificationProtocolVersion"?: string; + /** URL to send delivery status callback. */ + "deliveryCallbackUrl"?: string; + /** Callback configuration that enables delivery callbacks, default false */ + "deliveryCallbackEnabled"?: boolean; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** The string that identifies the Service resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** The string that identifies the Service resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** The string that identifies the Service resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + bindings: BindingListInstance; + notifications: NotificationListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _bindings?: BindingListInstance; + protected _notifications?: NotificationListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get bindings(): BindingListInstance { + this._bindings = this._bindings || BindingListInstance(this._version, this._solution.sid); + return this._bindings; + } + + get notifications(): NotificationListInstance { + this._notifications = this._notifications || NotificationListInstance(this._version, this._solution.sid); + return this._notifications; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["apnCredentialSid"] !== undefined) + data["ApnCredentialSid"] = params["apnCredentialSid"]; + if (params["gcmCredentialSid"] !== undefined) + data["GcmCredentialSid"] = params["gcmCredentialSid"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["facebookMessengerPageId"] !== undefined) + data["FacebookMessengerPageId"] = params["facebookMessengerPageId"]; + if (params["defaultApnNotificationProtocolVersion"] !== undefined) + data["DefaultApnNotificationProtocolVersion"] = params["defaultApnNotificationProtocolVersion"]; + if (params["defaultGcmNotificationProtocolVersion"] !== undefined) + data["DefaultGcmNotificationProtocolVersion"] = params["defaultGcmNotificationProtocolVersion"]; + if (params["fcmCredentialSid"] !== undefined) + data["FcmCredentialSid"] = params["fcmCredentialSid"]; + if (params["defaultFcmNotificationProtocolVersion"] !== undefined) + data["DefaultFcmNotificationProtocolVersion"] = params["defaultFcmNotificationProtocolVersion"]; + if (params["logEnabled"] !== undefined) + data["LogEnabled"] = serialize.bool(params["logEnabled"]); + if (params["alexaSkillId"] !== undefined) + data["AlexaSkillId"] = params["alexaSkillId"]; + if (params["defaultAlexaNotificationProtocolVersion"] !== undefined) + data["DefaultAlexaNotificationProtocolVersion"] = params["defaultAlexaNotificationProtocolVersion"]; + if (params["deliveryCallbackUrl"] !== undefined) + data["DeliveryCallbackUrl"] = params["deliveryCallbackUrl"]; + if (params["deliveryCallbackEnabled"] !== undefined) + data["DeliveryCallbackEnabled"] = serialize.bool(params["deliveryCallbackEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ServiceInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["apnCredentialSid"] !== undefined) + data["ApnCredentialSid"] = params["apnCredentialSid"]; + if (params["gcmCredentialSid"] !== undefined) + data["GcmCredentialSid"] = params["gcmCredentialSid"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["facebookMessengerPageId"] !== undefined) + data["FacebookMessengerPageId"] = params["facebookMessengerPageId"]; + if (params["defaultApnNotificationProtocolVersion"] !== undefined) + data["DefaultApnNotificationProtocolVersion"] = params["defaultApnNotificationProtocolVersion"]; + if (params["defaultGcmNotificationProtocolVersion"] !== undefined) + data["DefaultGcmNotificationProtocolVersion"] = params["defaultGcmNotificationProtocolVersion"]; + if (params["fcmCredentialSid"] !== undefined) + data["FcmCredentialSid"] = params["fcmCredentialSid"]; + if (params["defaultFcmNotificationProtocolVersion"] !== undefined) + data["DefaultFcmNotificationProtocolVersion"] = params["defaultFcmNotificationProtocolVersion"]; + if (params["logEnabled"] !== undefined) + data["LogEnabled"] = serialize.bool(params["logEnabled"]); + if (params["alexaSkillId"] !== undefined) + data["AlexaSkillId"] = params["alexaSkillId"]; + if (params["defaultAlexaNotificationProtocolVersion"] !== undefined) + data["DefaultAlexaNotificationProtocolVersion"] = params["defaultAlexaNotificationProtocolVersion"]; + if (params["deliveryCallbackUrl"] !== undefined) + data["DeliveryCallbackUrl"] = params["deliveryCallbackUrl"]; + if (params["deliveryCallbackEnabled"] !== undefined) + data["DeliveryCallbackEnabled"] = serialize.bool(params["deliveryCallbackEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + sid: string; + account_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + apn_credential_sid: string; + gcm_credential_sid: string; + fcm_credential_sid: string; + messaging_service_sid: string; + facebook_messenger_page_id: string; + default_apn_notification_protocol_version: string; + default_gcm_notification_protocol_version: string; + default_fcm_notification_protocol_version: string; + log_enabled: boolean; + url: string; + links: Record<string, string>; + alexa_skill_id: string; + default_alexa_notification_protocol_version: string; + delivery_callback_url: string; + delivery_callback_enabled: boolean; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V1, payload: ServiceResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.apnCredentialSid = (payload.apn_credential_sid); + this.gcmCredentialSid = (payload.gcm_credential_sid); + this.fcmCredentialSid = (payload.fcm_credential_sid); + this.messagingServiceSid = (payload.messaging_service_sid); + this.facebookMessengerPageId = (payload.facebook_messenger_page_id); + this.defaultApnNotificationProtocolVersion = (payload.default_apn_notification_protocol_version); + this.defaultGcmNotificationProtocolVersion = (payload.default_gcm_notification_protocol_version); + this.defaultFcmNotificationProtocolVersion = (payload.default_fcm_notification_protocol_version); + this.logEnabled = (payload.log_enabled); + this.url = (payload.url); + this.links = (payload.links); + this.alexaSkillId = (payload.alexa_skill_id); + this.defaultAlexaNotificationProtocolVersion = (payload.default_alexa_notification_protocol_version); + this.deliveryCallbackUrl = (payload.delivery_callback_url); + this.deliveryCallbackEnabled = (payload.delivery_callback_enabled); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Service resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + */ + apnCredentialSid: string; + /** + * The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + */ + gcmCredentialSid: string; + /** + * The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + */ + fcmCredentialSid: string; + /** + * The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. In order to send SMS notifications this parameter has to be set. + */ + messagingServiceSid: string; + /** + * Deprecated. + */ + facebookMessengerPageId: string; + /** + * The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + */ + defaultApnNotificationProtocolVersion: string; + /** + * The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + */ + defaultGcmNotificationProtocolVersion: string; + /** + * The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + */ + defaultFcmNotificationProtocolVersion: string; + /** + * Whether to log notifications. Can be: `true` or `false` and the default is `true`. + */ + logEnabled: boolean; + /** + * The absolute URL of the Service resource. + */ + url: string; + /** + * The URLs of the Binding, Notification, Segment, and User resources related to the service. + */ + links: Record<string, string>; + /** + * Deprecated. + */ + alexaSkillId: string; + /** + * Deprecated. + */ + defaultAlexaNotificationProtocolVersion: string; + /** + * URL to send delivery status callback. + */ + deliveryCallbackUrl: string; + /** + * Callback configuration that enables delivery callbacks, default false + */ + deliveryCallbackEnabled: boolean; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the bindings. + */ + bindings(): BindingListInstance { + return this._proxy.bindings; + } + + /** + * Access the notifications. + */ + notifications(): NotificationListInstance { + return this._proxy.notifications; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + apnCredentialSid: this.apnCredentialSid, + gcmCredentialSid: this.gcmCredentialSid, + fcmCredentialSid: this.fcmCredentialSid, + messagingServiceSid: this.messagingServiceSid, + facebookMessengerPageId: this.facebookMessengerPageId, + defaultApnNotificationProtocolVersion: this.defaultApnNotificationProtocolVersion, + defaultGcmNotificationProtocolVersion: this.defaultGcmNotificationProtocolVersion, + defaultFcmNotificationProtocolVersion: this.defaultFcmNotificationProtocolVersion, + logEnabled: this.logEnabled, + url: this.url, + links: this.links, + alexaSkillId: this.alexaSkillId, + defaultAlexaNotificationProtocolVersion: this.defaultAlexaNotificationProtocolVersion, + deliveryCallbackUrl: this.deliveryCallbackUrl, + deliveryCallbackEnabled: this.deliveryCallbackEnabled, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V1; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V1): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params?: ServiceListInstanceCreateOptions | ((error: Error | null, items: ServiceInstance) => any), callback?: (error: Error | null, items: ServiceInstance) => any): Promise<ServiceInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["apnCredentialSid"] !== undefined) + data["ApnCredentialSid"] = params["apnCredentialSid"]; + if (params["gcmCredentialSid"] !== undefined) + data["GcmCredentialSid"] = params["gcmCredentialSid"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["facebookMessengerPageId"] !== undefined) + data["FacebookMessengerPageId"] = params["facebookMessengerPageId"]; + if (params["defaultApnNotificationProtocolVersion"] !== undefined) + data["DefaultApnNotificationProtocolVersion"] = params["defaultApnNotificationProtocolVersion"]; + if (params["defaultGcmNotificationProtocolVersion"] !== undefined) + data["DefaultGcmNotificationProtocolVersion"] = params["defaultGcmNotificationProtocolVersion"]; + if (params["fcmCredentialSid"] !== undefined) + data["FcmCredentialSid"] = params["fcmCredentialSid"]; + if (params["defaultFcmNotificationProtocolVersion"] !== undefined) + data["DefaultFcmNotificationProtocolVersion"] = params["defaultFcmNotificationProtocolVersion"]; + if (params["logEnabled"] !== undefined) + data["LogEnabled"] = serialize.bool(params["logEnabled"]); + if (params["alexaSkillId"] !== undefined) + data["AlexaSkillId"] = params["alexaSkillId"]; + if (params["defaultAlexaNotificationProtocolVersion"] !== undefined) + data["DefaultAlexaNotificationProtocolVersion"] = params["defaultAlexaNotificationProtocolVersion"]; + if (params["deliveryCallbackUrl"] !== undefined) + data["DeliveryCallbackUrl"] = params["deliveryCallbackUrl"]; + if (params["deliveryCallbackEnabled"] !== undefined) + data["DeliveryCallbackEnabled"] = serialize.bool(params["deliveryCallbackEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ServiceListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<ServiceInstance>) => any), callback?: (error: Error | null, items: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["apnCredentialSid"] !== undefined) + data["ApnCredentialSid"] = params["apnCredentialSid"]; + if (params["gcmCredentialSid"] !== undefined) + data["GcmCredentialSid"] = params["gcmCredentialSid"]; + if (params["messagingServiceSid"] !== undefined) + data["MessagingServiceSid"] = params["messagingServiceSid"]; + if (params["facebookMessengerPageId"] !== undefined) + data["FacebookMessengerPageId"] = params["facebookMessengerPageId"]; + if (params["defaultApnNotificationProtocolVersion"] !== undefined) + data["DefaultApnNotificationProtocolVersion"] = params["defaultApnNotificationProtocolVersion"]; + if (params["defaultGcmNotificationProtocolVersion"] !== undefined) + data["DefaultGcmNotificationProtocolVersion"] = params["defaultGcmNotificationProtocolVersion"]; + if (params["fcmCredentialSid"] !== undefined) + data["FcmCredentialSid"] = params["fcmCredentialSid"]; + if (params["defaultFcmNotificationProtocolVersion"] !== undefined) + data["DefaultFcmNotificationProtocolVersion"] = params["defaultFcmNotificationProtocolVersion"]; + if (params["logEnabled"] !== undefined) + data["LogEnabled"] = serialize.bool(params["logEnabled"]); + if (params["alexaSkillId"] !== undefined) + data["AlexaSkillId"] = params["alexaSkillId"]; + if (params["defaultAlexaNotificationProtocolVersion"] !== undefined) + data["DefaultAlexaNotificationProtocolVersion"] = params["defaultAlexaNotificationProtocolVersion"]; + if (params["deliveryCallbackUrl"] !== undefined) + data["DeliveryCallbackUrl"] = params["deliveryCallbackUrl"]; + if (params["deliveryCallbackEnabled"] !== undefined) + data["DeliveryCallbackEnabled"] = serialize.bool(params["deliveryCallbackEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse<ServicePage>) => any), callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page<V1, ServicePayload, ServiceResource, ServiceInstance> { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/notify/v1/service/binding.ts b/rest/notify/v1/service/binding.ts new file mode 100644 index 000000000..57b64a148 --- /dev/null +++ b/rest/notify/v1/service/binding.ts @@ -0,0 +1,892 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Notify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The transport technology to use for the Binding. Can be: `apn`, `fcm`, `gcm`, `sms`, or `facebook-messenger`. + */ +export type BindingBindingType = 'apn'|'gcm'|'sms'|'fcm'|'facebook-messenger'|'alexa'; + + + + +/** + * Options to pass to create a BindingInstance + */ +export interface BindingListInstanceCreateOptions { + /** The `identity` value that uniquely identifies the new resource\\\'s [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. */ + "identity": string; + /** */ + "bindingType": BindingBindingType; + /** The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. */ + "address": string; + /** A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. */ + "tag"?: Array<string>; + /** The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. */ + "notificationProtocolVersion"?: string; + /** The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. */ + "credentialSid"?: string; + /** Deprecated. */ + "endpoint"?: string; +} + +/** + * Options to pass to each + */ +export interface BindingListInstanceEachOptions { + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. */ + "endDate"?: Date; + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the resources to read. */ + "identity"?: Array<string>; + /** Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. */ + "tag"?: Array<string>; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BindingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BindingListInstanceOptions { + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. */ + "endDate"?: Date; + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the resources to read. */ + "identity"?: Array<string>; + /** Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. */ + "tag"?: Array<string>; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BindingListInstancePageOptions { + /** Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. */ + "endDate"?: Date; + /** The [User](https://www.twilio.com/docs/chat/rest/user-resource)\'s `identity` value of the resources to read. */ + "identity"?: Array<string>; + /** Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. */ + "tag"?: Array<string>; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface BindingContext { + + /** + * Remove a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance + */ + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise<BindingInstance> + + /** + * Fetch a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BindingInstance>) => any): Promise<ApiResponse<BindingInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BindingContextSolution { + "serviceSid": string; + "sid": string; +} + +export class BindingContextImpl implements BindingContext { + protected _solution: BindingContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Bindings/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise<BindingInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BindingInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BindingInstance>) => any): Promise<ApiResponse<BindingInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<BindingResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<BindingInstance> => ({ + ...response, + body: new BindingInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BindingPayload extends TwilioResponsePayload { + bindings: BindingResource[]; +} + +interface BindingResource { + sid: string; + account_sid: string; + service_sid: string; + credential_sid: string; + date_created: Date; + date_updated: Date; + notification_protocol_version: string; + endpoint: string; + identity: string; + binding_type: string; + address: string; + tags: Array<string>; + url: string; + links: Record<string, string>; +} + +export class BindingInstance { + protected _solution: BindingContextSolution; + protected _context?: BindingContext; + + constructor(protected _version: V1, payload: BindingResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.credentialSid = (payload.credential_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.notificationProtocolVersion = (payload.notification_protocol_version); + this.endpoint = (payload.endpoint); + this.identity = (payload.identity); + this.bindingType = (payload.binding_type); + this.address = (payload.address); + this.tags = (payload.tags); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Binding resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Binding resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applicable only to `apn`, `fcm`, and `gcm` type Bindings. + */ + credentialSid: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` in the [Service](https://www.twilio.com/docs/notify/api/service-resource) for the protocol. The current version is `\"3\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + */ + notificationProtocolVersion: string; + /** + * Deprecated. + */ + endpoint: string; + /** + * The `identity` value that uniquely identifies the resource\'s [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + */ + identity: string; + /** + * The transport technology to use for the Binding. Can be: `apn`, `fcm`, `gcm`, `sms`, or `facebook-messenger`. + */ + bindingType: string; + /** + * The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + */ + address: string; + /** + * The list of tags associated with this Binding. Tags can be used to select the Bindings to use when sending a notification. Maximum 20 tags are allowed. + */ + tags: Array<string>; + /** + * The absolute URL of the Binding resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): BindingContext { + this._context = this._context || new BindingContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a BindingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance + */ + fetch(callback?: (error: Error | null, item?: BindingInstance) => any): Promise<BindingInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BindingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BindingInstance>) => any): Promise<ApiResponse<BindingInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + credentialSid: this.credentialSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + notificationProtocolVersion: this.notificationProtocolVersion, + endpoint: this.endpoint, + identity: this.identity, + bindingType: this.bindingType, + address: this.address, + tags: this.tags, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BindingSolution { + serviceSid: string; +} + +export interface BindingListInstance { + _version: V1; + _solution: BindingSolution; + _uri: string; + + (sid: string, ): BindingContext; + get(sid: string, ): BindingContext; + + + + + + + /** + * Create a BindingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance + */ + create(params: BindingListInstanceCreateOptions, callback?: (error: Error | null, item?: BindingInstance) => any): Promise<BindingInstance>; + + /** + * Create a BindingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BindingInstance with HTTP metadata + */ + createWithHttpInfo(params: BindingListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<BindingInstance>) => any): Promise<ApiResponse<BindingInstance>>; + + + + + /** + * Streams BindingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + each(params: BindingListInstanceEachOptions, callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BindingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BindingListInstanceEachOptions, callback?: (item: BindingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BindingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BindingPage) => any): Promise<BindingPage>; + /** + * Retrieve a single target page of BindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<BindingPage>) => any): Promise<ApiResponse<BindingPage>>; + /** + * Lists BindingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BindingInstance[]) => any): Promise<BindingInstance[]>; + list(params: BindingListInstanceOptions, callback?: (error: Error | null, items: BindingInstance[]) => any): Promise<BindingInstance[]>; + /** + * Lists BindingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BindingInstance[]>) => any): Promise<ApiResponse<BindingInstance[]>>; + listWithHttpInfo(params: BindingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<BindingInstance[]>) => any): Promise<ApiResponse<BindingInstance[]>>; + /** + * Retrieve a single page of BindingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BindingPage) => any): Promise<BindingPage>; + page(params: BindingListInstancePageOptions, callback?: (error: Error | null, items: BindingPage) => any): Promise<BindingPage>; + /** + * Retrieve a single page of BindingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BindingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BindingPage>) => any): Promise<ApiResponse<BindingPage>>; + pageWithHttpInfo(params: BindingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<BindingPage>) => any): Promise<ApiResponse<BindingPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BindingListInstance(version: V1, serviceSid: string): BindingListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as BindingListInstance; + + instance.get = function get(sid, ): BindingContext { + return new BindingContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Bindings`; + + instance.create = function create(params: BindingListInstanceCreateOptions, callback?: (error: Error | null, items: BindingInstance) => any): Promise<BindingInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + if (params["bindingType"] === null || params["bindingType"] === undefined) { + throw new Error('Required parameter "params[\'bindingType\']" missing.'); + } + + if (params["address"] === null || params["address"] === undefined) { + throw new Error('Required parameter "params[\'address\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + + data["BindingType"] = params["bindingType"]; + + data["Address"] = params["address"]; + if (params["tag"] !== undefined) + data["Tag"] = serialize.map(params["tag"], (e: string) => (e)); + if (params["notificationProtocolVersion"] !== undefined) + data["NotificationProtocolVersion"] = params["notificationProtocolVersion"]; + if (params["credentialSid"] !== undefined) + data["CredentialSid"] = params["credentialSid"]; + if (params["endpoint"] !== undefined) + data["Endpoint"] = params["endpoint"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BindingInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: BindingListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<BindingInstance>) => any): Promise<ApiResponse<BindingInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + if (params["bindingType"] === null || params["bindingType"] === undefined) { + throw new Error('Required parameter "params[\'bindingType\']" missing.'); + } + + if (params["address"] === null || params["address"] === undefined) { + throw new Error('Required parameter "params[\'address\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + + data["BindingType"] = params["bindingType"]; + + data["Address"] = params["address"]; + if (params["tag"] !== undefined) + data["Tag"] = serialize.map(params["tag"], (e: string) => (e)); + if (params["notificationProtocolVersion"] !== undefined) + data["NotificationProtocolVersion"] = params["notificationProtocolVersion"]; + if (params["credentialSid"] !== undefined) + data["CredentialSid"] = params["credentialSid"]; + if (params["endpoint"] !== undefined) + data["Endpoint"] = params["endpoint"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BindingResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BindingInstance> => ({ + ...response, + body: new BindingInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: BindingListInstancePageOptions | ((error: Error | null, items: BindingPage) => any), callback?: (error: Error | null, items: BindingPage) => any): Promise<BindingPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["tag"] !== undefined) + data["Tag"] = serialize.map(params["tag"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BindingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BindingPage) => any): Promise<BindingPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BindingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BindingListInstancePageOptions | ((error: Error | null, items: ApiResponse<BindingPage>) => any), callback?: (error: Error | null, items: ApiResponse<BindingPage>) => any): Promise<ApiResponse<BindingPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601Date(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601Date(params["endDate"]); + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["tag"] !== undefined) + data["Tag"] = serialize.map(params["tag"], (e: string) => (e)); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<BindingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BindingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<BindingPage>) => any): Promise<ApiResponse<BindingPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<BindingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BindingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class BindingPage extends Page<V1, BindingPayload, BindingResource, BindingInstance> { +/** +* Initialize the BindingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: BindingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of BindingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BindingResource): BindingInstance { + + return new BindingInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/notify/v1/service/notification.ts b/rest/notify/v1/service/notification.ts new file mode 100644 index 000000000..a6ae8b1ab --- /dev/null +++ b/rest/notify/v1/service/notification.ts @@ -0,0 +1,451 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Notify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The priority of the notification. Can be: `low` or `high` and the default is `high`. A value of `low` optimizes the client app\'s battery consumption; however, notifications may be delivered with unspecified delay. For FCM and GCM, `low` priority is the same as `Normal` priority. For APNS `low` priority is the same as `5`. A value of `high` sends the notification immediately, and can wake up a sleeping device. For FCM and GCM, `high` is the same as `High` priority. For APNS, `high` is a priority `10`. SMS does not support this property. + */ +export type NotificationPriority = 'high'|'low'; + + +/** + * Options to pass to create a NotificationInstance + */ +export interface NotificationListInstanceCreateOptions { + /** The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. */ + "body"?: string; + /** */ + "priority"?: NotificationPriority; + /** How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. */ + "ttl"?: number; + /** The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. */ + "title"?: string; + /** The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. */ + "sound"?: string; + /** The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. */ + "action"?: string; + /** The custom key-value pairs of the notification\\\'s payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. */ + "data"?: any; + /** The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. */ + "apn"?: any; + /** The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). */ + "gcm"?: any; + /** The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. */ + "sms"?: any; + /** Deprecated. */ + "facebookMessenger"?: any; + /** The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. */ + "fcm"?: any; + /** The Segment resource is deprecated. Use the `tag` parameter, instead. */ + "segment"?: Array<string>; + /** Deprecated. */ + "alexa"?: any; + /** The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. */ + "toBinding"?: Array<string>; + /** URL to send webhooks. */ + "deliveryCallbackUrl"?: string; + /** The `identity` value that uniquely identifies the new resource\\\'s [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. */ + "identity"?: Array<string>; + /** A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. */ + "tag"?: Array<string>; +} + + +export interface NotificationSolution { + serviceSid: string; +} + +export interface NotificationListInstance { + _version: V1; + _solution: NotificationSolution; + _uri: string; + + + + /** + * Create a NotificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + create(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise<NotificationInstance>; + /** + * Create a NotificationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + create(params: NotificationListInstanceCreateOptions, callback?: (error: Error | null, item?: NotificationInstance) => any): Promise<NotificationInstance>; + + /** + * Create a NotificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NotificationInstance>) => any): Promise<ApiResponse<NotificationInstance>>; + /** + * Create a NotificationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + createWithHttpInfo(params: NotificationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<NotificationInstance>) => any): Promise<ApiResponse<NotificationInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NotificationListInstance(version: V1, serviceSid: string): NotificationListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = {} as NotificationListInstance; + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Notifications`; + + instance.create = function create(params?: NotificationListInstanceCreateOptions | ((error: Error | null, items: NotificationInstance) => any), callback?: (error: Error | null, items: NotificationInstance) => any): Promise<NotificationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["title"] !== undefined) + data["Title"] = params["title"]; + if (params["sound"] !== undefined) + data["Sound"] = params["sound"]; + if (params["action"] !== undefined) + data["Action"] = params["action"]; + if (params["data"] !== undefined) + data["Data"] = serialize.object(params["data"]); + if (params["apn"] !== undefined) + data["Apn"] = serialize.object(params["apn"]); + if (params["gcm"] !== undefined) + data["Gcm"] = serialize.object(params["gcm"]); + if (params["sms"] !== undefined) + data["Sms"] = serialize.object(params["sms"]); + if (params["facebookMessenger"] !== undefined) + data["FacebookMessenger"] = serialize.object(params["facebookMessenger"]); + if (params["fcm"] !== undefined) + data["Fcm"] = serialize.object(params["fcm"]); + if (params["segment"] !== undefined) + data["Segment"] = serialize.map(params["segment"], (e: string) => (e)); + if (params["alexa"] !== undefined) + data["Alexa"] = serialize.object(params["alexa"]); + if (params["toBinding"] !== undefined) + data["ToBinding"] = serialize.map(params["toBinding"], (e: string) => (e)); + if (params["deliveryCallbackUrl"] !== undefined) + data["DeliveryCallbackUrl"] = params["deliveryCallbackUrl"]; + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["tag"] !== undefined) + data["Tag"] = serialize.map(params["tag"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NotificationInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: NotificationListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<NotificationInstance>) => any), callback?: (error: Error | null, items: ApiResponse<NotificationInstance>) => any): Promise<ApiResponse<NotificationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["title"] !== undefined) + data["Title"] = params["title"]; + if (params["sound"] !== undefined) + data["Sound"] = params["sound"]; + if (params["action"] !== undefined) + data["Action"] = params["action"]; + if (params["data"] !== undefined) + data["Data"] = serialize.object(params["data"]); + if (params["apn"] !== undefined) + data["Apn"] = serialize.object(params["apn"]); + if (params["gcm"] !== undefined) + data["Gcm"] = serialize.object(params["gcm"]); + if (params["sms"] !== undefined) + data["Sms"] = serialize.object(params["sms"]); + if (params["facebookMessenger"] !== undefined) + data["FacebookMessenger"] = serialize.object(params["facebookMessenger"]); + if (params["fcm"] !== undefined) + data["Fcm"] = serialize.object(params["fcm"]); + if (params["segment"] !== undefined) + data["Segment"] = serialize.map(params["segment"], (e: string) => (e)); + if (params["alexa"] !== undefined) + data["Alexa"] = serialize.object(params["alexa"]); + if (params["toBinding"] !== undefined) + data["ToBinding"] = serialize.map(params["toBinding"], (e: string) => (e)); + if (params["deliveryCallbackUrl"] !== undefined) + data["DeliveryCallbackUrl"] = params["deliveryCallbackUrl"]; + if (params["identity"] !== undefined) + data["Identity"] = serialize.map(params["identity"], (e: string) => (e)); + if (params["tag"] !== undefined) + data["Tag"] = serialize.map(params["tag"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<NotificationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<NotificationInstance> => ({ + ...response, + body: new NotificationInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface NotificationPayload extends NotificationResource {} + +interface NotificationResource { + sid: string; + account_sid: string; + service_sid: string; + date_created: Date; + identities: Array<string>; + tags: Array<string>; + segments: Array<string>; + priority: NotificationPriority; + ttl: number; + title: string; + body: string; + sound: string; + action: string; + data: any; + apn: any; + gcm: any; + fcm: any; + sms: any; + facebook_messenger: any; + alexa: any; +} + +export class NotificationInstance { + + constructor(protected _version: V1, payload: NotificationResource, serviceSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.identities = (payload.identities); + this.tags = (payload.tags); + this.segments = (payload.segments); + this.priority = payload.priority; + this.ttl = deserialize.integer(payload.ttl); + this.title = (payload.title); + this.body = (payload.body); + this.sound = (payload.sound); + this.action = (payload.action); + this.data = (payload.data); + this.apn = (payload.apn); + this.gcm = (payload.gcm); + this.fcm = (payload.fcm); + this.sms = (payload.sms); + this.facebookMessenger = (payload.facebook_messenger); + this.alexa = (payload.alexa); + + } + + /** + * The unique string that we created to identify the Notification resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) the resource is associated with. + */ + serviceSid: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The list of `identity` values of the Users to notify. We will attempt to deliver notifications only to Bindings with an identity in this list. + */ + identities: Array<string>; + /** + * The tags that select the Bindings to notify. Notifications will be attempted only to Bindings that have all of the tags listed in this property. + */ + tags: Array<string>; + /** + * The list of Segments to notify. The [Segment](https://www.twilio.com/docs/notify/api/segment-resource) resource is deprecated. Use the `tags` property, instead. + */ + segments: Array<string>; + priority: NotificationPriority; + /** + * How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + */ + ttl: number; + /** + * The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + */ + title: string; + /** + * The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + */ + body: string; + /** + * The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + */ + sound: string; + /** + * The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + */ + action: string; + /** + * The custom key-value pairs of the notification\'s payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + */ + data: any; + /** + * The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + */ + apn: any; + /** + * The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + */ + gcm: any; + /** + * The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + */ + fcm: any; + /** + * The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/api/message-resource) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + */ + sms: any; + /** + * Deprecated. + */ + facebookMessenger: any; + /** + * Deprecated. + */ + alexa: any; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + identities: this.identities, + tags: this.tags, + segments: this.segments, + priority: this.priority, + ttl: this.ttl, + title: this.title, + body: this.body, + sound: this.sound, + action: this.action, + data: this.data, + apn: this.apn, + gcm: this.gcm, + fcm: this.fcm, + sms: this.sms, + facebookMessenger: this.facebookMessenger, + alexa: this.alexa, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/numbers/V1.ts b/rest/numbers/V1.ts new file mode 100644 index 000000000..7bf1ac371 --- /dev/null +++ b/rest/numbers/V1.ts @@ -0,0 +1,134 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import NumbersBase from "../NumbersBase"; +import Version from "../../base/Version"; +import { BulkEligibilityListInstance } from "./v1/bulkEligibility"; +import { EligibilityListInstance } from "./v1/eligibility"; +import { EmbeddedSessionListInstance } from "./v1/embeddedSession"; +import { PortingAllPortInListInstance } from "./v1/portingAllPortIn"; +import { PortingPortInListInstance } from "./v1/portingPortIn"; +import { PortingPortInPhoneNumberListInstance } from "./v1/portingPortInPhoneNumber"; +import { PortingPortabilityListInstance } from "./v1/portingPortability"; +import { PortingWebhookConfigurationListInstance } from "./v1/portingWebhookConfiguration"; +import { PortingWebhookConfigurationDeleteListInstance } from "./v1/portingWebhookConfigurationDelete"; +import { SenderIdRegistrationListInstance } from "./v1/senderIdRegistration"; +import { SigningRequestConfigurationListInstance } from "./v1/signingRequestConfiguration"; +import { WebhookListInstance } from "./v1/webhook"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Numbers + * + * @param domain - The Twilio (Twilio.Numbers) domain + */ + constructor(domain: NumbersBase) { + super(domain, "v1"); + } + + /** bulkEligibilities - { Twilio.Numbers.V1.BulkEligibilityListInstance } resource */ + protected _bulkEligibilities?: BulkEligibilityListInstance; + /** eligibilities - { Twilio.Numbers.V1.EligibilityListInstance } resource */ + protected _eligibilities?: EligibilityListInstance; + /** portingAllPortIns - { Twilio.Numbers.V1.PortingAllPortInListInstance } resource */ + protected _portingAllPortIns?: PortingAllPortInListInstance; + /** portingPortIns - { Twilio.Numbers.V1.PortingPortInListInstance } resource */ + protected _portingPortIns?: PortingPortInListInstance; + /** portingPortInPhoneNumber - { Twilio.Numbers.V1.PortingPortInPhoneNumberListInstance } resource */ + protected _portingPortInPhoneNumber?: PortingPortInPhoneNumberListInstance; + /** portingPortabilities - { Twilio.Numbers.V1.PortingPortabilityListInstance } resource */ + protected _portingPortabilities?: PortingPortabilityListInstance; + /** portingWebhookConfigurations - { Twilio.Numbers.V1.PortingWebhookConfigurationListInstance } resource */ + protected _portingWebhookConfigurations?: PortingWebhookConfigurationListInstance; + /** portingWebhookConfigurationsDelete - { Twilio.Numbers.V1.PortingWebhookConfigurationDeleteListInstance } resource */ + protected _portingWebhookConfigurationsDelete?: PortingWebhookConfigurationDeleteListInstance; + /** senderIdRegistrations - { Twilio.Numbers.V1.SenderIdRegistrationListInstance } resource */ + protected _senderIdRegistrations?: SenderIdRegistrationListInstance; + /** signingRequestConfigurations - { Twilio.Numbers.V1.SigningRequestConfigurationListInstance } resource */ + protected _signingRequestConfigurations?: SigningRequestConfigurationListInstance; + /** webhook - { Twilio.Numbers.V1.WebhookListInstance } resource */ + protected _webhook?: WebhookListInstance; + + /** Getter for bulkEligibilities resource */ + get bulkEligibilities(): BulkEligibilityListInstance { + this._bulkEligibilities = this._bulkEligibilities || BulkEligibilityListInstance(this); + return this._bulkEligibilities; + } + + /** Getter for eligibilities resource */ + get eligibilities(): EligibilityListInstance { + this._eligibilities = this._eligibilities || EligibilityListInstance(this); + return this._eligibilities; + } + + /** Accessor for embeddedSessions resource */ + embeddedSessions(BundleSid: string): EmbeddedSessionListInstance { + return EmbeddedSessionListInstance(this, BundleSid); + } + + /** Getter for portingAllPortIns resource */ + get portingAllPortIns(): PortingAllPortInListInstance { + this._portingAllPortIns = this._portingAllPortIns || PortingAllPortInListInstance(this); + return this._portingAllPortIns; + } + + /** Getter for portingPortIns resource */ + get portingPortIns(): PortingPortInListInstance { + this._portingPortIns = this._portingPortIns || PortingPortInListInstance(this); + return this._portingPortIns; + } + + /** Getter for portingPortInPhoneNumber resource */ + get portingPortInPhoneNumber(): PortingPortInPhoneNumberListInstance { + this._portingPortInPhoneNumber = this._portingPortInPhoneNumber || PortingPortInPhoneNumberListInstance(this); + return this._portingPortInPhoneNumber; + } + + /** Getter for portingPortabilities resource */ + get portingPortabilities(): PortingPortabilityListInstance { + this._portingPortabilities = this._portingPortabilities || PortingPortabilityListInstance(this); + return this._portingPortabilities; + } + + /** Getter for portingWebhookConfigurations resource */ + get portingWebhookConfigurations(): PortingWebhookConfigurationListInstance { + this._portingWebhookConfigurations = this._portingWebhookConfigurations || PortingWebhookConfigurationListInstance(this); + return this._portingWebhookConfigurations; + } + + /** Getter for portingWebhookConfigurationsDelete resource */ + get portingWebhookConfigurationsDelete(): PortingWebhookConfigurationDeleteListInstance { + this._portingWebhookConfigurationsDelete = this._portingWebhookConfigurationsDelete || PortingWebhookConfigurationDeleteListInstance(this); + return this._portingWebhookConfigurationsDelete; + } + + /** Getter for senderIdRegistrations resource */ + get senderIdRegistrations(): SenderIdRegistrationListInstance { + this._senderIdRegistrations = this._senderIdRegistrations || SenderIdRegistrationListInstance(this); + return this._senderIdRegistrations; + } + + /** Getter for signingRequestConfigurations resource */ + get signingRequestConfigurations(): SigningRequestConfigurationListInstance { + this._signingRequestConfigurations = this._signingRequestConfigurations || SigningRequestConfigurationListInstance(this); + return this._signingRequestConfigurations; + } + + /** Getter for webhook resource */ + get webhook(): WebhookListInstance { + this._webhook = this._webhook || WebhookListInstance(this); + return this._webhook; + } + +} diff --git a/rest/numbers/V2.ts b/rest/numbers/V2.ts new file mode 100644 index 000000000..0d07d9a27 --- /dev/null +++ b/rest/numbers/V2.ts @@ -0,0 +1,128 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import NumbersBase from "../NumbersBase"; +import Version from "../../base/Version"; +import { ApplicationListInstance } from "./v2/application"; +import { AuthorizationDocumentListInstance } from "./v2/authorizationDocument"; +import { BulkHostedNumberOrderListInstance } from "./v2/bulkHostedNumberOrder"; +import { BundleListInstance } from "./v2/bundle"; +import { BundleCloneListInstance } from "./v2/bundleClone"; +import { EndUserListInstance } from "./v2/endUser"; +import { EndUserTypeListInstance } from "./v2/endUserType"; +import { HostedNumberOrderListInstance } from "./v2/hostedNumberOrder"; +import { RegulationListInstance } from "./v2/regulation"; +import { SupportingDocumentListInstance } from "./v2/supportingDocument"; +import { SupportingDocumentTypeListInstance } from "./v2/supportingDocumentType"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Numbers + * + * @param domain - The Twilio (Twilio.Numbers) domain + */ + constructor(domain: NumbersBase) { + super(domain, "v2"); + } + + /** applications - { Twilio.Numbers.V2.ApplicationListInstance } resource */ + protected _applications?: ApplicationListInstance; + /** authorizationDocuments - { Twilio.Numbers.V2.AuthorizationDocumentListInstance } resource */ + protected _authorizationDocuments?: AuthorizationDocumentListInstance; + /** bulkHostedNumberOrders - { Twilio.Numbers.V2.BulkHostedNumberOrderListInstance } resource */ + protected _bulkHostedNumberOrders?: BulkHostedNumberOrderListInstance; + /** bundles - { Twilio.Numbers.V2.BundleListInstance } resource */ + protected _bundles?: BundleListInstance; + /** bundleClone - { Twilio.Numbers.V2.BundleCloneListInstance } resource */ + protected _bundleClone?: BundleCloneListInstance; + /** endUsers - { Twilio.Numbers.V2.EndUserListInstance } resource */ + protected _endUsers?: EndUserListInstance; + /** endUserTypes - { Twilio.Numbers.V2.EndUserTypeListInstance } resource */ + protected _endUserTypes?: EndUserTypeListInstance; + /** hostedNumberOrders - { Twilio.Numbers.V2.HostedNumberOrderListInstance } resource */ + protected _hostedNumberOrders?: HostedNumberOrderListInstance; + /** regulations - { Twilio.Numbers.V2.RegulationListInstance } resource */ + protected _regulations?: RegulationListInstance; + /** supportingDocuments - { Twilio.Numbers.V2.SupportingDocumentListInstance } resource */ + protected _supportingDocuments?: SupportingDocumentListInstance; + /** supportingDocumentTypes - { Twilio.Numbers.V2.SupportingDocumentTypeListInstance } resource */ + protected _supportingDocumentTypes?: SupportingDocumentTypeListInstance; + + /** Getter for applications resource */ + get applications(): ApplicationListInstance { + this._applications = this._applications || ApplicationListInstance(this); + return this._applications; + } + + /** Getter for authorizationDocuments resource */ + get authorizationDocuments(): AuthorizationDocumentListInstance { + this._authorizationDocuments = this._authorizationDocuments || AuthorizationDocumentListInstance(this); + return this._authorizationDocuments; + } + + /** Getter for bulkHostedNumberOrders resource */ + get bulkHostedNumberOrders(): BulkHostedNumberOrderListInstance { + this._bulkHostedNumberOrders = this._bulkHostedNumberOrders || BulkHostedNumberOrderListInstance(this); + return this._bulkHostedNumberOrders; + } + + /** Getter for bundles resource */ + get bundles(): BundleListInstance { + this._bundles = this._bundles || BundleListInstance(this); + return this._bundles; + } + + /** Getter for bundleClone resource */ + get bundleClone(): BundleCloneListInstance { + this._bundleClone = this._bundleClone || BundleCloneListInstance(this); + return this._bundleClone; + } + + /** Getter for endUsers resource */ + get endUsers(): EndUserListInstance { + this._endUsers = this._endUsers || EndUserListInstance(this); + return this._endUsers; + } + + /** Getter for endUserTypes resource */ + get endUserTypes(): EndUserTypeListInstance { + this._endUserTypes = this._endUserTypes || EndUserTypeListInstance(this); + return this._endUserTypes; + } + + /** Getter for hostedNumberOrders resource */ + get hostedNumberOrders(): HostedNumberOrderListInstance { + this._hostedNumberOrders = this._hostedNumberOrders || HostedNumberOrderListInstance(this); + return this._hostedNumberOrders; + } + + /** Getter for regulations resource */ + get regulations(): RegulationListInstance { + this._regulations = this._regulations || RegulationListInstance(this); + return this._regulations; + } + + /** Getter for supportingDocuments resource */ + get supportingDocuments(): SupportingDocumentListInstance { + this._supportingDocuments = this._supportingDocuments || SupportingDocumentListInstance(this); + return this._supportingDocuments; + } + + /** Getter for supportingDocumentTypes resource */ + get supportingDocumentTypes(): SupportingDocumentTypeListInstance { + this._supportingDocumentTypes = this._supportingDocumentTypes || SupportingDocumentTypeListInstance(this); + return this._supportingDocumentTypes; + } + +} diff --git a/rest/numbers/V3.ts b/rest/numbers/V3.ts new file mode 100644 index 000000000..003b21d5f --- /dev/null +++ b/rest/numbers/V3.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import NumbersBase from "../NumbersBase"; +import Version from "../../base/Version"; +import { HostedNumberOrderListInstance } from "./v3/hostedNumberOrder"; + +export default class V3 extends Version { + /** + * Initialize the V3 version of Numbers + * + * @param domain - The Twilio (Twilio.Numbers) domain + */ + constructor(domain: NumbersBase) { + super(domain, "v3"); + } + + /** hostedNumberOrders - { Twilio.Numbers.V3.HostedNumberOrderListInstance } resource */ + protected _hostedNumberOrders?: HostedNumberOrderListInstance; + + /** Getter for hostedNumberOrders resource */ + get hostedNumberOrders(): HostedNumberOrderListInstance { + this._hostedNumberOrders = this._hostedNumberOrders || HostedNumberOrderListInstance(this); + return this._hostedNumberOrders; + } + +} diff --git a/rest/numbers/v1/bulkEligibility.ts b/rest/numbers/v1/bulkEligibility.ts new file mode 100644 index 000000000..467d7da7b --- /dev/null +++ b/rest/numbers/v1/bulkEligibility.ts @@ -0,0 +1,385 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to create a BulkEligibilityInstance + */ +export interface BulkEligibilityListInstanceCreateOptions { + /** */ + "body"?: object; +} + +export interface BulkEligibilityContext { + + /** + * Fetch a BulkEligibilityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkEligibilityInstance + */ + fetch(callback?: (error: Error | null, item?: BulkEligibilityInstance) => any): Promise<BulkEligibilityInstance> + + /** + * Fetch a BulkEligibilityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkEligibilityInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BulkEligibilityInstance>) => any): Promise<ApiResponse<BulkEligibilityInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BulkEligibilityContextSolution { + "requestId": string; +} + +export class BulkEligibilityContextImpl implements BulkEligibilityContext { + protected _solution: BulkEligibilityContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, requestId: string) { + if (!isValidPathParam(requestId)) { + throw new Error('Parameter \'requestId\' is not valid.'); + } + + this._solution = { requestId, }; + this._uri = `/HostedNumber/Eligibility/Bulk/${requestId}`; + } + + fetch(callback?: (error: Error | null, item?: BulkEligibilityInstance) => any): Promise<BulkEligibilityInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BulkEligibilityInstance(operationVersion, payload, instance._solution.requestId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BulkEligibilityInstance>) => any): Promise<ApiResponse<BulkEligibilityInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<BulkEligibilityResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<BulkEligibilityInstance> => ({ + ...response, + body: new BulkEligibilityInstance(operationVersion, response.body, instance._solution.requestId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BulkEligibilityPayload extends BulkEligibilityResource {} + +interface BulkEligibilityResource { + request_id: string; + url: string; + results: Array<any>; + friendly_name: string; + status: string; + date_created: Date; + date_completed: Date; +} + +export class BulkEligibilityInstance { + protected _solution: BulkEligibilityContextSolution; + protected _context?: BulkEligibilityContext; + + constructor(protected _version: V1, payload: BulkEligibilityResource, requestId?: string) { + + this.requestId = (payload.request_id); + this.url = (payload.url); + this.results = (payload.results); + this.friendlyName = (payload.friendly_name); + this.status = (payload.status); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateCompleted = deserialize.iso8601DateTime(payload.date_completed); + + this._solution = { requestId: requestId, }; + } + + /** + * The SID of the bulk eligibility check that you want to know about. + */ + requestId: string; + /** + * This is the url of the request that you\'re trying to reach out to locate the resource. + */ + url: string; + /** + * The result set that contains the eligibility check response for each requested number, each result has at least the following attributes: phone_number: The requested phone number ,hosting_account_sid: The account sid where the phone number will be hosted, country: Phone number’s country, eligibility_status: Indicates the eligibility status of the PN (Eligible/Ineligible), eligibility_sub_status: Indicates the sub status of the eligibility , ineligibility_reason: Reason for number\'s ineligibility (if applicable), next_step: Suggested next step in the hosting process based on the eligibility status. + */ + results: Array<any>; + /** + * This is the string that you assigned as a friendly name for describing the eligibility check request. + */ + friendlyName: string; + /** + * This is the status of the bulk eligibility check request. (Example: COMPLETE, IN_PROGRESS) + */ + status: string; + dateCreated: Date; + dateCompleted: Date; + + private get _proxy(): BulkEligibilityContext { + this._context = this._context || new BulkEligibilityContextImpl(this._version, this._solution.requestId); + return this._context; + } + + /** + * Fetch a BulkEligibilityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkEligibilityInstance + */ + fetch(callback?: (error: Error | null, item?: BulkEligibilityInstance) => any): Promise<BulkEligibilityInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BulkEligibilityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkEligibilityInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BulkEligibilityInstance>) => any): Promise<ApiResponse<BulkEligibilityInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + requestId: this.requestId, + url: this.url, + results: this.results, + friendlyName: this.friendlyName, + status: this.status, + dateCreated: this.dateCreated, + dateCompleted: this.dateCompleted, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BulkEligibilitySolution { +} + +export interface BulkEligibilityListInstance { + _version: V1; + _solution: BulkEligibilitySolution; + _uri: string; + + (requestId: string, ): BulkEligibilityContext; + get(requestId: string, ): BulkEligibilityContext; + + + + + /** + * Create a BulkEligibilityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkEligibilityInstance + */ + create(callback?: (error: Error | null, item?: BulkEligibilityInstance) => any): Promise<BulkEligibilityInstance>; + /** + * Create a BulkEligibilityInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkEligibilityInstance + */ + create(params: object, headers?: any, callback?: (error: Error | null, item?: BulkEligibilityInstance) => any): Promise<BulkEligibilityInstance>; + + /** + * Create a BulkEligibilityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkEligibilityInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BulkEligibilityInstance>) => any): Promise<ApiResponse<BulkEligibilityInstance>>; + /** + * Create a BulkEligibilityInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkEligibilityInstance with HTTP metadata + */ + createWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse<BulkEligibilityInstance>) => any): Promise<ApiResponse<BulkEligibilityInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BulkEligibilityListInstance(version: V1): BulkEligibilityListInstance { + const instance = ((requestId, ) => instance.get(requestId, )) as BulkEligibilityListInstance; + + instance.get = function get(requestId, ): BulkEligibilityContext { + return new BulkEligibilityContextImpl(version, requestId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/HostedNumber/Eligibility/Bulk`; + + instance.create = function create(params?: object | ((error: Error | null, items: BulkEligibilityInstance) => any), headers?: any, callback?: (error: Error | null, items: BulkEligibilityInstance) => any): Promise<BulkEligibilityInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BulkEligibilityInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: object | ((error: Error | null, items: ApiResponse<BulkEligibilityInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<BulkEligibilityInstance>) => any): Promise<ApiResponse<BulkEligibilityInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BulkEligibilityResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BulkEligibilityInstance> => ({ + ...response, + body: new BulkEligibilityInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/numbers/v1/eligibility.ts b/rest/numbers/v1/eligibility.ts new file mode 100644 index 000000000..c41b92367 --- /dev/null +++ b/rest/numbers/v1/eligibility.ts @@ -0,0 +1,211 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a EligibilityInstance + */ +export interface EligibilityListInstanceCreateOptions { + /** */ + "body"?: object; +} + + +export interface EligibilitySolution { +} + +export interface EligibilityListInstance { + _version: V1; + _solution: EligibilitySolution; + _uri: string; + + + + /** + * Create a EligibilityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EligibilityInstance + */ + create(callback?: (error: Error | null, item?: EligibilityInstance) => any): Promise<EligibilityInstance>; + /** + * Create a EligibilityInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EligibilityInstance + */ + create(params: object, headers?: any, callback?: (error: Error | null, item?: EligibilityInstance) => any): Promise<EligibilityInstance>; + + /** + * Create a EligibilityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EligibilityInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EligibilityInstance>) => any): Promise<ApiResponse<EligibilityInstance>>; + /** + * Create a EligibilityInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EligibilityInstance with HTTP metadata + */ + createWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse<EligibilityInstance>) => any): Promise<ApiResponse<EligibilityInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EligibilityListInstance(version: V1): EligibilityListInstance { + const instance = {} as EligibilityListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/HostedNumber/Eligibility`; + + instance.create = function create(params?: object | ((error: Error | null, items: EligibilityInstance) => any), headers?: any, callback?: (error: Error | null, items: EligibilityInstance) => any): Promise<EligibilityInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new EligibilityInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: object | ((error: Error | null, items: ApiResponse<EligibilityInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<EligibilityInstance>) => any): Promise<ApiResponse<EligibilityInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<EligibilityResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<EligibilityInstance> => ({ + ...response, + body: new EligibilityInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface EligibilityPayload extends EligibilityResource {} + +interface EligibilityResource { + results: Array<any>; +} + +export class EligibilityInstance { + + constructor(protected _version: V1, payload: EligibilityResource) { + + this.results = (payload.results); + + } + + /** + * The result set that contains the eligibility check response for the requested number, each result has at least the following attributes: phone_number: The requested phone number ,hosting_account_sid: The account sid where the phone number will be hosted, date_last_checked: Datetime (ISO 8601) when the PN was last checked for eligibility, country: Phone number’s country, eligibility_status: Indicates the eligibility status of the PN (Eligible/Ineligible), eligibility_sub_status: Indicates the sub status of the eligibility , ineligibility_reason: Reason for number\'s ineligibility (if applicable), next_step: Suggested next step in the hosting process based on the eligibility status. + */ + results: Array<any>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + results: this.results, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/numbers/v1/embeddedSession.ts b/rest/numbers/v1/embeddedSession.ts new file mode 100644 index 000000000..99cb0ae45 --- /dev/null +++ b/rest/numbers/v1/embeddedSession.ts @@ -0,0 +1,220 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class NumbersV1CreateEmbeddedSessionRequest { + /** + * Theme ID for the Compliance Embeddable UI. Overrides the theme set during registration creation. + */ + "themeSetId"?: string; + + constructor(payload) { + this.themeSetId = payload["themeSetId"]; + } +} + + + +/** + * Options to pass to create a EmbeddedSessionInstance + */ +export interface EmbeddedSessionListInstanceCreateOptions { + /** */ + "numbersV1CreateEmbeddedSessionRequest": NumbersV1CreateEmbeddedSessionRequest; +} + + +export interface EmbeddedSessionSolution { + bundleSid: string; +} + +export interface EmbeddedSessionListInstance { + _version: V1; + _solution: EmbeddedSessionSolution; + _uri: string; + + + + /** + * Create a EmbeddedSessionInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EmbeddedSessionInstance + */ + create(params: NumbersV1CreateEmbeddedSessionRequest, headers?: any, callback?: (error: Error | null, item?: EmbeddedSessionInstance) => any): Promise<EmbeddedSessionInstance>; + + /** + * Create a EmbeddedSessionInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EmbeddedSessionInstance with HTTP metadata + */ + createWithHttpInfo(params: NumbersV1CreateEmbeddedSessionRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<EmbeddedSessionInstance>) => any): Promise<ApiResponse<EmbeddedSessionInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EmbeddedSessionListInstance(version: V1, bundleSid: string): EmbeddedSessionListInstance { + if (!isValidPathParam(bundleSid)) { + throw new Error('Parameter \'bundleSid\' is not valid.'); + } + + const instance = {} as EmbeddedSessionListInstance; + + instance._version = version; + instance._solution = { bundleSid, }; + instance._uri = `/SenderIdRegistrations/${bundleSid}/EmbeddedSessions`; + + instance.create = function create(params: NumbersV1CreateEmbeddedSessionRequest, headers?: any, callback?: (error: Error | null, items: EmbeddedSessionInstance) => any): Promise<EmbeddedSessionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new EmbeddedSessionInstance(operationVersion, payload, instance._solution.bundleSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: NumbersV1CreateEmbeddedSessionRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<EmbeddedSessionInstance>) => any): Promise<ApiResponse<EmbeddedSessionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<EmbeddedSessionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<EmbeddedSessionInstance> => ({ + ...response, + body: new EmbeddedSessionInstance(operationVersion, response.body, instance._solution.bundleSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface EmbeddedSessionPayload extends EmbeddedSessionResource {} + +interface EmbeddedSessionResource { + id: string; + sessionId: string; + sessionToken: string; +} + +export class EmbeddedSessionInstance { + + constructor(protected _version: V1, payload: EmbeddedSessionResource, bundleSid?: string) { + + this.id = (payload.id); + this.sessionId = (payload.sessionId); + this.sessionToken = (payload.sessionToken); + + } + + /** + * Registration identifier (BU-prefixed). + */ + id: string; + /** + * Session ID for the compliance embeddable. + */ + sessionId: string; + /** + * Ephemeral session token for the compliance embeddable. + */ + sessionToken: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + sessionId: this.sessionId, + sessionToken: this.sessionToken, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/numbers/v1/portingAllPortIn.ts b/rest/numbers/v1/portingAllPortIn.ts new file mode 100644 index 000000000..ac50998a3 --- /dev/null +++ b/rest/numbers/v1/portingAllPortIn.ts @@ -0,0 +1,463 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface PortingAllPortInListInstanceEachOptions { + /** Page start token, if null then it will start from the beginning */ + "token"?: string; + /** Number of items per page */ + "size"?: number; + /** Filter by Port in request SID, supports multiple values separated by comma */ + "portInRequestSid"?: string; + /** Filter by Port In request status */ + "portInRequestStatus"?: string; + /** Find all created before a certain date */ + "createdBefore"?: string; + /** Find all created after a certain date */ + "createdAfter"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PortingAllPortInInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PortingAllPortInListInstanceOptions { + /** Page start token, if null then it will start from the beginning */ + "token"?: string; + /** Number of items per page */ + "size"?: number; + /** Filter by Port in request SID, supports multiple values separated by comma */ + "portInRequestSid"?: string; + /** Filter by Port In request status */ + "portInRequestStatus"?: string; + /** Find all created before a certain date */ + "createdBefore"?: string; + /** Find all created after a certain date */ + "createdAfter"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PortingAllPortInListInstancePageOptions { + /** Page start token, if null then it will start from the beginning */ + "token"?: string; + /** Number of items per page */ + "size"?: number; + /** Filter by Port in request SID, supports multiple values separated by comma */ + "portInRequestSid"?: string; + /** Filter by Port In request status */ + "portInRequestStatus"?: string; + /** Find all created before a certain date */ + "createdBefore"?: string; + /** Find all created after a certain date */ + "createdAfter"?: string; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface PortingAllPortInSolution { +} + +export interface PortingAllPortInListInstance { + _version: V1; + _solution: PortingAllPortInSolution; + _uri: string; + + + + + /** + * Streams PortingAllPortInInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PortingAllPortInListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PortingAllPortInInstance, done: (err?: Error) => void) => void): void; + each(params: PortingAllPortInListInstanceEachOptions, callback?: (item: PortingAllPortInInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PortingAllPortInInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PortingAllPortInListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PortingAllPortInInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PortingAllPortInListInstanceEachOptions, callback?: (item: PortingAllPortInInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PortingAllPortInInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PortingAllPortInPage) => any): Promise<PortingAllPortInPage>; + /** + * Retrieve a single target page of PortingAllPortInInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<PortingAllPortInPage>) => any): Promise<ApiResponse<PortingAllPortInPage>>; + /** + * Lists PortingAllPortInInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PortingAllPortInListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PortingAllPortInInstance[]) => any): Promise<PortingAllPortInInstance[]>; + list(params: PortingAllPortInListInstanceOptions, callback?: (error: Error | null, items: PortingAllPortInInstance[]) => any): Promise<PortingAllPortInInstance[]>; + /** + * Lists PortingAllPortInInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PortingAllPortInListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PortingAllPortInInstance[]>) => any): Promise<ApiResponse<PortingAllPortInInstance[]>>; + listWithHttpInfo(params: PortingAllPortInListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<PortingAllPortInInstance[]>) => any): Promise<ApiResponse<PortingAllPortInInstance[]>>; + /** + * Retrieve a single page of PortingAllPortInInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PortingAllPortInListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PortingAllPortInPage) => any): Promise<PortingAllPortInPage>; + page(params: PortingAllPortInListInstancePageOptions, callback?: (error: Error | null, items: PortingAllPortInPage) => any): Promise<PortingAllPortInPage>; + /** + * Retrieve a single page of PortingAllPortInInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PortingAllPortInListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PortingAllPortInPage>) => any): Promise<ApiResponse<PortingAllPortInPage>>; + pageWithHttpInfo(params: PortingAllPortInListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<PortingAllPortInPage>) => any): Promise<ApiResponse<PortingAllPortInPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PortingAllPortInListInstance(version: V1): PortingAllPortInListInstance { + const instance = {} as PortingAllPortInListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Porting/PortIn/PortInRequests`; + + instance.page = function page(params?: PortingAllPortInListInstancePageOptions | ((error: Error | null, items: PortingAllPortInPage) => any), callback?: (error: Error | null, items: PortingAllPortInPage) => any): Promise<PortingAllPortInPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["token"] !== undefined) + data["Token"] = params["token"]; + if (params["size"] !== undefined) + data["Size"] = params["size"]; + if (params["portInRequestSid"] !== undefined) + data["PortInRequestSid"] = params["portInRequestSid"]; + if (params["portInRequestStatus"] !== undefined) + data["PortInRequestStatus"] = params["portInRequestStatus"]; + if (params["createdBefore"] !== undefined) + data["CreatedBefore"] = params["createdBefore"]; + if (params["createdAfter"] !== undefined) + data["CreatedAfter"] = params["createdAfter"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PortingAllPortInPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PortingAllPortInPage) => any): Promise<PortingAllPortInPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PortingAllPortInPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PortingAllPortInListInstancePageOptions | ((error: Error | null, items: ApiResponse<PortingAllPortInPage>) => any), callback?: (error: Error | null, items: ApiResponse<PortingAllPortInPage>) => any): Promise<ApiResponse<PortingAllPortInPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["token"] !== undefined) + data["Token"] = params["token"]; + if (params["size"] !== undefined) + data["Size"] = params["size"]; + if (params["portInRequestSid"] !== undefined) + data["PortInRequestSid"] = params["portInRequestSid"]; + if (params["portInRequestStatus"] !== undefined) + data["PortInRequestStatus"] = params["portInRequestStatus"]; + if (params["createdBefore"] !== undefined) + data["CreatedBefore"] = params["createdBefore"]; + if (params["createdAfter"] !== undefined) + data["CreatedAfter"] = params["createdAfter"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<PortingAllPortInPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PortingAllPortInPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<PortingAllPortInPage>) => any): Promise<ApiResponse<PortingAllPortInPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<PortingAllPortInPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PortingAllPortInPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface PortingAllPortInPayload extends TwilioResponsePayload { + port_in_requests: PortingAllPortInResource[]; +} + +interface PortingAllPortInResource { + port_in_request_sid: string; + port_in_request_status: string; + status_last_updated_timestamp: string; + phone_numbers_requested: number; + phone_numbers_ported: number; + suggested_action: string; +} + +export class PortingAllPortInInstance { + + constructor(protected _version: V1, payload: PortingAllPortInResource) { + + this.portInRequestSid = (payload.port_in_request_sid); + this.portInRequestStatus = (payload.port_in_request_status); + this.statusLastUpdatedTimestamp = (payload.status_last_updated_timestamp); + this.phoneNumbersRequested = deserialize.integer(payload.phone_numbers_requested); + this.phoneNumbersPorted = deserialize.integer(payload.phone_numbers_ported); + this.suggestedAction = (payload.suggested_action); + + } + + /** + * The SID of the Port-in request + */ + portInRequestSid: string; + /** + * Status of the Port In Request + */ + portInRequestStatus: string; + /** + * The last updated timestamp of the request + */ + statusLastUpdatedTimestamp: string; + /** + * Amount of phone numbers requested + */ + phoneNumbersRequested: number; + /** + * Amount of phone numbers ported + */ + phoneNumbersPorted: number; + /** + * Suggested action on this ticket + */ + suggestedAction: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + portInRequestSid: this.portInRequestSid, + portInRequestStatus: this.portInRequestStatus, + statusLastUpdatedTimestamp: this.statusLastUpdatedTimestamp, + phoneNumbersRequested: this.phoneNumbersRequested, + phoneNumbersPorted: this.phoneNumbersPorted, + suggestedAction: this.suggestedAction, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class PortingAllPortInPage extends Page<V1, PortingAllPortInPayload, PortingAllPortInResource, PortingAllPortInInstance> { +/** +* Initialize the PortingAllPortInPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: PortingAllPortInSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PortingAllPortInInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PortingAllPortInResource): PortingAllPortInInstance { + + return new PortingAllPortInInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v1/portingPortIn.ts b/rest/numbers/v1/portingPortIn.ts new file mode 100644 index 000000000..79840c984 --- /dev/null +++ b/rest/numbers/v1/portingPortIn.ts @@ -0,0 +1,743 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class NumbersV1PortingAddress { + /** + * The street address, ex: 101 Spear St + */ + "street": string; + /** + * The building information, ex : 5th floor. + */ + "street2"?: string; + /** + * The city name, ex: San Francisco. + */ + "city": string; + /** + * The state name, ex: CA or California. Note this should match the losing carrier’s information exactly. So if they spell out the entire state’s name instead of abbreviating it, please do so. + */ + "state": string; + /** + * The zip code, ex: 94105. + */ + "zip": string; + /** + * The country, ex: USA. + */ + "country": string; + + constructor(payload) { + this.street = payload["street"]; + this.street2 = payload["street_2"]; + this.city = payload["city"]; + this.state = payload["state"]; + this.zip = payload["zip"]; + this.country = payload["country"]; + } +} + + +export class NumbersV1PortingLosingCarrierInformation { + /** + * Customer name as it is registered with the losing carrier. This can be an individual or a business name depending on the customer type selected. + */ + "customerName": string; + /** + * The account number of the customer for the losing carrier. Only require for mobile phone numbers. + */ + "accountNumber"?: string; + /** + * The account phone number of the customer for the losing carrier. + */ + "accountTelephoneNumber"?: string; + /** + * If you already have an Address SID that represents the address needed for the LOA, you can provide an Address SID instead of providing the address object in the request body. This will copy the address into the port in request. If changes are made to the Address SID after port in request creation, those changes will not be reflected in the port in request. + */ + "addressSid"?: string; + "address"?: NumbersV1PortingAddress; + /** + * The first and last name of the person listed with the losing carrier who is authorized to make changes on the account. + */ + "authorizedRepresentative": string; + /** + * Email address of the person (owner of the number) who will sign the letter of authorization for the port in request. This email address should belong to the person named in as the authorized representative. + */ + "authorizedRepresentativeEmail": string; + /** + * The type of customer account in the losing carrier. This should either be: \'Individual\' or \'Business\'. + */ + "customerType"?: string; + "authorizedRepresentativeKatakana"?: string; + "subMunicipality"?: string; + "building"?: string; + "katakanaName"?: string; + + constructor(payload) { + this.customerName = payload["customer_name"]; + this.accountNumber = payload["account_number"]; + this.accountTelephoneNumber = payload["account_telephone_number"]; + this.addressSid = payload["address_sid"]; + this.address = payload["address"]; + this.authorizedRepresentative = payload["authorized_representative"]; + this.authorizedRepresentativeEmail = payload["authorized_representative_email"]; + this.customerType = payload["customer_type"]; + this.authorizedRepresentativeKatakana = payload["authorized_representative_katakana"]; + this.subMunicipality = payload["sub_municipality"]; + this.building = payload["building"]; + this.katakanaName = payload["katakana_name"]; + } +} + + +export class NumbersV1PortingPortInCreate { + /** + * Account Sid or subaccount where the phone number(s) will be Ported + */ + "accountSid": string; + /** + * List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. + */ + "documents": Array<string>; + /** + * List of phone numbers to be ported. Maximum of 1,000 phone numbers per request. + */ + "phoneNumbers"?: Array<NumbersV1PortingPortInCreatePhoneNumbers>; + "losingCarrierInformation": NumbersV1PortingLosingCarrierInformation; + /** + * Additional emails to send a copy of the signed LOA to. + */ + "notificationEmails"?: Array<string> | null; + /** + * Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. We can\'t guarantee the exact date and time, as this depends on the losing carrier + */ + "targetPortInDate"?: string | null; + /** + * The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00\'. We can\'t guarantee the exact date and time, as this depends on the losing carrier + */ + "targetPortInTimeRangeStart"?: string | null; + /** + * The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00\'. We can\'t guarantee the exact date and time, as this depends on the losing carrier + */ + "targetPortInTimeRangeEnd"?: string | null; + /** + * The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + */ + "bundleSid"?: string | null; + /** + * A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + */ + "portabilityAdvanceCarrier"?: string | null; + /** + * Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + */ + "autoCancelApprovalNumbers"?: string | null; + + constructor(payload) { + this.accountSid = payload["account_sid"]; + this.documents = payload["documents"]; + this.phoneNumbers = payload["phone_numbers"]; + this.losingCarrierInformation = payload["losing_carrier_information"]; + this.notificationEmails = payload["notification_emails"]; + this.targetPortInDate = payload["target_port_in_date"]; + this.targetPortInTimeRangeStart = payload["target_port_in_time_range_start"]; + this.targetPortInTimeRangeEnd = payload["target_port_in_time_range_end"]; + this.bundleSid = payload["bundle_sid"]; + this.portabilityAdvanceCarrier = payload["portability_advance_carrier"]; + this.autoCancelApprovalNumbers = payload["auto_cancel_approval_numbers"]; + } +} + + +export class NumbersV1PortingPortInCreatePhoneNumbers { + /** + * Phone number to be ported. This must be in the E164 Format. + */ + "phoneNumber": string; + /** + * Some losing carriers require a PIN to authorize the port of a phone number. If the phone number is a US mobile phone number, the PIN is mandatory to process a porting request. Other carriers and number types may also require a PIN, you\'ll need to contact the losing carrier to determine what your phone number\'s PIN is. + */ + "pin"?: string; + + constructor(payload) { + this.phoneNumber = payload["phone_number"]; + this.pin = payload["pin"]; + } +} + + +export class NumbersV1PortingPortInPhoneNumberResult { + /** + * The not portability reason code description. This field may be null if the number is portable or if the portability for a number has not yet been evaluated. + */ + "notPortabilityReason"?: string | null; + /** + * The not portability reason code. This field may be null if the number is portable or if the portability for a number has not yet been evaluated. + */ + "notPortabilityReasonCode"?: number | null; + /** + * The number type of the phone number. This can be: toll-free, local, mobile or unknown. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + */ + "numberType"?: string | null; + /** + * Phone number to be ported. This will be in the E164 Format. + */ + "phoneNumber"?: string; + /** + * The timestamp the phone number will be ported. This will only be set once a port date has been confirmed. Not all carriers can guarantee a specific time on the port date. Twilio will try its best to get the port completed by this time on the port date. Please subscribe to webhooks for confirmation on when a port has actually been completed. + */ + "portDate"?: Date | null; + /** + * The SID of the Phone number. This is a unique identifier of the phone number. + */ + "portInPhoneNumberSid"?: string; + /** + * The status of the port in phone number. + */ + "portInPhoneNumberStatus"?: string; + /** + * Whether the number is portable by Twilio or not. This field may be null if the number portability has not yet been evaluated. If a number is not portable reference the `not_portability_reason_code` and `not_portability_reason` fields for more details + */ + "portable"?: boolean | null; + /** + * The description of the rejection reason provided by the losing carrier. This field may be null if the number has not been rejected by the losing carrier. + */ + "rejectionReason"?: string | null; + /** + * The code for the rejection reason provided by the losing carrier. This field may be null if the number has not been rejected by the losing carrier. + */ + "rejectionReasonCode"?: string | null; + /** + * Timestamp indicating when the Port In Phone Number resource was last modified. + */ + "statusLastTimeUpdatedTimestamp"?: string | null; + "externalPortingVendorPhoneNumberId"?: string | null; + + constructor(payload) { + this.notPortabilityReason = payload["not_portability_reason"]; + this.notPortabilityReasonCode = payload["not_portability_reason_code"]; + this.numberType = payload["number_type"]; + this.phoneNumber = payload["phone_number"]; + this.portDate = payload["port_date"]; + this.portInPhoneNumberSid = payload["port_in_phone_number_sid"]; + this.portInPhoneNumberStatus = payload["port_in_phone_number_status"]; + this.portable = payload["portable"]; + this.rejectionReason = payload["rejection_reason"]; + this.rejectionReasonCode = payload["rejection_reason_code"]; + this.statusLastTimeUpdatedTimestamp = payload["status_last_time_updated_timestamp"]; + this.externalPortingVendorPhoneNumberId = payload["external_porting_vendor_phone_number_id"]; + } +} + + + + + +/** + * Options to pass to create a PortingPortInInstance + */ +export interface PortingPortInListInstanceCreateOptions { + /** */ + "numbersV1PortingPortInCreate": NumbersV1PortingPortInCreate; +} + +export interface PortingPortInContext { + + /** + * Remove a PortingPortInInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a PortingPortInInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a PortingPortInInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortInInstance + */ + fetch(callback?: (error: Error | null, item?: PortingPortInInstance) => any): Promise<PortingPortInInstance> + + /** + * Fetch a PortingPortInInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortInInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PortingPortInInstance>) => any): Promise<ApiResponse<PortingPortInInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PortingPortInContextSolution { + "portInRequestSid": string; +} + +export class PortingPortInContextImpl implements PortingPortInContext { + protected _solution: PortingPortInContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, portInRequestSid: string) { + if (!isValidPathParam(portInRequestSid)) { + throw new Error('Parameter \'portInRequestSid\' is not valid.'); + } + + this._solution = { portInRequestSid, }; + this._uri = `/Porting/PortIn/${portInRequestSid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: PortingPortInInstance) => any): Promise<PortingPortInInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PortingPortInInstance(operationVersion, payload, instance._solution.portInRequestSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PortingPortInInstance>) => any): Promise<ApiResponse<PortingPortInInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PortingPortInResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<PortingPortInInstance> => ({ + ...response, + body: new PortingPortInInstance(operationVersion, response.body, instance._solution.portInRequestSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PortingPortInPayload extends PortingPortInResource {} + +interface PortingPortInResource { + port_in_request_sid: string; + url: string; + account_sid: string; + notification_emails: Array<string>; + target_port_in_date: Date; + target_port_in_time_range_start: string; + target_port_in_time_range_end: string; + port_in_request_status: string; + order_cancellation_reason: string; + losing_carrier_information: NumbersV1PortingLosingCarrierInformation; + phone_numbers: Array<NumbersV1PortingPortInPhoneNumberResult>; + bundle_sid: string; + portability_advance_carrier: string; + auto_cancel_approval_numbers: string; + documents: Array<string>; + date_created: Date; + support_ticket_id: number; + signature_request_url: string; +} + +export class PortingPortInInstance { + protected _solution: PortingPortInContextSolution; + protected _context?: PortingPortInContext; + + constructor(protected _version: V1, payload: PortingPortInResource, portInRequestSid?: string) { + + this.portInRequestSid = (payload.port_in_request_sid); + this.url = (payload.url); + this.accountSid = (payload.account_sid); + this.notificationEmails = (payload.notification_emails); + this.targetPortInDate = deserialize.iso8601Date(payload.target_port_in_date); + this.targetPortInTimeRangeStart = (payload.target_port_in_time_range_start); + this.targetPortInTimeRangeEnd = (payload.target_port_in_time_range_end); + this.portInRequestStatus = (payload.port_in_request_status); + this.orderCancellationReason = (payload.order_cancellation_reason); + this.losingCarrierInformation = payload.losing_carrier_information !== null && payload.losing_carrier_information !== undefined ? new NumbersV1PortingLosingCarrierInformation(payload.losing_carrier_information) : null; + this.phoneNumbers = payload.phone_numbers !== null && payload.phone_numbers !== undefined ? payload.phone_numbers.map( + (payload: any) => new NumbersV1PortingPortInPhoneNumberResult(payload) + ) : null; + this.bundleSid = (payload.bundle_sid); + this.portabilityAdvanceCarrier = (payload.portability_advance_carrier); + this.autoCancelApprovalNumbers = (payload.auto_cancel_approval_numbers); + this.documents = (payload.documents); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.supportTicketId = deserialize.integer(payload.support_ticket_id); + this.signatureRequestUrl = (payload.signature_request_url); + + this._solution = { portInRequestSid: portInRequestSid, }; + } + + /** + * The SID of the Port In request. This is a unique identifier of the port in request. + */ + portInRequestSid: string; + /** + * The URL of this Port In request + */ + url: string; + /** + * Account Sid or subaccount where the phone number(s) will be Ported + */ + accountSid: string; + /** + * Additional emails to send a copy of the signed LOA to. + */ + notificationEmails: Array<string>; + /** + * Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. If a start and end range is provided, the date will be converted to its UTC equivalent with the ranges as reference and stored in UTC. We can\'t guarantee the exact date and time, as this depends on the losing carrier. + */ + targetPortInDate: Date; + /** + * The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00\'. We can\'t guarantee the exact date and time, as this depends on the losing carrier. The time will be stored and returned as UTC standard timezone. + */ + targetPortInTimeRangeStart: string; + /** + * The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00\'. We can\'t guarantee the exact date and time, as this depends on the losing carrier. The time will be stored and returned as UTC standard timezone. + */ + targetPortInTimeRangeEnd: string; + /** + * The status of the port in request. The possible values are: In progress, Completed, Expired, In review, Waiting for Signature, Action Required, and Canceled. + */ + portInRequestStatus: string; + /** + * If the order is cancelled this field will provide further context on the cause of the cancellation. + */ + orderCancellationReason: string; + losingCarrierInformation: NumbersV1PortingLosingCarrierInformation; + phoneNumbers: Array<NumbersV1PortingPortInPhoneNumberResult>; + /** + * The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + */ + bundleSid: string; + /** + * A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + */ + portabilityAdvanceCarrier: string; + /** + * Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + */ + autoCancelApprovalNumbers: string; + /** + * List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. + */ + documents: Array<string>; + dateCreated: Date; + /** + * Unique ID of the request\'s support ticket + */ + supportTicketId: number; + signatureRequestUrl: string; + + private get _proxy(): PortingPortInContext { + this._context = this._context || new PortingPortInContextImpl(this._version, this._solution.portInRequestSid); + return this._context; + } + + /** + * Remove a PortingPortInInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a PortingPortInInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a PortingPortInInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortInInstance + */ + fetch(callback?: (error: Error | null, item?: PortingPortInInstance) => any): Promise<PortingPortInInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PortingPortInInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortInInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PortingPortInInstance>) => any): Promise<ApiResponse<PortingPortInInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + portInRequestSid: this.portInRequestSid, + url: this.url, + accountSid: this.accountSid, + notificationEmails: this.notificationEmails, + targetPortInDate: this.targetPortInDate, + targetPortInTimeRangeStart: this.targetPortInTimeRangeStart, + targetPortInTimeRangeEnd: this.targetPortInTimeRangeEnd, + portInRequestStatus: this.portInRequestStatus, + orderCancellationReason: this.orderCancellationReason, + losingCarrierInformation: this.losingCarrierInformation, + phoneNumbers: this.phoneNumbers, + bundleSid: this.bundleSid, + portabilityAdvanceCarrier: this.portabilityAdvanceCarrier, + autoCancelApprovalNumbers: this.autoCancelApprovalNumbers, + documents: this.documents, + dateCreated: this.dateCreated, + supportTicketId: this.supportTicketId, + signatureRequestUrl: this.signatureRequestUrl, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PortingPortInSolution { +} + +export interface PortingPortInListInstance { + _version: V1; + _solution: PortingPortInSolution; + _uri: string; + + (portInRequestSid: string, ): PortingPortInContext; + get(portInRequestSid: string, ): PortingPortInContext; + + + + + + + /** + * Create a PortingPortInInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortInInstance + */ + create(params: NumbersV1PortingPortInCreate, headers?: any, callback?: (error: Error | null, item?: PortingPortInInstance) => any): Promise<PortingPortInInstance>; + + /** + * Create a PortingPortInInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortInInstance with HTTP metadata + */ + createWithHttpInfo(params: NumbersV1PortingPortInCreate, headers?: any, callback?: (error: Error | null, item?: ApiResponse<PortingPortInInstance>) => any): Promise<ApiResponse<PortingPortInInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PortingPortInListInstance(version: V1): PortingPortInListInstance { + const instance = ((portInRequestSid, ) => instance.get(portInRequestSid, )) as PortingPortInListInstance; + + instance.get = function get(portInRequestSid, ): PortingPortInContext { + return new PortingPortInContextImpl(version, portInRequestSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Porting/PortIn`; + + instance.create = function create(params: NumbersV1PortingPortInCreate, headers?: any, callback?: (error: Error | null, items: PortingPortInInstance) => any): Promise<PortingPortInInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PortingPortInInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: NumbersV1PortingPortInCreate, headers?: any, callback?: (error: Error | null, items: ApiResponse<PortingPortInInstance>) => any): Promise<ApiResponse<PortingPortInInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<PortingPortInResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<PortingPortInInstance> => ({ + ...response, + body: new PortingPortInInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/numbers/v1/portingPortInPhoneNumber.ts b/rest/numbers/v1/portingPortInPhoneNumber.ts new file mode 100644 index 000000000..e4d8dab4d --- /dev/null +++ b/rest/numbers/v1/portingPortInPhoneNumber.ts @@ -0,0 +1,436 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface PortingPortInPhoneNumberContext { + + /** + * Remove a PortingPortInPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a PortingPortInPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a PortingPortInPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortInPhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PortingPortInPhoneNumberInstance) => any): Promise<PortingPortInPhoneNumberInstance> + + /** + * Fetch a PortingPortInPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortInPhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PortingPortInPhoneNumberInstance>) => any): Promise<ApiResponse<PortingPortInPhoneNumberInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PortingPortInPhoneNumberContextSolution { + "portInRequestSid": string; + "phoneNumberSid": string; +} + +export class PortingPortInPhoneNumberContextImpl implements PortingPortInPhoneNumberContext { + protected _solution: PortingPortInPhoneNumberContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, portInRequestSid: string, phoneNumberSid: string) { + if (!isValidPathParam(portInRequestSid)) { + throw new Error('Parameter \'portInRequestSid\' is not valid.'); + } + + if (!isValidPathParam(phoneNumberSid)) { + throw new Error('Parameter \'phoneNumberSid\' is not valid.'); + } + + this._solution = { portInRequestSid, phoneNumberSid, }; + this._uri = `/Porting/PortIn/${portInRequestSid}/PhoneNumber/${phoneNumberSid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: PortingPortInPhoneNumberInstance) => any): Promise<PortingPortInPhoneNumberInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PortingPortInPhoneNumberInstance(operationVersion, payload, instance._solution.portInRequestSid, instance._solution.phoneNumberSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PortingPortInPhoneNumberInstance>) => any): Promise<ApiResponse<PortingPortInPhoneNumberInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PortingPortInPhoneNumberResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<PortingPortInPhoneNumberInstance> => ({ + ...response, + body: new PortingPortInPhoneNumberInstance(operationVersion, response.body, instance._solution.portInRequestSid, instance._solution.phoneNumberSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PortingPortInPhoneNumberPayload extends PortingPortInPhoneNumberResource {} + +interface PortingPortInPhoneNumberResource { + port_in_request_sid: string; + phone_number_sid: string; + url: string; + account_sid: string; + phone_number_type: string; + date_created: Date; + country: string; + missing_required_fields: boolean; + last_updated: Date; + phone_number: string; + portable: boolean; + not_portability_reason: string; + not_portability_reason_code: number; + port_in_phone_number_status: string; + port_out_pin: number; + rejection_reason: string; + rejection_reason_code: number; + port_date: Date; +} + +export class PortingPortInPhoneNumberInstance { + protected _solution: PortingPortInPhoneNumberContextSolution; + protected _context?: PortingPortInPhoneNumberContext; + + constructor(protected _version: V1, payload: PortingPortInPhoneNumberResource, portInRequestSid?: string, phoneNumberSid?: string) { + + this.portInRequestSid = (payload.port_in_request_sid); + this.phoneNumberSid = (payload.phone_number_sid); + this.url = (payload.url); + this.accountSid = (payload.account_sid); + this.phoneNumberType = (payload.phone_number_type); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.country = (payload.country); + this.missingRequiredFields = (payload.missing_required_fields); + this.lastUpdated = deserialize.iso8601DateTime(payload.last_updated); + this.phoneNumber = (payload.phone_number); + this.portable = (payload.portable); + this.notPortabilityReason = (payload.not_portability_reason); + this.notPortabilityReasonCode = deserialize.integer(payload.not_portability_reason_code); + this.portInPhoneNumberStatus = (payload.port_in_phone_number_status); + this.portOutPin = deserialize.integer(payload.port_out_pin); + this.rejectionReason = (payload.rejection_reason); + this.rejectionReasonCode = deserialize.integer(payload.rejection_reason_code); + this.portDate = deserialize.iso8601DateTime(payload.port_date); + + this._solution = { portInRequestSid: portInRequestSid, phoneNumberSid: phoneNumberSid, }; + } + + /** + * The unique identifier for the port in request that this phone number is associated with. + */ + portInRequestSid: string; + /** + * The unique identifier for this phone number associated with this port in request. + */ + phoneNumberSid: string; + /** + * URL reference for this resource. + */ + url: string; + /** + * Account Sid or subaccount where the phone number(s) will be Ported. + */ + accountSid: string; + /** + * The number type of the phone number. This can be: toll-free, local, mobile or unknown. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + */ + phoneNumberType: string; + /** + * The timestamp for when this port in phone number was created. + */ + dateCreated: Date; + /** + * The ISO country code that this number is associated with. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + */ + country: string; + /** + * Indicates if the phone number is missing required fields such as a PIN or account number. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + */ + missingRequiredFields: boolean; + /** + * Timestamp indicating when the Port In Phone Number resource was last modified. + */ + lastUpdated: Date; + /** + * Phone number to be ported. This will be in the E164 Format. + */ + phoneNumber: string; + /** + * If the number is portable by Twilio or not. This field may be null if the number portability has not yet been evaluated. If a number is not portable reference the `not_portability_reason_code` and `not_portability_reason` fields for more details + */ + portable: boolean; + /** + * The not portability reason code description. This field may be null if the number is portable or if the portability for a number has not yet been evaluated. + */ + notPortabilityReason: string; + /** + * The not portability reason code. This field may be null if the number is portable or if the portability for a number has not yet been evaluated. + */ + notPortabilityReasonCode: number; + /** + * The status of the port in phone number. + */ + portInPhoneNumberStatus: string; + /** + * The pin required by the losing carrier to do the port out. + */ + portOutPin: number; + /** + * The description of the rejection reason provided by the losing carrier. This field may be null if the number has not been rejected by the losing carrier. + */ + rejectionReason: string; + /** + * The code for the rejection reason provided by the losing carrier. This field may be null if the number has not been rejected by the losing carrier. + */ + rejectionReasonCode: number; + /** + * The timestamp the phone number will be ported. This will only be set once a port date has been confirmed. Not all carriers can guarantee a specific time on the port date. Twilio will try its best to get the port completed by this time on the port date. Please subscribe to webhooks for confirmation on when a port has actually been completed. + */ + portDate: Date; + + private get _proxy(): PortingPortInPhoneNumberContext { + this._context = this._context || new PortingPortInPhoneNumberContextImpl(this._version, this._solution.portInRequestSid, this._solution.phoneNumberSid); + return this._context; + } + + /** + * Remove a PortingPortInPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a PortingPortInPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a PortingPortInPhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortInPhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PortingPortInPhoneNumberInstance) => any): Promise<PortingPortInPhoneNumberInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PortingPortInPhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortInPhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PortingPortInPhoneNumberInstance>) => any): Promise<ApiResponse<PortingPortInPhoneNumberInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + portInRequestSid: this.portInRequestSid, + phoneNumberSid: this.phoneNumberSid, + url: this.url, + accountSid: this.accountSid, + phoneNumberType: this.phoneNumberType, + dateCreated: this.dateCreated, + country: this.country, + missingRequiredFields: this.missingRequiredFields, + lastUpdated: this.lastUpdated, + phoneNumber: this.phoneNumber, + portable: this.portable, + notPortabilityReason: this.notPortabilityReason, + notPortabilityReasonCode: this.notPortabilityReasonCode, + portInPhoneNumberStatus: this.portInPhoneNumberStatus, + portOutPin: this.portOutPin, + rejectionReason: this.rejectionReason, + rejectionReasonCode: this.rejectionReasonCode, + portDate: this.portDate, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PortingPortInPhoneNumberSolution { +} + +export interface PortingPortInPhoneNumberListInstance { + _version: V1; + _solution: PortingPortInPhoneNumberSolution; + _uri: string; + + (portInRequestSid: string, phoneNumberSid: string, ): PortingPortInPhoneNumberContext; + get(portInRequestSid: string, phoneNumberSid: string, ): PortingPortInPhoneNumberContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PortingPortInPhoneNumberListInstance(version: V1): PortingPortInPhoneNumberListInstance { + const instance = ((portInRequestSid, phoneNumberSid, ) => instance.get(portInRequestSid, phoneNumberSid, )) as PortingPortInPhoneNumberListInstance; + + instance.get = function get(portInRequestSid, phoneNumberSid, ): PortingPortInPhoneNumberContext { + return new PortingPortInPhoneNumberContextImpl(version, portInRequestSid, phoneNumberSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/numbers/v1/portingPortability.ts b/rest/numbers/v1/portingPortability.ts new file mode 100644 index 000000000..c94d9b0b8 --- /dev/null +++ b/rest/numbers/v1/portingPortability.ts @@ -0,0 +1,375 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The type of the requested phone number. One of `LOCAL`, `UNKNOWN`, `MOBILE`, `TOLL-FREE`. + */ +export type PortingPortabilityNumberType = 'LOCAL'|'UNKNOWN'|'MOBILE'|'TOLL-FREE'; + + +/** + * Options to pass to fetch a PortingPortabilityInstance + */ +export interface PortingPortabilityContextFetchOptions { + /** Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. */ + "targetAccountSid"?: string; + /** Address Sid of customer to which the number will be ported. */ + "addressSid"?: string; +} + +export interface PortingPortabilityContext { + + /** + * Fetch a PortingPortabilityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortabilityInstance + */ + fetch(callback?: (error: Error | null, item?: PortingPortabilityInstance) => any): Promise<PortingPortabilityInstance>; + /** + * Fetch a PortingPortabilityInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortabilityInstance + */ + fetch(params: PortingPortabilityContextFetchOptions, callback?: (error: Error | null, item?: PortingPortabilityInstance) => any): Promise<PortingPortabilityInstance>; + + /** + * Fetch a PortingPortabilityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortabilityInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PortingPortabilityInstance>) => any): Promise<ApiResponse<PortingPortabilityInstance>>; + /** + * Fetch a PortingPortabilityInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortabilityInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PortingPortabilityContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<PortingPortabilityInstance>) => any): Promise<ApiResponse<PortingPortabilityInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PortingPortabilityContextSolution { + "phoneNumber": string; +} + +export class PortingPortabilityContextImpl implements PortingPortabilityContext { + protected _solution: PortingPortabilityContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, phoneNumber: string) { + if (!isValidPathParam(phoneNumber)) { + throw new Error('Parameter \'phoneNumber\' is not valid.'); + } + + this._solution = { phoneNumber, }; + this._uri = `/Porting/Portability/PhoneNumber/${phoneNumber}`; + } + + fetch(params?: PortingPortabilityContextFetchOptions | ((error: Error | null, item?: PortingPortabilityInstance) => any),callback?: (error: Error | null, item?: PortingPortabilityInstance) => any): Promise<PortingPortabilityInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["targetAccountSid"] !== undefined) + data["TargetAccountSid"] = params["targetAccountSid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new PortingPortabilityInstance(operationVersion, payload, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: PortingPortabilityContextFetchOptions | ((error: Error | null, item?: ApiResponse<PortingPortabilityInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<PortingPortabilityInstance>) => any): Promise<ApiResponse<PortingPortabilityInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["targetAccountSid"] !== undefined) + data["TargetAccountSid"] = params["targetAccountSid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PortingPortabilityResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<PortingPortabilityInstance> => ({ + ...response, + body: new PortingPortabilityInstance(operationVersion, response.body, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PortingPortabilityPayload extends PortingPortabilityResource {} + +interface PortingPortabilityResource { + phone_number: string; + account_sid: string; + portable: boolean; + pin_and_account_number_required: boolean; + not_portable_reason: string; + not_portable_reason_code: number; + number_type: PortingPortabilityNumberType; + country: string; + url: string; +} + +export class PortingPortabilityInstance { + protected _solution: PortingPortabilityContextSolution; + protected _context?: PortingPortabilityContext; + + constructor(protected _version: V1, payload: PortingPortabilityResource, phoneNumber?: string) { + + this.phoneNumber = (payload.phone_number); + this.accountSid = (payload.account_sid); + this.portable = (payload.portable); + this.pinAndAccountNumberRequired = (payload.pin_and_account_number_required); + this.notPortableReason = (payload.not_portable_reason); + this.notPortableReasonCode = deserialize.integer(payload.not_portable_reason_code); + this.numberType = payload.number_type; + this.country = (payload.country); + this.url = (payload.url); + + this._solution = { phoneNumber: phoneNumber, }; + } + + /** + * The phone number which portability is to be checked. Phone numbers are in E.164 format (e.g. +16175551212). + */ + phoneNumber: string; + /** + * Account Sid that the phone number belongs to in Twilio. This is only returned for phone numbers that already exist in Twilio’s inventory and belong to your account or sub account. + */ + accountSid: string; + /** + * Boolean flag indicates if the phone number can be ported into Twilio through the Porting API or not. + */ + portable: boolean; + /** + * Indicates if the port in process will require a personal identification number (PIN) and an account number for this phone number. If this is true you will be required to submit both a PIN and account number from the losing carrier for this number when opening a port in request. These fields will be required in order to complete the port in process to Twilio. + */ + pinAndAccountNumberRequired: boolean; + /** + * Reason why the phone number cannot be ported into Twilio, `null` otherwise. + */ + notPortableReason: string; + /** + * The Portability Reason Code for the phone number if it cannot be ported into Twilio, `null` otherwise. + */ + notPortableReasonCode: number; + numberType: PortingPortabilityNumberType; + /** + * Country the phone number belongs to. + */ + country: string; + /** + * This is the url of the request that you\'re trying to reach out to locate the resource. + */ + url: string; + + private get _proxy(): PortingPortabilityContext { + this._context = this._context || new PortingPortabilityContextImpl(this._version, this._solution.phoneNumber); + return this._context; + } + + /** + * Fetch a PortingPortabilityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortabilityInstance + */ + fetch(callback?: (error: Error | null, item?: PortingPortabilityInstance) => any): Promise<PortingPortabilityInstance>; + /** + * Fetch a PortingPortabilityInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortabilityInstance + */ + fetch(params: PortingPortabilityContextFetchOptions, callback?: (error: Error | null, item?: PortingPortabilityInstance) => any): Promise<PortingPortabilityInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: PortingPortabilityInstance) => any): Promise<PortingPortabilityInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a PortingPortabilityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortabilityInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PortingPortabilityInstance>) => any): Promise<ApiResponse<PortingPortabilityInstance>>; + /** + * Fetch a PortingPortabilityInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingPortabilityInstance with HTTP metadata + */ + fetchWithHttpInfo(params: PortingPortabilityContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<PortingPortabilityInstance>) => any): Promise<ApiResponse<PortingPortabilityInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<PortingPortabilityInstance>) => any): Promise<ApiResponse<PortingPortabilityInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + phoneNumber: this.phoneNumber, + accountSid: this.accountSid, + portable: this.portable, + pinAndAccountNumberRequired: this.pinAndAccountNumberRequired, + notPortableReason: this.notPortableReason, + notPortableReasonCode: this.notPortableReasonCode, + numberType: this.numberType, + country: this.country, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PortingPortabilitySolution { +} + +export interface PortingPortabilityListInstance { + _version: V1; + _solution: PortingPortabilitySolution; + _uri: string; + + (phoneNumber: string, ): PortingPortabilityContext; + get(phoneNumber: string, ): PortingPortabilityContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PortingPortabilityListInstance(version: V1): PortingPortabilityListInstance { + const instance = ((phoneNumber, ) => instance.get(phoneNumber, )) as PortingPortabilityListInstance; + + instance.get = function get(phoneNumber, ): PortingPortabilityContext { + return new PortingPortabilityContextImpl(version, phoneNumber); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/numbers/v1/portingWebhookConfiguration.ts b/rest/numbers/v1/portingWebhookConfiguration.ts new file mode 100644 index 000000000..571d02dc7 --- /dev/null +++ b/rest/numbers/v1/portingWebhookConfiguration.ts @@ -0,0 +1,232 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a PortingWebhookConfigurationInstance + */ +export interface PortingWebhookConfigurationListInstanceCreateOptions { + /** */ + "body"?: object; +} + + +export interface PortingWebhookConfigurationSolution { +} + +export interface PortingWebhookConfigurationListInstance { + _version: V1; + _solution: PortingWebhookConfigurationSolution; + _uri: string; + + + + /** + * Create a PortingWebhookConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingWebhookConfigurationInstance + */ + create(callback?: (error: Error | null, item?: PortingWebhookConfigurationInstance) => any): Promise<PortingWebhookConfigurationInstance>; + /** + * Create a PortingWebhookConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingWebhookConfigurationInstance + */ + create(params: object, headers?: any, callback?: (error: Error | null, item?: PortingWebhookConfigurationInstance) => any): Promise<PortingWebhookConfigurationInstance>; + + /** + * Create a PortingWebhookConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingWebhookConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PortingWebhookConfigurationInstance>) => any): Promise<ApiResponse<PortingWebhookConfigurationInstance>>; + /** + * Create a PortingWebhookConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PortingWebhookConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse<PortingWebhookConfigurationInstance>) => any): Promise<ApiResponse<PortingWebhookConfigurationInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PortingWebhookConfigurationListInstance(version: V1): PortingWebhookConfigurationListInstance { + const instance = {} as PortingWebhookConfigurationListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Porting/Configuration/Webhook`; + + instance.create = function create(params?: object | ((error: Error | null, items: PortingWebhookConfigurationInstance) => any), headers?: any, callback?: (error: Error | null, items: PortingWebhookConfigurationInstance) => any): Promise<PortingWebhookConfigurationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PortingWebhookConfigurationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: object | ((error: Error | null, items: ApiResponse<PortingWebhookConfigurationInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<PortingWebhookConfigurationInstance>) => any): Promise<ApiResponse<PortingWebhookConfigurationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<PortingWebhookConfigurationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<PortingWebhookConfigurationInstance> => ({ + ...response, + body: new PortingWebhookConfigurationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface PortingWebhookConfigurationPayload extends PortingWebhookConfigurationResource {} + +interface PortingWebhookConfigurationResource { + url: string; + port_in_target_url: string; + port_out_target_url: string; + notifications_of: Array<string>; +} + +export class PortingWebhookConfigurationInstance { + + constructor(protected _version: V1, payload: PortingWebhookConfigurationResource) { + + this.url = (payload.url); + this.portInTargetUrl = (payload.port_in_target_url); + this.portOutTargetUrl = (payload.port_out_target_url); + this.notificationsOf = (payload.notifications_of); + + } + + /** + * The URL of the webhook configuration request + */ + url: string; + /** + * The complete webhook url that will be called when a notification event for port in request or port in phone number happens + */ + portInTargetUrl: string; + /** + * The complete webhook url that will be called when a notification event for a port out phone number happens. + */ + portOutTargetUrl: string; + /** + * A list to filter what notification events to receive for this account and its sub accounts. If it is an empty list, then it means that there are no filters for the notifications events to send in each webhook and all events will get sent. + */ + notificationsOf: Array<string>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + url: this.url, + portInTargetUrl: this.portInTargetUrl, + portOutTargetUrl: this.portOutTargetUrl, + notificationsOf: this.notificationsOf, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/numbers/v1/portingWebhookConfigurationDelete.ts b/rest/numbers/v1/portingWebhookConfigurationDelete.ts new file mode 100644 index 000000000..50c29d917 --- /dev/null +++ b/rest/numbers/v1/portingWebhookConfigurationDelete.ts @@ -0,0 +1,166 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The of the webhook type of the configuration to be deleted + */ +export type PortingWebhookConfigurationDeleteWebhookType = 'PORT_IN'|'PORT_OUT'; + + + +export interface PortingWebhookConfigurationDeleteContext { + + /** + * Remove a PortingWebhookConfigurationDeleteInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a PortingWebhookConfigurationDeleteInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PortingWebhookConfigurationDeleteContextSolution { + "webhookType": PortingWebhookConfigurationDeleteWebhookType; +} + +export class PortingWebhookConfigurationDeleteContextImpl implements PortingWebhookConfigurationDeleteContext { + protected _solution: PortingWebhookConfigurationDeleteContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, webhookType: PortingWebhookConfigurationDeleteWebhookType) { + if (!isValidPathParam(webhookType)) { + throw new Error('Parameter \'webhookType\' is not valid.'); + } + + this._solution = { webhookType, }; + this._uri = `/Porting/Configuration/Webhook/${webhookType}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + +export interface PortingWebhookConfigurationDeleteSolution { +} + +export interface PortingWebhookConfigurationDeleteListInstance { + _version: V1; + _solution: PortingWebhookConfigurationDeleteSolution; + _uri: string; + + (webhookType: PortingWebhookConfigurationDeleteWebhookType, ): PortingWebhookConfigurationDeleteContext; + get(webhookType: PortingWebhookConfigurationDeleteWebhookType, ): PortingWebhookConfigurationDeleteContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PortingWebhookConfigurationDeleteListInstance(version: V1): PortingWebhookConfigurationDeleteListInstance { + const instance = ((webhookType, ) => instance.get(webhookType, )) as PortingWebhookConfigurationDeleteListInstance; + + instance.get = function get(webhookType, ): PortingWebhookConfigurationDeleteContext { + return new PortingWebhookConfigurationDeleteContextImpl(version, webhookType); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/numbers/v1/senderIdRegistration.ts b/rest/numbers/v1/senderIdRegistration.ts new file mode 100644 index 000000000..a8499fdf6 --- /dev/null +++ b/rest/numbers/v1/senderIdRegistration.ts @@ -0,0 +1,327 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class NumbersV1CreateEmbeddedRegistrationRequest { + /** + * The regulation for this registration. + */ + "regulationId": string; + /** + * The regulation version. + */ + "regulationVersion": number; + /** + * Human-readable name for the registration. + */ + "friendlyName": string; + /** + * Email address for registration status notifications. + */ + "statusNotificationEmail"?: string; + /** + * The URL of this resource. + */ + "statusCallbackUrl"?: string | null; + /** + * Additional comments about the registration. + */ + "comments"?: string; + /** + * Theme ID for the Compliance Embeddable UI. + */ + "themeSetId"?: string; + /** + * Registration data organized by section (alphanumericSender, business, useCase, authorizedRepresentative, officer, businessAddress). + */ + "data": { [key: string]: any; }; + + constructor(payload) { + this.regulationId = payload["regulationId"]; + this.regulationVersion = payload["regulationVersion"]; + this.friendlyName = payload["friendlyName"]; + this.statusNotificationEmail = payload["statusNotificationEmail"]; + this.statusCallbackUrl = payload["statusCallbackUrl"]; + this.comments = payload["comments"]; + this.themeSetId = payload["themeSetId"]; + this.data = payload["data"]; + } +} + + +export class NumbersV1EmbeddedSession { + /** + * Session ID for the compliance embeddable. + */ + "sessionId": string; + /** + * Ephemeral session token for the compliance embeddable. + */ + "sessionToken": string; + + constructor(payload) { + this.sessionId = payload["sessionId"]; + this.sessionToken = payload["sessionToken"]; + } +} + + + +/** + * Options to pass to create a SenderIdRegistrationInstance + */ +export interface SenderIdRegistrationListInstanceCreateOptions { + /** */ + "numbersV1CreateEmbeddedRegistrationRequest": NumbersV1CreateEmbeddedRegistrationRequest; +} + + +export interface SenderIdRegistrationSolution { +} + +export interface SenderIdRegistrationListInstance { + _version: V1; + _solution: SenderIdRegistrationSolution; + _uri: string; + + + + /** + * Create a SenderIdRegistrationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SenderIdRegistrationInstance + */ + create(params: NumbersV1CreateEmbeddedRegistrationRequest, headers?: any, callback?: (error: Error | null, item?: SenderIdRegistrationInstance) => any): Promise<SenderIdRegistrationInstance>; + + /** + * Create a SenderIdRegistrationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SenderIdRegistrationInstance with HTTP metadata + */ + createWithHttpInfo(params: NumbersV1CreateEmbeddedRegistrationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<SenderIdRegistrationInstance>) => any): Promise<ApiResponse<SenderIdRegistrationInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SenderIdRegistrationListInstance(version: V1): SenderIdRegistrationListInstance { + const instance = {} as SenderIdRegistrationListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/SenderIdRegistrations`; + + instance.create = function create(params: NumbersV1CreateEmbeddedRegistrationRequest, headers?: any, callback?: (error: Error | null, items: SenderIdRegistrationInstance) => any): Promise<SenderIdRegistrationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SenderIdRegistrationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: NumbersV1CreateEmbeddedRegistrationRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<SenderIdRegistrationInstance>) => any): Promise<ApiResponse<SenderIdRegistrationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SenderIdRegistrationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SenderIdRegistrationInstance> => ({ + ...response, + body: new SenderIdRegistrationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface SenderIdRegistrationPayload extends SenderIdRegistrationResource {} + +interface SenderIdRegistrationResource { + id: string; + regulationId: string; + regulationVersion: number; + friendlyName: string; + status: string; + statusNotificationEmail: string; + statusCallbackUrl: string; + comments: string; + embeddedSession: NumbersV1EmbeddedSession; + data: { [key: string]: any; }; + dateCreated: Date; + dateUpdated: Date; +} + +export class SenderIdRegistrationInstance { + + constructor(protected _version: V1, payload: SenderIdRegistrationResource) { + + this.id = (payload.id); + this.regulationId = (payload.regulationId); + this.regulationVersion = deserialize.integer(payload.regulationVersion); + this.friendlyName = (payload.friendlyName); + this.status = (payload.status); + this.statusNotificationEmail = (payload.statusNotificationEmail); + this.statusCallbackUrl = (payload.statusCallbackUrl); + this.comments = (payload.comments); + this.embeddedSession = payload.embeddedSession !== null && payload.embeddedSession !== undefined ? new NumbersV1EmbeddedSession(payload.embeddedSession) : null; + this.data = (payload.data); + this.dateCreated = deserialize.iso8601DateTime(payload.dateCreated); + this.dateUpdated = deserialize.iso8601DateTime(payload.dateUpdated); + + } + + /** + * Registration identifier (BU-prefixed). + */ + id: string; + /** + * The regulation ID for this registration. + */ + regulationId: string; + /** + * The regulation version. + */ + regulationVersion: number; + /** + * The friendly name provided in the request. + */ + friendlyName: string; + /** + * Registration status. Always DRAFT on creation. + */ + status: string; + /** + * Email address for status notifications. + */ + statusNotificationEmail: string; + /** + * Callback URL for status webhooks. + */ + statusCallbackUrl: string; + /** + * Additional comments. + */ + comments: string; + embeddedSession: NumbersV1EmbeddedSession; + /** + * Registration data echoed from the request. + */ + data: { [key: string]: any; }; + /** + * Timestamp of creation. + */ + dateCreated: Date; + /** + * Timestamp of last update. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + regulationId: this.regulationId, + regulationVersion: this.regulationVersion, + friendlyName: this.friendlyName, + status: this.status, + statusNotificationEmail: this.statusNotificationEmail, + statusCallbackUrl: this.statusCallbackUrl, + comments: this.comments, + embeddedSession: this.embeddedSession, + data: this.data, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/numbers/v1/signingRequestConfiguration.ts b/rest/numbers/v1/signingRequestConfiguration.ts new file mode 100644 index 000000000..d7faf80ce --- /dev/null +++ b/rest/numbers/v1/signingRequestConfiguration.ts @@ -0,0 +1,559 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a SigningRequestConfigurationInstance + */ +export interface SigningRequestConfigurationListInstanceCreateOptions { + /** */ + "body"?: object; +} + +/** + * Options to pass to each + */ +export interface SigningRequestConfigurationListInstanceEachOptions { + /** The country ISO code to apply this configuration, this is an optional field, Example: US, MX */ + "country"?: string; + /** The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting */ + "product"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SigningRequestConfigurationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SigningRequestConfigurationListInstanceOptions { + /** The country ISO code to apply this configuration, this is an optional field, Example: US, MX */ + "country"?: string; + /** The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting */ + "product"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SigningRequestConfigurationListInstancePageOptions { + /** The country ISO code to apply this configuration, this is an optional field, Example: US, MX */ + "country"?: string; + /** The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting */ + "product"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface SigningRequestConfigurationSolution { +} + +export interface SigningRequestConfigurationListInstance { + _version: V1; + _solution: SigningRequestConfigurationSolution; + _uri: string; + + + + /** + * Create a SigningRequestConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningRequestConfigurationInstance + */ + create(callback?: (error: Error | null, item?: SigningRequestConfigurationInstance) => any): Promise<SigningRequestConfigurationInstance>; + /** + * Create a SigningRequestConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningRequestConfigurationInstance + */ + create(params: object, headers?: any, callback?: (error: Error | null, item?: SigningRequestConfigurationInstance) => any): Promise<SigningRequestConfigurationInstance>; + + /** + * Create a SigningRequestConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningRequestConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SigningRequestConfigurationInstance>) => any): Promise<ApiResponse<SigningRequestConfigurationInstance>>; + /** + * Create a SigningRequestConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SigningRequestConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse<SigningRequestConfigurationInstance>) => any): Promise<ApiResponse<SigningRequestConfigurationInstance>>; + + + + + /** + * Streams SigningRequestConfigurationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningRequestConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SigningRequestConfigurationInstance, done: (err?: Error) => void) => void): void; + each(params: SigningRequestConfigurationListInstanceEachOptions, callback?: (item: SigningRequestConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SigningRequestConfigurationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningRequestConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SigningRequestConfigurationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SigningRequestConfigurationListInstanceEachOptions, callback?: (item: SigningRequestConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SigningRequestConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SigningRequestConfigurationPage) => any): Promise<SigningRequestConfigurationPage>; + /** + * Retrieve a single target page of SigningRequestConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SigningRequestConfigurationPage>) => any): Promise<ApiResponse<SigningRequestConfigurationPage>>; + /** + * Lists SigningRequestConfigurationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningRequestConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SigningRequestConfigurationInstance[]) => any): Promise<SigningRequestConfigurationInstance[]>; + list(params: SigningRequestConfigurationListInstanceOptions, callback?: (error: Error | null, items: SigningRequestConfigurationInstance[]) => any): Promise<SigningRequestConfigurationInstance[]>; + /** + * Lists SigningRequestConfigurationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningRequestConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SigningRequestConfigurationInstance[]>) => any): Promise<ApiResponse<SigningRequestConfigurationInstance[]>>; + listWithHttpInfo(params: SigningRequestConfigurationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SigningRequestConfigurationInstance[]>) => any): Promise<ApiResponse<SigningRequestConfigurationInstance[]>>; + /** + * Retrieve a single page of SigningRequestConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningRequestConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SigningRequestConfigurationPage) => any): Promise<SigningRequestConfigurationPage>; + page(params: SigningRequestConfigurationListInstancePageOptions, callback?: (error: Error | null, items: SigningRequestConfigurationPage) => any): Promise<SigningRequestConfigurationPage>; + /** + * Retrieve a single page of SigningRequestConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SigningRequestConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SigningRequestConfigurationPage>) => any): Promise<ApiResponse<SigningRequestConfigurationPage>>; + pageWithHttpInfo(params: SigningRequestConfigurationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SigningRequestConfigurationPage>) => any): Promise<ApiResponse<SigningRequestConfigurationPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SigningRequestConfigurationListInstance(version: V1): SigningRequestConfigurationListInstance { + const instance = {} as SigningRequestConfigurationListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/SigningRequest/Configuration`; + + instance.create = function create(params?: object | ((error: Error | null, items: SigningRequestConfigurationInstance) => any), headers?: any, callback?: (error: Error | null, items: SigningRequestConfigurationInstance) => any): Promise<SigningRequestConfigurationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SigningRequestConfigurationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: object | ((error: Error | null, items: ApiResponse<SigningRequestConfigurationInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<SigningRequestConfigurationInstance>) => any): Promise<ApiResponse<SigningRequestConfigurationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SigningRequestConfigurationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SigningRequestConfigurationInstance> => ({ + ...response, + body: new SigningRequestConfigurationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SigningRequestConfigurationListInstancePageOptions | ((error: Error | null, items: SigningRequestConfigurationPage) => any), callback?: (error: Error | null, items: SigningRequestConfigurationPage) => any): Promise<SigningRequestConfigurationPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["country"] !== undefined) + data["Country"] = params["country"]; + if (params["product"] !== undefined) + data["Product"] = params["product"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SigningRequestConfigurationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SigningRequestConfigurationPage) => any): Promise<SigningRequestConfigurationPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SigningRequestConfigurationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SigningRequestConfigurationListInstancePageOptions | ((error: Error | null, items: ApiResponse<SigningRequestConfigurationPage>) => any), callback?: (error: Error | null, items: ApiResponse<SigningRequestConfigurationPage>) => any): Promise<ApiResponse<SigningRequestConfigurationPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["country"] !== undefined) + data["Country"] = params["country"]; + if (params["product"] !== undefined) + data["Product"] = params["product"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SigningRequestConfigurationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SigningRequestConfigurationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SigningRequestConfigurationPage>) => any): Promise<ApiResponse<SigningRequestConfigurationPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SigningRequestConfigurationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SigningRequestConfigurationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface SigningRequestConfigurationPayload extends TwilioResponsePayload { + configurations: SigningRequestConfigurationResource[]; +} + +interface SigningRequestConfigurationResource { + logo_sid: string; + friendly_name: string; + product: string; + country: string; + email_subject: string; + email_message: string; + url_redirection: string; + url: string; +} + +export class SigningRequestConfigurationInstance { + + constructor(protected _version: V1, payload: SigningRequestConfigurationResource) { + + this.logoSid = (payload.logo_sid); + this.friendlyName = (payload.friendly_name); + this.product = (payload.product); + this.country = (payload.country); + this.emailSubject = (payload.email_subject); + this.emailMessage = (payload.email_message); + this.urlRedirection = (payload.url_redirection); + this.url = (payload.url); + + } + + /** + * The SID of the document that includes the logo that will appear in the LOA. To upload documents follow the following guide: https://www.twilio.com/docs/phone-numbers/regulatory/getting-started/create-new-bundle-public-rest-apis#supporting-document-create + */ + logoSid: string; + /** + * This is the string that you assigned as a friendly name for describing the creation of the configuration. + */ + friendlyName: string; + /** + * The product or service for which is requesting the signature. + */ + product: string; + /** + * The country ISO code to apply the configuration. + */ + country: string; + /** + * Subject of the email that the end client will receive ex: “Twilio Hosting Request”, maximum length of 255 characters. + */ + emailSubject: string; + /** + * Content of the email that the end client will receive ex: “This is a Hosting request from Twilio, please check the document and sign it”, maximum length of 5,000 characters. + */ + emailMessage: string; + /** + * Url the end client will be redirected after signing a document. + */ + urlRedirection: string; + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + logoSid: this.logoSid, + friendlyName: this.friendlyName, + product: this.product, + country: this.country, + emailSubject: this.emailSubject, + emailMessage: this.emailMessage, + urlRedirection: this.urlRedirection, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class SigningRequestConfigurationPage extends Page<V1, SigningRequestConfigurationPayload, SigningRequestConfigurationResource, SigningRequestConfigurationInstance> { +/** +* Initialize the SigningRequestConfigurationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SigningRequestConfigurationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SigningRequestConfigurationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SigningRequestConfigurationResource): SigningRequestConfigurationInstance { + + return new SigningRequestConfigurationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v1/webhook.ts b/rest/numbers/v1/webhook.ts new file mode 100644 index 000000000..20a8852ce --- /dev/null +++ b/rest/numbers/v1/webhook.ts @@ -0,0 +1,185 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface WebhookSolution { +} + +export interface WebhookListInstance { + _version: V1; + _solution: WebhookSolution; + _uri: string; + + + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance> + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WebhookListInstance(version: V1): WebhookListInstance { + const instance = {} as WebhookListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Porting/Configuration/Webhook`; + + instance.fetch = function fetch( callback?: (error: Error | null, items: WebhookInstance) => any): Promise<WebhookInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WebhookResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<WebhookInstance> => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface WebhookPayload extends WebhookResource {} + +interface WebhookResource { + url: string; + port_in_target_url: string; + port_out_target_url: string; + notifications_of: Array<string>; + port_in_target_date_created: Date; + port_out_target_date_created: Date; +} + +export class WebhookInstance { + + constructor(protected _version: V1, payload: WebhookResource) { + + this.url = (payload.url); + this.portInTargetUrl = (payload.port_in_target_url); + this.portOutTargetUrl = (payload.port_out_target_url); + this.notificationsOf = (payload.notifications_of); + this.portInTargetDateCreated = deserialize.iso8601DateTime(payload.port_in_target_date_created); + this.portOutTargetDateCreated = deserialize.iso8601DateTime(payload.port_out_target_date_created); + + } + + /** + * The URL of the webhook configuration request + */ + url: string; + /** + * The complete webhook url that will be called when a notification event for port in request or port in phone number happens + */ + portInTargetUrl: string; + /** + * The complete webhook url that will be called when a notification event for a port out phone number happens. + */ + portOutTargetUrl: string; + /** + * A list to filter what notification events to receive for this account and its sub accounts. If it is an empty list, then it means that there are no filters for the notifications events to send in each webhook and all events will get sent. + */ + notificationsOf: Array<string>; + /** + * Creation date for the port in webhook configuration + */ + portInTargetDateCreated: Date; + /** + * Creation date for the port out webhook configuration + */ + portOutTargetDateCreated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + url: this.url, + portInTargetUrl: this.portInTargetUrl, + portOutTargetUrl: this.portOutTargetUrl, + notificationsOf: this.notificationsOf, + portInTargetDateCreated: this.portInTargetDateCreated, + portOutTargetDateCreated: this.portOutTargetDateCreated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/numbers/v2/application.ts b/rest/numbers/v2/application.ts new file mode 100644 index 000000000..ac048e17c --- /dev/null +++ b/rest/numbers/v2/application.ts @@ -0,0 +1,984 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class CreateShortCodeApplicationRequest { + /** + * The friendly name for the short code application. + */ + "friendlyName": string; + /** + * The ISO country code. + */ + "isoCountry": string; + "businessInformation": CreateShortCodeApplicationRequestBusinessInformation; + "setup": CreateShortCodeApplicationRequestSetup; + + constructor(payload) { + this.friendlyName = payload["friendly_name"]; + this.isoCountry = payload["iso_country"]; + this.businessInformation = payload["business_information"]; + this.setup = payload["setup"]; + } +} + + +/** + * Business information associated with the application. + */ +export class CreateShortCodeApplicationRequestBusinessInformation { + /** + * The Compliance Profile SID for the customer-facing business profile. + */ + "customerFacingProfile": string; + + constructor(payload) { + this.customerFacingProfile = payload["customer_facing_profile"]; + } +} + + +export class CreateShortCodeApplicationRequestSetup { + "chargesApply": boolean; + + constructor(payload) { + this.chargesApply = payload["charges_apply"]; + } +} + + +/** + * Business information associated with the application. + */ +export class CreateShortCodeApplicationResponseBusinessInformation { + "managingCompanyProfile"?: string; + "customerFacingProfile"?: string; + "businessWebsite"?: string; + "einManagingCompanyProfile"?: string; + "einCustomerFacingProfile"?: string; + + constructor(payload) { + this.managingCompanyProfile = payload["managing_company_profile"]; + this.customerFacingProfile = payload["customer_facing_profile"]; + this.businessWebsite = payload["business_website"]; + this.einManagingCompanyProfile = payload["ein_managing_company_profile"]; + this.einCustomerFacingProfile = payload["ein_customer_facing_profile"]; + } +} + + +/** + * Compliance keywords for the application. + */ +export class CreateShortCodeApplicationResponseComplianceKeywords { + "help"?: string; + "stop"?: string; + "info"?: string; + "aide"?: string; + "arret"?: string; + "optOutFiltering"?: boolean; + + constructor(payload) { + this.help = payload["help"]; + this.stop = payload["stop"]; + this.info = payload["info"]; + this.aide = payload["aide"]; + this.arret = payload["arret"]; + this.optOutFiltering = payload["opt_out_filtering"]; + } +} + + +/** + * Content examples for the application. + */ +export class CreateShortCodeApplicationResponseContentExamples { + "examples"?: Array<string>; + + constructor(payload) { + this.examples = payload["examples"]; + } +} + + +/** + * Setup configuration for the application. + */ +export class CreateShortCodeApplicationResponseSetup { + "requestType"?: string; + "trafficType"?: string; + "leaseType"?: string; + "paymentFrequency"?: string; + "shortCodePreference"?: string; + "mmsEnabled"?: boolean; + "freeToEndUser"?: boolean; + "chargesApply"?: boolean; + "currentProvider"?: string; + "migratedMmsEnabled"?: boolean; + "migratedLiveTraffic"?: boolean; + + constructor(payload) { + this.requestType = payload["request_type"]; + this.trafficType = payload["traffic_type"]; + this.leaseType = payload["lease_type"]; + this.paymentFrequency = payload["payment_frequency"]; + this.shortCodePreference = payload["short_code_preference"]; + this.mmsEnabled = payload["mms_enabled"]; + this.freeToEndUser = payload["free_to_end_user"]; + this.chargesApply = payload["charges_apply"]; + this.currentProvider = payload["current_provider"]; + this.migratedMmsEnabled = payload["migrated_mms_enabled"]; + this.migratedLiveTraffic = payload["migrated_live_traffic"]; + } +} + + +/** + * SMS campaign details for the application. + */ +export class CreateShortCodeApplicationResponseSmsCampaignDetails { + "campaignName"?: string; + "campaignBrandWebsite"?: string; + "customerCareChannel"?: string; + "customerCareValue"?: string; + "campaignFrequency"?: Array<string>; + "scUseCaseCategories"?: Array<string>; + "smsTermsOfServiceUrl"?: string; + "smsPrivacyPolicyUrl"?: string; + "monthlyOutboundVolumeExpected"?: string; + "monthlyInboundVolumeExpected"?: string; + "avgMonthlyMessagesSentToEachSubscriber"?: string; + "avgMonthlyMessagesReceivedFromSubscribers"?: string; + "estimatedTotalSubscribers"?: string; + "durationOfTheCampaign"?: string; + "plannedTrafficSpikes"?: string; + "spikeDetails"?: string; + "expectedTrafficStartDate"?: string; + + constructor(payload) { + this.campaignName = payload["campaign_name"]; + this.campaignBrandWebsite = payload["campaign_brand_website"]; + this.customerCareChannel = payload["customer_care_channel"]; + this.customerCareValue = payload["customer_care_value"]; + this.campaignFrequency = payload["campaign_frequency"]; + this.scUseCaseCategories = payload["sc_use_case_categories"]; + this.smsTermsOfServiceUrl = payload["sms_terms_of_service_url"]; + this.smsPrivacyPolicyUrl = payload["sms_privacy_policy_url"]; + this.monthlyOutboundVolumeExpected = payload["monthly_outbound_volume_expected"]; + this.monthlyInboundVolumeExpected = payload["monthly_inbound_volume_expected"]; + this.avgMonthlyMessagesSentToEachSubscriber = payload["avg_monthly_messages_sent_to_each_subscriber"]; + this.avgMonthlyMessagesReceivedFromSubscribers = payload["avg_monthly_messages_received_from_subscribers"]; + this.estimatedTotalSubscribers = payload["estimated_total_subscribers"]; + this.durationOfTheCampaign = payload["duration_of_the_campaign"]; + this.plannedTrafficSpikes = payload["planned_traffic_spikes"]; + this.spikeDetails = payload["spike_details"]; + this.expectedTrafficStartDate = payload["expected_traffic_start_date"]; + } +} + + +/** + * User sign-up configuration for the application. + */ +export class CreateShortCodeApplicationResponseUserSignUp { + "signUpOptions"?: Array<string>; + "doubleOptInProcess"?: boolean; + "doubleOptInMessage"?: string; + "signUpConfirmationMessage"?: string; + "doubleOptInResponseMessage"?: string; + "onlineWebFormMessage"?: string; + "keywordMessage"?: string; + "ivrMessage"?: string; + "otherFormMessage"?: string; + + constructor(payload) { + this.signUpOptions = payload["sign_up_options"]; + this.doubleOptInProcess = payload["double_opt_in_process"]; + this.doubleOptInMessage = payload["double_opt_in_message"]; + this.signUpConfirmationMessage = payload["sign_up_confirmation_message"]; + this.doubleOptInResponseMessage = payload["double_opt_in_response_message"]; + this.onlineWebFormMessage = payload["online_web_form_message"]; + this.keywordMessage = payload["keyword_message"]; + this.ivrMessage = payload["ivr_message"]; + this.otherFormMessage = payload["other_form_message"]; + } +} + + + + +/** + * Options to pass to create a ApplicationInstance + */ +export interface ApplicationListInstanceCreateOptions { + /** */ + "createShortCodeApplicationRequest": CreateShortCodeApplicationRequest; +} + +/** + * Options to pass to each + */ +export interface ApplicationListInstanceEachOptions { + /** The Account SID to filter by. */ + "accountSid"?: string; + /** The ISO country to filter by. */ + "isoCountry"?: string; + /** The application status to filter by. */ + "status"?: string; + /** The friendly name to filter by. */ + "friendlyName"?: string; + /** The application SID to filter by. */ + "sid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ApplicationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ApplicationListInstanceOptions { + /** The Account SID to filter by. */ + "accountSid"?: string; + /** The ISO country to filter by. */ + "isoCountry"?: string; + /** The application status to filter by. */ + "status"?: string; + /** The friendly name to filter by. */ + "friendlyName"?: string; + /** The application SID to filter by. */ + "sid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ApplicationListInstancePageOptions { + /** The Account SID to filter by. */ + "accountSid"?: string; + /** The ISO country to filter by. */ + "isoCountry"?: string; + /** The application status to filter by. */ + "status"?: string; + /** The friendly name to filter by. */ + "friendlyName"?: string; + /** The application SID to filter by. */ + "sid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 50. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ApplicationContext { + + /** + * Fetch a ApplicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + fetch(callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise<ApplicationInstance> + + /** + * Fetch a ApplicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ApplicationInstance>) => any): Promise<ApiResponse<ApplicationInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ApplicationContextSolution { + "sid": string; +} + +export class ApplicationContextImpl implements ApplicationContext { + protected _solution: ApplicationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/ShortCodes/Applications/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise<ApplicationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ApplicationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ApplicationInstance>) => any): Promise<ApiResponse<ApplicationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ApplicationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ApplicationInstance> => ({ + ...response, + body: new ApplicationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ApplicationPayload extends TwilioResponsePayload { + results: ApplicationResource[]; +} + +interface ApplicationResource { + sid: string; + application_requirements_sid: string; + application_requirements_version: number; + account_sid: string; + bundle_sid: string; + reviewer: string; + zendesk_ticket_id: string; + friendly_name: string; + notification_emails: Array<string>; + iso_country: string; + state: string; + setup: CreateShortCodeApplicationResponseSetup; + business_information: CreateShortCodeApplicationResponseBusinessInformation; + user_sign_up: CreateShortCodeApplicationResponseUserSignUp; + compliance_keywords: CreateShortCodeApplicationResponseComplianceKeywords; + content_examples: CreateShortCodeApplicationResponseContentExamples; + sms_campaign_details: CreateShortCodeApplicationResponseSmsCampaignDetails; + date_created: Date; + date_updated: Date; + created_by: string; + updated_by: string; +} + +export class ApplicationInstance { + protected _solution: ApplicationContextSolution; + protected _context?: ApplicationContext; + + constructor(protected _version: V2, payload: ApplicationResource, sid?: string) { + + this.sid = (payload.sid); + this.applicationRequirementsSid = (payload.application_requirements_sid); + this.applicationRequirementsVersion = deserialize.integer(payload.application_requirements_version); + this.accountSid = (payload.account_sid); + this.bundleSid = (payload.bundle_sid); + this.reviewer = (payload.reviewer); + this.zendeskTicketId = (payload.zendesk_ticket_id); + this.friendlyName = (payload.friendly_name); + this.notificationEmails = (payload.notification_emails); + this.isoCountry = (payload.iso_country); + this.state = (payload.state); + this.setup = payload.setup !== null && payload.setup !== undefined ? new CreateShortCodeApplicationResponseSetup(payload.setup) : null; + this.businessInformation = payload.business_information !== null && payload.business_information !== undefined ? new CreateShortCodeApplicationResponseBusinessInformation(payload.business_information) : null; + this.userSignUp = payload.user_sign_up !== null && payload.user_sign_up !== undefined ? new CreateShortCodeApplicationResponseUserSignUp(payload.user_sign_up) : null; + this.complianceKeywords = payload.compliance_keywords !== null && payload.compliance_keywords !== undefined ? new CreateShortCodeApplicationResponseComplianceKeywords(payload.compliance_keywords) : null; + this.contentExamples = payload.content_examples !== null && payload.content_examples !== undefined ? new CreateShortCodeApplicationResponseContentExamples(payload.content_examples) : null; + this.smsCampaignDetails = payload.sms_campaign_details !== null && payload.sms_campaign_details !== undefined ? new CreateShortCodeApplicationResponseSmsCampaignDetails(payload.sms_campaign_details) : null; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + this.updatedBy = (payload.updated_by); + + this._solution = { sid: sid, }; + } + + /** + * The unique identifier of the Short Code Application. + */ + sid: string; + /** + * The Application Requirements SID. + */ + applicationRequirementsSid: string; + /** + * The version of the application requirements. + */ + applicationRequirementsVersion: number; + /** + * The Account SID associated with the application. + */ + accountSid: string; + /** + * The Bundle SID for regulatory compliance. + */ + bundleSid: string; + /** + * The reviewer of the application. + */ + reviewer: string; + /** + * The Zendesk ticket ID associated with the application. + */ + zendeskTicketId: string; + /** + * The friendly name of the application. + */ + friendlyName: string; + /** + * The notification emails for the application. + */ + notificationEmails: Array<string>; + /** + * The ISO country code. + */ + isoCountry: string; + /** + * The state of the application. + */ + state: string; + setup: CreateShortCodeApplicationResponseSetup; + businessInformation: CreateShortCodeApplicationResponseBusinessInformation; + userSignUp: CreateShortCodeApplicationResponseUserSignUp; + complianceKeywords: CreateShortCodeApplicationResponseComplianceKeywords; + contentExamples: CreateShortCodeApplicationResponseContentExamples; + smsCampaignDetails: CreateShortCodeApplicationResponseSmsCampaignDetails; + /** + * The date and time the application was created. + */ + dateCreated: Date; + /** + * The date and time the application was last updated. + */ + dateUpdated: Date; + /** + * The identity of the user who created the application. + */ + createdBy: string; + /** + * The identity of the user who last updated the application. + */ + updatedBy: string; + + private get _proxy(): ApplicationContext { + this._context = this._context || new ApplicationContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a ApplicationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + fetch(callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise<ApplicationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ApplicationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ApplicationInstance>) => any): Promise<ApiResponse<ApplicationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + applicationRequirementsSid: this.applicationRequirementsSid, + applicationRequirementsVersion: this.applicationRequirementsVersion, + accountSid: this.accountSid, + bundleSid: this.bundleSid, + reviewer: this.reviewer, + zendeskTicketId: this.zendeskTicketId, + friendlyName: this.friendlyName, + notificationEmails: this.notificationEmails, + isoCountry: this.isoCountry, + state: this.state, + setup: this.setup, + businessInformation: this.businessInformation, + userSignUp: this.userSignUp, + complianceKeywords: this.complianceKeywords, + contentExamples: this.contentExamples, + smsCampaignDetails: this.smsCampaignDetails, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + updatedBy: this.updatedBy, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ApplicationSolution { +} + +export interface ApplicationListInstance { + _version: V2; + _solution: ApplicationSolution; + _uri: string; + + (sid: string, ): ApplicationContext; + get(sid: string, ): ApplicationContext; + + + + + /** + * Create a ApplicationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance + */ + create(params: CreateShortCodeApplicationRequest, headers?: any, callback?: (error: Error | null, item?: ApplicationInstance) => any): Promise<ApplicationInstance>; + + /** + * Create a ApplicationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApplicationInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateShortCodeApplicationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ApplicationInstance>) => any): Promise<ApiResponse<ApplicationInstance>>; + + + + + /** + * Streams ApplicationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ApplicationInstance, done: (err?: Error) => void) => void): void; + each(params: ApplicationListInstanceEachOptions, callback?: (item: ApplicationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ApplicationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ApplicationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ApplicationListInstanceEachOptions, callback?: (item: ApplicationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ApplicationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ApplicationPage) => any): Promise<ApplicationPage>; + /** + * Retrieve a single target page of ApplicationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ApplicationPage>) => any): Promise<ApiResponse<ApplicationPage>>; + /** + * Lists ApplicationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ApplicationInstance[]) => any): Promise<ApplicationInstance[]>; + list(params: ApplicationListInstanceOptions, callback?: (error: Error | null, items: ApplicationInstance[]) => any): Promise<ApplicationInstance[]>; + /** + * Lists ApplicationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ApplicationInstance[]>) => any): Promise<ApiResponse<ApplicationInstance[]>>; + listWithHttpInfo(params: ApplicationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ApplicationInstance[]>) => any): Promise<ApiResponse<ApplicationInstance[]>>; + /** + * Retrieve a single page of ApplicationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ApplicationPage) => any): Promise<ApplicationPage>; + page(params: ApplicationListInstancePageOptions, callback?: (error: Error | null, items: ApplicationPage) => any): Promise<ApplicationPage>; + /** + * Retrieve a single page of ApplicationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ApplicationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ApplicationPage>) => any): Promise<ApiResponse<ApplicationPage>>; + pageWithHttpInfo(params: ApplicationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ApplicationPage>) => any): Promise<ApiResponse<ApplicationPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ApplicationListInstance(version: V2): ApplicationListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ApplicationListInstance; + + instance.get = function get(sid, ): ApplicationContext { + return new ApplicationContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ShortCodes/Applications`; + + instance.create = function create(params: CreateShortCodeApplicationRequest, headers?: any, callback?: (error: Error | null, items: ApplicationInstance) => any): Promise<ApplicationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ApplicationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateShortCodeApplicationRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<ApplicationInstance>) => any): Promise<ApiResponse<ApplicationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ApplicationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ApplicationInstance> => ({ + ...response, + body: new ApplicationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ApplicationListInstancePageOptions | ((error: Error | null, items: ApplicationPage) => any), callback?: (error: Error | null, items: ApplicationPage) => any): Promise<ApplicationPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["sid"] !== undefined) + data["Sid"] = params["sid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ApplicationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ApplicationPage) => any): Promise<ApplicationPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ApplicationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ApplicationListInstancePageOptions | ((error: Error | null, items: ApiResponse<ApplicationPage>) => any), callback?: (error: Error | null, items: ApiResponse<ApplicationPage>) => any): Promise<ApiResponse<ApplicationPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["sid"] !== undefined) + data["Sid"] = params["sid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ApplicationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ApplicationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ApplicationPage>) => any): Promise<ApiResponse<ApplicationPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ApplicationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ApplicationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ApplicationPage extends Page<V2, ApplicationPayload, ApplicationResource, ApplicationInstance> { +/** +* Initialize the ApplicationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: ApplicationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ApplicationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ApplicationResource): ApplicationInstance { + + return new ApplicationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/authorizationDocument.ts b/rest/numbers/v2/authorizationDocument.ts new file mode 100644 index 000000000..c783fa3ff --- /dev/null +++ b/rest/numbers/v2/authorizationDocument.ts @@ -0,0 +1,834 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { DependentHostedNumberOrderListInstance } from "./authorizationDocument/dependentHostedNumberOrder"; + + +/** + * Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + */ +export type AuthorizationDocumentStatus = 'opened'|'signing'|'signed'|'canceled'|'failed'; + + + + +/** + * Options to pass to create a AuthorizationDocumentInstance + */ +export interface AuthorizationDocumentListInstanceCreateOptions { + /** A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. */ + "addressSid": string; + /** Email that this AuthorizationDocument will be sent to for signing. */ + "email": string; + /** The contact phone number of the person authorized to sign the Authorization Document. */ + "contactPhoneNumber": string; + /** A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio\\\'s platform. */ + "hostedNumberOrderSids": Array<string>; + /** The title of the person authorized to sign the Authorization Document for this phone number. */ + "contactTitle"?: string; + /** Email recipients who will be informed when an Authorization Document has been sent and signed. */ + "ccEmails"?: Array<string>; +} + +/** + * Options to pass to each + */ +export interface AuthorizationDocumentListInstanceEachOptions { + /** Email that this AuthorizationDocument will be sent to for signing. */ + "email"?: string; + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: AuthorizationDocumentStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AuthorizationDocumentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AuthorizationDocumentListInstanceOptions { + /** Email that this AuthorizationDocument will be sent to for signing. */ + "email"?: string; + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: AuthorizationDocumentStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AuthorizationDocumentListInstancePageOptions { + /** Email that this AuthorizationDocument will be sent to for signing. */ + "email"?: string; + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: AuthorizationDocumentStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AuthorizationDocumentContext { + dependentHostedNumberOrders: DependentHostedNumberOrderListInstance; + + /** + * Remove a AuthorizationDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a AuthorizationDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a AuthorizationDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance + */ + fetch(callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance> + + /** + * Fetch a AuthorizationDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AuthorizationDocumentContextSolution { + "sid": string; +} + +export class AuthorizationDocumentContextImpl implements AuthorizationDocumentContext { + protected _solution: AuthorizationDocumentContextSolution; + protected _uri: string; + + protected _dependentHostedNumberOrders?: DependentHostedNumberOrderListInstance; + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/HostedNumber/AuthorizationDocuments/${sid}`; + } + + get dependentHostedNumberOrders(): DependentHostedNumberOrderListInstance { + this._dependentHostedNumberOrders = this._dependentHostedNumberOrders || DependentHostedNumberOrderListInstance(this._version, this._solution.sid); + return this._dependentHostedNumberOrders; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AuthorizationDocumentInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AuthorizationDocumentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AuthorizationDocumentInstance> => ({ + ...response, + body: new AuthorizationDocumentInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AuthorizationDocumentPayload extends TwilioResponsePayload { + items: AuthorizationDocumentResource[]; +} + +interface AuthorizationDocumentResource { + sid: string; + address_sid: string; + status: AuthorizationDocumentStatus; + email: string; + cc_emails: Array<string>; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class AuthorizationDocumentInstance { + protected _solution: AuthorizationDocumentContextSolution; + protected _context?: AuthorizationDocumentContext; + + constructor(protected _version: V2, payload: AuthorizationDocumentResource, sid?: string) { + + this.sid = (payload.sid); + this.addressSid = (payload.address_sid); + this.status = payload.status; + this.email = (payload.email); + this.ccEmails = (payload.cc_emails); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this AuthorizationDocument. + */ + sid: string; + /** + * A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + */ + addressSid: string; + status: AuthorizationDocumentStatus; + /** + * Email that this AuthorizationDocument will be sent to for signing. + */ + email: string; + /** + * Email recipients who will be informed when an Authorization Document has been sent and signed. + */ + ccEmails: Array<string>; + /** + * The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + url: string; + links: Record<string, string>; + + private get _proxy(): AuthorizationDocumentContext { + this._context = this._context || new AuthorizationDocumentContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a AuthorizationDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AuthorizationDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AuthorizationDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance + */ + fetch(callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AuthorizationDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the dependentHostedNumberOrders. + */ + dependentHostedNumberOrders(): DependentHostedNumberOrderListInstance { + return this._proxy.dependentHostedNumberOrders; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + addressSid: this.addressSid, + status: this.status, + email: this.email, + ccEmails: this.ccEmails, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AuthorizationDocumentSolution { +} + +export interface AuthorizationDocumentListInstance { + _version: V2; + _solution: AuthorizationDocumentSolution; + _uri: string; + + (sid: string, ): AuthorizationDocumentContext; + get(sid: string, ): AuthorizationDocumentContext; + + + + + + + /** + * Create a AuthorizationDocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance + */ + create(params: AuthorizationDocumentListInstanceCreateOptions, callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance>; + + /** + * Create a AuthorizationDocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance with HTTP metadata + */ + createWithHttpInfo(params: AuthorizationDocumentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>>; + + + + + /** + * Streams AuthorizationDocumentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AuthorizationDocumentInstance, done: (err?: Error) => void) => void): void; + each(params: AuthorizationDocumentListInstanceEachOptions, callback?: (item: AuthorizationDocumentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AuthorizationDocumentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AuthorizationDocumentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AuthorizationDocumentListInstanceEachOptions, callback?: (item: AuthorizationDocumentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AuthorizationDocumentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AuthorizationDocumentPage) => any): Promise<AuthorizationDocumentPage>; + /** + * Retrieve a single target page of AuthorizationDocumentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentPage>) => any): Promise<ApiResponse<AuthorizationDocumentPage>>; + /** + * Lists AuthorizationDocumentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AuthorizationDocumentInstance[]) => any): Promise<AuthorizationDocumentInstance[]>; + list(params: AuthorizationDocumentListInstanceOptions, callback?: (error: Error | null, items: AuthorizationDocumentInstance[]) => any): Promise<AuthorizationDocumentInstance[]>; + /** + * Lists AuthorizationDocumentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentInstance[]>) => any): Promise<ApiResponse<AuthorizationDocumentInstance[]>>; + listWithHttpInfo(params: AuthorizationDocumentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentInstance[]>) => any): Promise<ApiResponse<AuthorizationDocumentInstance[]>>; + /** + * Retrieve a single page of AuthorizationDocumentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AuthorizationDocumentPage) => any): Promise<AuthorizationDocumentPage>; + page(params: AuthorizationDocumentListInstancePageOptions, callback?: (error: Error | null, items: AuthorizationDocumentPage) => any): Promise<AuthorizationDocumentPage>; + /** + * Retrieve a single page of AuthorizationDocumentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentPage>) => any): Promise<ApiResponse<AuthorizationDocumentPage>>; + pageWithHttpInfo(params: AuthorizationDocumentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentPage>) => any): Promise<ApiResponse<AuthorizationDocumentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AuthorizationDocumentListInstance(version: V2): AuthorizationDocumentListInstance { + const instance = ((sid, ) => instance.get(sid, )) as AuthorizationDocumentListInstance; + + instance.get = function get(sid, ): AuthorizationDocumentContext { + return new AuthorizationDocumentContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/HostedNumber/AuthorizationDocuments`; + + instance.create = function create(params: AuthorizationDocumentListInstanceCreateOptions, callback?: (error: Error | null, items: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["addressSid"] === null || params["addressSid"] === undefined) { + throw new Error('Required parameter "params[\'addressSid\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + if (params["contactPhoneNumber"] === null || params["contactPhoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'contactPhoneNumber\']" missing.'); + } + + if (params["hostedNumberOrderSids"] === null || params["hostedNumberOrderSids"] === undefined) { + throw new Error('Required parameter "params[\'hostedNumberOrderSids\']" missing.'); + } + + let data: any = {}; + + + + data["AddressSid"] = params["addressSid"]; + + data["Email"] = params["email"]; + + data["ContactPhoneNumber"] = params["contactPhoneNumber"]; + + data["HostedNumberOrderSids"] = serialize.map(params["hostedNumberOrderSids"], (e: string) => (e)); + if (params["contactTitle"] !== undefined) + data["ContactTitle"] = params["contactTitle"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AuthorizationDocumentInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AuthorizationDocumentListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["addressSid"] === null || params["addressSid"] === undefined) { + throw new Error('Required parameter "params[\'addressSid\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + if (params["contactPhoneNumber"] === null || params["contactPhoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'contactPhoneNumber\']" missing.'); + } + + if (params["hostedNumberOrderSids"] === null || params["hostedNumberOrderSids"] === undefined) { + throw new Error('Required parameter "params[\'hostedNumberOrderSids\']" missing.'); + } + + let data: any = {}; + + + + data["AddressSid"] = params["addressSid"]; + + data["Email"] = params["email"]; + + data["ContactPhoneNumber"] = params["contactPhoneNumber"]; + + data["HostedNumberOrderSids"] = serialize.map(params["hostedNumberOrderSids"], (e: string) => (e)); + if (params["contactTitle"] !== undefined) + data["ContactTitle"] = params["contactTitle"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<AuthorizationDocumentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<AuthorizationDocumentInstance> => ({ + ...response, + body: new AuthorizationDocumentInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AuthorizationDocumentListInstancePageOptions | ((error: Error | null, items: AuthorizationDocumentPage) => any), callback?: (error: Error | null, items: AuthorizationDocumentPage) => any): Promise<AuthorizationDocumentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AuthorizationDocumentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AuthorizationDocumentPage) => any): Promise<AuthorizationDocumentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AuthorizationDocumentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AuthorizationDocumentListInstancePageOptions | ((error: Error | null, items: ApiResponse<AuthorizationDocumentPage>) => any), callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentPage>) => any): Promise<ApiResponse<AuthorizationDocumentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AuthorizationDocumentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthorizationDocumentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AuthorizationDocumentPage>) => any): Promise<ApiResponse<AuthorizationDocumentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AuthorizationDocumentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthorizationDocumentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AuthorizationDocumentPage extends Page<V2, AuthorizationDocumentPayload, AuthorizationDocumentResource, AuthorizationDocumentInstance> { +/** +* Initialize the AuthorizationDocumentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: AuthorizationDocumentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AuthorizationDocumentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AuthorizationDocumentResource): AuthorizationDocumentInstance { + + return new AuthorizationDocumentInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/authorizationDocument/dependentHostedNumberOrder.ts b/rest/numbers/v2/authorizationDocument/dependentHostedNumberOrder.ts new file mode 100644 index 000000000..28fff8571 --- /dev/null +++ b/rest/numbers/v2/authorizationDocument/dependentHostedNumberOrder.ts @@ -0,0 +1,543 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../interfaces"; + + +/** + * Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + */ +export type DependentHostedNumberOrderStatus = 'received'|'verified'|'pending-loa'|'carrier-processing'|'completed'|'failed'|'action-required'; + + +/** + * Options to pass to each + */ +export interface DependentHostedNumberOrderListInstanceEachOptions { + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: DependentHostedNumberOrderStatus; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 128 characters. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DependentHostedNumberOrderListInstanceOptions { + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: DependentHostedNumberOrderStatus; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 128 characters. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DependentHostedNumberOrderListInstancePageOptions { + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: DependentHostedNumberOrderStatus; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 128 characters. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface DependentHostedNumberOrderSolution { + signingDocumentSid: string; +} + +export interface DependentHostedNumberOrderListInstance { + _version: V2; + _solution: DependentHostedNumberOrderSolution; + _uri: string; + + + + + /** + * Streams DependentHostedNumberOrderInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + each(params: DependentHostedNumberOrderListInstanceEachOptions, callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DependentHostedNumberOrderInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DependentHostedNumberOrderListInstanceEachOptions, callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DependentHostedNumberOrderInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage>; + /** + * Retrieve a single target page of DependentHostedNumberOrderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderPage>) => any): Promise<ApiResponse<DependentHostedNumberOrderPage>>; + /** + * Lists DependentHostedNumberOrderInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DependentHostedNumberOrderInstance[]) => any): Promise<DependentHostedNumberOrderInstance[]>; + list(params: DependentHostedNumberOrderListInstanceOptions, callback?: (error: Error | null, items: DependentHostedNumberOrderInstance[]) => any): Promise<DependentHostedNumberOrderInstance[]>; + /** + * Lists DependentHostedNumberOrderInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderInstance[]>) => any): Promise<ApiResponse<DependentHostedNumberOrderInstance[]>>; + listWithHttpInfo(params: DependentHostedNumberOrderListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderInstance[]>) => any): Promise<ApiResponse<DependentHostedNumberOrderInstance[]>>; + /** + * Retrieve a single page of DependentHostedNumberOrderInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage>; + page(params: DependentHostedNumberOrderListInstancePageOptions, callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage>; + /** + * Retrieve a single page of DependentHostedNumberOrderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderPage>) => any): Promise<ApiResponse<DependentHostedNumberOrderPage>>; + pageWithHttpInfo(params: DependentHostedNumberOrderListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderPage>) => any): Promise<ApiResponse<DependentHostedNumberOrderPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DependentHostedNumberOrderListInstance(version: V2, signingDocumentSid: string): DependentHostedNumberOrderListInstance { + if (!isValidPathParam(signingDocumentSid)) { + throw new Error('Parameter \'signingDocumentSid\' is not valid.'); + } + + const instance = {} as DependentHostedNumberOrderListInstance; + + instance._version = version; + instance._solution = { signingDocumentSid, }; + instance._uri = `/HostedNumber/AuthorizationDocuments/${signingDocumentSid}/DependentHostedNumberOrders`; + + instance.page = function page(params?: DependentHostedNumberOrderListInstancePageOptions | ((error: Error | null, items: DependentHostedNumberOrderPage) => any), callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["incomingPhoneNumberSid"] !== undefined) + data["IncomingPhoneNumberSid"] = params["incomingPhoneNumberSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DependentHostedNumberOrderPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DependentHostedNumberOrderPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DependentHostedNumberOrderListInstancePageOptions | ((error: Error | null, items: ApiResponse<DependentHostedNumberOrderPage>) => any), callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderPage>) => any): Promise<ApiResponse<DependentHostedNumberOrderPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["incomingPhoneNumberSid"] !== undefined) + data["IncomingPhoneNumberSid"] = params["incomingPhoneNumberSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<DependentHostedNumberOrderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DependentHostedNumberOrderPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<DependentHostedNumberOrderPage>) => any): Promise<ApiResponse<DependentHostedNumberOrderPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<DependentHostedNumberOrderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DependentHostedNumberOrderPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface DependentHostedNumberOrderPayload extends TwilioResponsePayload { + items: DependentHostedNumberOrderResource[]; +} + +interface DependentHostedNumberOrderResource { + sid: string; + bulk_hosting_request_sid: string; + next_step: string; + account_sid: string; + incoming_phone_number_sid: string; + address_sid: string; + signing_document_sid: string; + phone_number: string; + capabilities: PhoneNumberCapabilities; + friendly_name: string; + status: DependentHostedNumberOrderStatus; + failure_reason: string; + date_created: Date; + date_updated: Date; + email: string; + cc_emails: Array<string>; + contact_title: string; + contact_phone_number: string; +} + +export class DependentHostedNumberOrderInstance { + + constructor(protected _version: V2, payload: DependentHostedNumberOrderResource, signingDocumentSid: string) { + + this.sid = (payload.sid); + this.bulkHostingRequestSid = (payload.bulk_hosting_request_sid); + this.nextStep = (payload.next_step); + this.accountSid = (payload.account_sid); + this.incomingPhoneNumberSid = (payload.incoming_phone_number_sid); + this.addressSid = (payload.address_sid); + this.signingDocumentSid = (payload.signing_document_sid); + this.phoneNumber = (payload.phone_number); + this.capabilities = (payload.capabilities); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.failureReason = (payload.failure_reason); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.email = (payload.email); + this.ccEmails = (payload.cc_emails); + this.contactTitle = (payload.contact_title); + this.contactPhoneNumber = (payload.contact_phone_number); + + } + + /** + * A 34 character string that uniquely identifies this Authorization Document + */ + sid: string; + /** + * A 34 character string that uniquely identifies the bulk hosting request associated with this HostedNumberOrder. + */ + bulkHostingRequestSid: string; + /** + * The next step you need to take to complete the hosted number order and request it successfully. + */ + nextStep: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + */ + incomingPhoneNumberSid: string; + /** + * A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + */ + addressSid: string; + /** + * A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + */ + signingDocumentSid: string; + /** + * An E164 formatted phone number hosted by this HostedNumberOrder. + */ + phoneNumber: string; + capabilities: PhoneNumberCapabilities; + /** + * A human readable description of this resource, up to 128 characters. + */ + friendlyName: string; + status: DependentHostedNumberOrderStatus; + /** + * A message that explains why a hosted_number_order went to status \"action-required\" + */ + failureReason: string; + /** + * The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * Email of the owner of this phone number that is being hosted. + */ + email: string; + /** + * Email recipients who will be informed when an Authorization Document has been sent and signed + */ + ccEmails: Array<string>; + /** + * The title of the person authorized to sign the Authorization Document for this phone number. + */ + contactTitle: string; + /** + * The contact phone number of the person authorized to sign the Authorization Document. + */ + contactPhoneNumber: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + bulkHostingRequestSid: this.bulkHostingRequestSid, + nextStep: this.nextStep, + accountSid: this.accountSid, + incomingPhoneNumberSid: this.incomingPhoneNumberSid, + addressSid: this.addressSid, + signingDocumentSid: this.signingDocumentSid, + phoneNumber: this.phoneNumber, + capabilities: this.capabilities, + friendlyName: this.friendlyName, + status: this.status, + failureReason: this.failureReason, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + email: this.email, + ccEmails: this.ccEmails, + contactTitle: this.contactTitle, + contactPhoneNumber: this.contactPhoneNumber, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class DependentHostedNumberOrderPage extends Page<V2, DependentHostedNumberOrderPayload, DependentHostedNumberOrderResource, DependentHostedNumberOrderInstance> { +/** +* Initialize the DependentHostedNumberOrderPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: DependentHostedNumberOrderSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DependentHostedNumberOrderInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DependentHostedNumberOrderResource): DependentHostedNumberOrderInstance { + + return new DependentHostedNumberOrderInstance( + this._version, + payload, + this._solution.signingDocumentSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/bulkHostedNumberOrder.ts b/rest/numbers/v2/bulkHostedNumberOrder.ts new file mode 100644 index 000000000..62e5bd41b --- /dev/null +++ b/rest/numbers/v2/bulkHostedNumberOrder.ts @@ -0,0 +1,484 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * A string that shows the status of the current Bulk Hosting request, it can vary between these values: \'QUEUED\',\'IN_PROGRESS\',\'PROCESSED\' + */ +export type BulkHostedNumberOrderRequestStatus = 'QUEUED'|'IN_PROGRESS'|'PROCESSED'; + + +/** + * Options to pass to fetch a BulkHostedNumberOrderInstance + */ +export interface BulkHostedNumberOrderContextFetchOptions { + /** Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check \'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values\'. */ + "orderStatus"?: string; +} + +/** + * Options to pass to create a BulkHostedNumberOrderInstance + */ +export interface BulkHostedNumberOrderListInstanceCreateOptions { + /** */ + "body"?: object; +} + +export interface BulkHostedNumberOrderContext { + + /** + * Fetch a BulkHostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance + */ + fetch(callback?: (error: Error | null, item?: BulkHostedNumberOrderInstance) => any): Promise<BulkHostedNumberOrderInstance>; + /** + * Fetch a BulkHostedNumberOrderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance + */ + fetch(params: BulkHostedNumberOrderContextFetchOptions, callback?: (error: Error | null, item?: BulkHostedNumberOrderInstance) => any): Promise<BulkHostedNumberOrderInstance>; + + /** + * Fetch a BulkHostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BulkHostedNumberOrderInstance>) => any): Promise<ApiResponse<BulkHostedNumberOrderInstance>>; + /** + * Fetch a BulkHostedNumberOrderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance with HTTP metadata + */ + fetchWithHttpInfo(params: BulkHostedNumberOrderContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<BulkHostedNumberOrderInstance>) => any): Promise<ApiResponse<BulkHostedNumberOrderInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BulkHostedNumberOrderContextSolution { + "bulkHostingSid": string; +} + +export class BulkHostedNumberOrderContextImpl implements BulkHostedNumberOrderContext { + protected _solution: BulkHostedNumberOrderContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, bulkHostingSid: string) { + if (!isValidPathParam(bulkHostingSid)) { + throw new Error('Parameter \'bulkHostingSid\' is not valid.'); + } + + this._solution = { bulkHostingSid, }; + this._uri = `/HostedNumber/Orders/Bulk/${bulkHostingSid}`; + } + + fetch(params?: BulkHostedNumberOrderContextFetchOptions | ((error: Error | null, item?: BulkHostedNumberOrderInstance) => any),callback?: (error: Error | null, item?: BulkHostedNumberOrderInstance) => any): Promise<BulkHostedNumberOrderInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["orderStatus"] !== undefined) + data["OrderStatus"] = params["orderStatus"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new BulkHostedNumberOrderInstance(operationVersion, payload, instance._solution.bulkHostingSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: BulkHostedNumberOrderContextFetchOptions | ((error: Error | null, item?: ApiResponse<BulkHostedNumberOrderInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<BulkHostedNumberOrderInstance>) => any): Promise<ApiResponse<BulkHostedNumberOrderInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["orderStatus"] !== undefined) + data["OrderStatus"] = params["orderStatus"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<BulkHostedNumberOrderResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<BulkHostedNumberOrderInstance> => ({ + ...response, + body: new BulkHostedNumberOrderInstance(operationVersion, response.body, instance._solution.bulkHostingSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BulkHostedNumberOrderPayload extends BulkHostedNumberOrderResource {} + +interface BulkHostedNumberOrderResource { + bulk_hosting_sid: string; + request_status: BulkHostedNumberOrderRequestStatus; + friendly_name: string; + notification_email: string; + date_created: Date; + date_completed: Date; + url: string; + total_count: number; + results: Array<any>; +} + +export class BulkHostedNumberOrderInstance { + protected _solution: BulkHostedNumberOrderContextSolution; + protected _context?: BulkHostedNumberOrderContext; + + constructor(protected _version: V2, payload: BulkHostedNumberOrderResource, bulkHostingSid?: string) { + + this.bulkHostingSid = (payload.bulk_hosting_sid); + this.requestStatus = payload.request_status; + this.friendlyName = (payload.friendly_name); + this.notificationEmail = (payload.notification_email); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateCompleted = deserialize.iso8601DateTime(payload.date_completed); + this.url = (payload.url); + this.totalCount = deserialize.integer(payload.total_count); + this.results = (payload.results); + + this._solution = { bulkHostingSid: bulkHostingSid, }; + } + + /** + * A 34 character string that uniquely identifies this BulkHostedNumberOrder. + */ + bulkHostingSid: string; + requestStatus: BulkHostedNumberOrderRequestStatus; + /** + * A 128 character string that is a human-readable text that describes this resource. + */ + friendlyName: string; + /** + * Email address used for send notifications about this Bulk hosted number request. + */ + notificationEmail: string; + /** + * The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date that this resource was completed, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCompleted: Date; + /** + * The URL of this BulkHostedNumberOrder resource. + */ + url: string; + /** + * The total count of phone numbers in this Bulk hosting request. + */ + totalCount: number; + /** + * Contains a list of all the individual hosting orders and their information, for this Bulk request. Each result object is grouped by its order status. To see a complete list of order status, please check \'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values\'. + */ + results: Array<any>; + + private get _proxy(): BulkHostedNumberOrderContext { + this._context = this._context || new BulkHostedNumberOrderContextImpl(this._version, this._solution.bulkHostingSid); + return this._context; + } + + /** + * Fetch a BulkHostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance + */ + fetch(callback?: (error: Error | null, item?: BulkHostedNumberOrderInstance) => any): Promise<BulkHostedNumberOrderInstance>; + /** + * Fetch a BulkHostedNumberOrderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance + */ + fetch(params: BulkHostedNumberOrderContextFetchOptions, callback?: (error: Error | null, item?: BulkHostedNumberOrderInstance) => any): Promise<BulkHostedNumberOrderInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: BulkHostedNumberOrderInstance) => any): Promise<BulkHostedNumberOrderInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a BulkHostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BulkHostedNumberOrderInstance>) => any): Promise<ApiResponse<BulkHostedNumberOrderInstance>>; + /** + * Fetch a BulkHostedNumberOrderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance with HTTP metadata + */ + fetchWithHttpInfo(params: BulkHostedNumberOrderContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<BulkHostedNumberOrderInstance>) => any): Promise<ApiResponse<BulkHostedNumberOrderInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<BulkHostedNumberOrderInstance>) => any): Promise<ApiResponse<BulkHostedNumberOrderInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + bulkHostingSid: this.bulkHostingSid, + requestStatus: this.requestStatus, + friendlyName: this.friendlyName, + notificationEmail: this.notificationEmail, + dateCreated: this.dateCreated, + dateCompleted: this.dateCompleted, + url: this.url, + totalCount: this.totalCount, + results: this.results, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BulkHostedNumberOrderSolution { +} + +export interface BulkHostedNumberOrderListInstance { + _version: V2; + _solution: BulkHostedNumberOrderSolution; + _uri: string; + + (bulkHostingSid: string, ): BulkHostedNumberOrderContext; + get(bulkHostingSid: string, ): BulkHostedNumberOrderContext; + + + + + /** + * Create a BulkHostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance + */ + create(callback?: (error: Error | null, item?: BulkHostedNumberOrderInstance) => any): Promise<BulkHostedNumberOrderInstance>; + /** + * Create a BulkHostedNumberOrderInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance + */ + create(params: object, headers?: any, callback?: (error: Error | null, item?: BulkHostedNumberOrderInstance) => any): Promise<BulkHostedNumberOrderInstance>; + + /** + * Create a BulkHostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BulkHostedNumberOrderInstance>) => any): Promise<ApiResponse<BulkHostedNumberOrderInstance>>; + /** + * Create a BulkHostedNumberOrderInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkHostedNumberOrderInstance with HTTP metadata + */ + createWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse<BulkHostedNumberOrderInstance>) => any): Promise<ApiResponse<BulkHostedNumberOrderInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BulkHostedNumberOrderListInstance(version: V2): BulkHostedNumberOrderListInstance { + const instance = ((bulkHostingSid, ) => instance.get(bulkHostingSid, )) as BulkHostedNumberOrderListInstance; + + instance.get = function get(bulkHostingSid, ): BulkHostedNumberOrderContext { + return new BulkHostedNumberOrderContextImpl(version, bulkHostingSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/HostedNumber/Orders/Bulk`; + + instance.create = function create(params?: object | ((error: Error | null, items: BulkHostedNumberOrderInstance) => any), headers?: any, callback?: (error: Error | null, items: BulkHostedNumberOrderInstance) => any): Promise<BulkHostedNumberOrderInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BulkHostedNumberOrderInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: object | ((error: Error | null, items: ApiResponse<BulkHostedNumberOrderInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<BulkHostedNumberOrderInstance>) => any): Promise<ApiResponse<BulkHostedNumberOrderInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BulkHostedNumberOrderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BulkHostedNumberOrderInstance> => ({ + ...response, + body: new BulkHostedNumberOrderInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/numbers/v2/bundle.ts b/rest/numbers/v2/bundle.ts new file mode 100644 index 000000000..c5a4ecbdb --- /dev/null +++ b/rest/numbers/v2/bundle.ts @@ -0,0 +1,1197 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { BundleCopyListInstance } from "./bundle/bundleCopy"; +import { EvaluationListInstance } from "./bundle/evaluation"; +import { ItemAssignmentListInstance } from "./bundle/itemAssignment"; +import { ReplaceItemsListInstance } from "./bundle/replaceItems"; + + +export type BundleEndUserType = 'individual'|'business'; + +export type BundleSortBy = 'valid-until'|'date-updated'; + +export type BundleSortDirection = 'ASC'|'DESC'; + +/** + * The verification status of the Bundle resource. + */ +export type BundleStatus = 'draft'|'pending-review'|'in-review'|'twilio-rejected'|'twilio-approved'|'provisionally-approved'; + + + + +/** + * Options to pass to update a BundleInstance + */ +export interface BundleContextUpdateOptions { + /** */ + "status"?: BundleStatus; + /** The URL we call to inform your application of status changes. */ + "statusCallback"?: string; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The email address that will receive updates when the Bundle resource changes status. */ + "email"?: string; +} + +/** + * Options to pass to create a BundleInstance + */ +export interface BundleListInstanceCreateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName": string; + /** The email address that will receive updates when the Bundle resource changes status. */ + "email": string; + /** The URL we call to inform your application of status changes. */ + "statusCallback"?: string; + /** The unique string of a regulation that is associated to the Bundle resource. */ + "regulationSid"?: string; + /** The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle\\\'s phone number country ownership request. */ + "isoCountry"?: string; + /** */ + "endUserType"?: BundleEndUserType; + /** The type of phone number of the Bundle\\\'s ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. */ + "numberType"?: string; + /** Indicates that Bundle is a Test Bundle and will be Auto-Rejected */ + "isTest"?: boolean; +} + +/** + * Options to pass to each + */ +export interface BundleListInstanceEachOptions { + /** The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. */ + "status"?: BundleStatus; + /** A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. */ + "bundleSids"?: string; + /** The string that you assigned to describe the resource. The column can contain 255 variable characters. */ + "friendlyName"?: string; + /** The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. */ + "regulationSid"?: string; + /** The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle\'s phone number country ownership request. */ + "isoCountry"?: string; + /** The type of phone number of the Bundle\'s ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. */ + "numberType"?: string; + /** The end user type of the regulation of the Bundle. Can be `business` or `individual`. */ + "endUserType"?: 'business' | 'individual'; + /** Indicates that the Bundle is a valid Bundle until a specified expiration date. */ + "hasValidUntilDate"?: boolean; + /** Can be `valid-until` or `date-updated`. Defaults to `date-created`. */ + "sortBy"?: BundleSortBy; + /** Default is `DESC`. Can be `ASC` or `DESC`. */ + "sortDirection"?: BundleSortDirection; + /** Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. */ + "validUntilDate"?: Date; + /** Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. */ + "validUntilDateBefore"?: Date; + /** Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. */ + "validUntilDateAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BundleInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BundleListInstanceOptions { + /** The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. */ + "status"?: BundleStatus; + /** A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. */ + "bundleSids"?: string; + /** The string that you assigned to describe the resource. The column can contain 255 variable characters. */ + "friendlyName"?: string; + /** The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. */ + "regulationSid"?: string; + /** The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle\'s phone number country ownership request. */ + "isoCountry"?: string; + /** The type of phone number of the Bundle\'s ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. */ + "numberType"?: string; + /** The end user type of the regulation of the Bundle. Can be `business` or `individual`. */ + "endUserType"?: 'business' | 'individual'; + /** Indicates that the Bundle is a valid Bundle until a specified expiration date. */ + "hasValidUntilDate"?: boolean; + /** Can be `valid-until` or `date-updated`. Defaults to `date-created`. */ + "sortBy"?: BundleSortBy; + /** Default is `DESC`. Can be `ASC` or `DESC`. */ + "sortDirection"?: BundleSortDirection; + /** Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. */ + "validUntilDate"?: Date; + /** Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. */ + "validUntilDateBefore"?: Date; + /** Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. */ + "validUntilDateAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BundleListInstancePageOptions { + /** The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. */ + "status"?: BundleStatus; + /** A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. */ + "bundleSids"?: string; + /** The string that you assigned to describe the resource. The column can contain 255 variable characters. */ + "friendlyName"?: string; + /** The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. */ + "regulationSid"?: string; + /** The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle\'s phone number country ownership request. */ + "isoCountry"?: string; + /** The type of phone number of the Bundle\'s ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. */ + "numberType"?: string; + /** The end user type of the regulation of the Bundle. Can be `business` or `individual`. */ + "endUserType"?: 'business' | 'individual'; + /** Indicates that the Bundle is a valid Bundle until a specified expiration date. */ + "hasValidUntilDate"?: boolean; + /** Can be `valid-until` or `date-updated`. Defaults to `date-created`. */ + "sortBy"?: BundleSortBy; + /** Default is `DESC`. Can be `ASC` or `DESC`. */ + "sortDirection"?: BundleSortDirection; + /** Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. */ + "validUntilDate"?: Date; + /** Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. */ + "validUntilDateBefore"?: Date; + /** Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. */ + "validUntilDateAfter"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface BundleContext { + bundleCopies: BundleCopyListInstance; + evaluations: EvaluationListInstance; + itemAssignments: ItemAssignmentListInstance; + replaceItems: ReplaceItemsListInstance; + + /** + * Remove a BundleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a BundleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a BundleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance + */ + fetch(callback?: (error: Error | null, item?: BundleInstance) => any): Promise<BundleInstance> + + /** + * Fetch a BundleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>> + + /** + * Update a BundleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance + */ + update(callback?: (error: Error | null, item?: BundleInstance) => any): Promise<BundleInstance>; + /** + * Update a BundleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance + */ + update(params: BundleContextUpdateOptions, callback?: (error: Error | null, item?: BundleInstance) => any): Promise<BundleInstance>; + + /** + * Update a BundleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>>; + /** + * Update a BundleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance with HTTP metadata + */ + updateWithHttpInfo(params: BundleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BundleContextSolution { + "sid": string; +} + +export class BundleContextImpl implements BundleContext { + protected _solution: BundleContextSolution; + protected _uri: string; + + protected _bundleCopies?: BundleCopyListInstance; + protected _evaluations?: EvaluationListInstance; + protected _itemAssignments?: ItemAssignmentListInstance; + protected _replaceItems?: ReplaceItemsListInstance; + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/RegulatoryCompliance/Bundles/${sid}`; + } + + get bundleCopies(): BundleCopyListInstance { + this._bundleCopies = this._bundleCopies || BundleCopyListInstance(this._version, this._solution.sid); + return this._bundleCopies; + } + + get evaluations(): EvaluationListInstance { + this._evaluations = this._evaluations || EvaluationListInstance(this._version, this._solution.sid); + return this._evaluations; + } + + get itemAssignments(): ItemAssignmentListInstance { + this._itemAssignments = this._itemAssignments || ItemAssignmentListInstance(this._version, this._solution.sid); + return this._itemAssignments; + } + + get replaceItems(): ReplaceItemsListInstance { + this._replaceItems = this._replaceItems || ReplaceItemsListInstance(this._version, this._solution.sid); + return this._replaceItems; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: BundleInstance) => any): Promise<BundleInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BundleInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<BundleResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<BundleInstance> => ({ + ...response, + body: new BundleInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: BundleContextUpdateOptions | ((error: Error | null, item?: BundleInstance) => any),callback?: (error: Error | null, item?: BundleInstance) => any): Promise<BundleInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BundleInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: BundleContextUpdateOptions | ((error: Error | null, item?: ApiResponse<BundleInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<BundleResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BundleInstance> => ({ + ...response, + body: new BundleInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BundlePayload extends TwilioResponsePayload { + results: BundleResource[]; +} + +interface BundleResource { + sid: string; + account_sid: string; + regulation_sid: string; + friendly_name: string; + status: BundleStatus; + valid_until: Date; + email: string; + status_callback: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class BundleInstance { + protected _solution: BundleContextSolution; + protected _context?: BundleContext; + + constructor(protected _version: V2, payload: BundleResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.regulationSid = (payload.regulation_sid); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.validUntil = deserialize.iso8601DateTime(payload.valid_until); + this.email = (payload.email); + this.statusCallback = (payload.status_callback); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Bundle resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + */ + accountSid: string; + /** + * The unique string of a regulation that is associated to the Bundle resource. + */ + regulationSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + status: BundleStatus; + /** + * The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + */ + validUntil: Date; + /** + * The email address that will receive updates when the Bundle resource changes status. + */ + email: string; + /** + * The URL we call to inform your application of status changes. + */ + statusCallback: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Bundle resource. + */ + url: string; + /** + * The URLs of the Assigned Items of the Bundle resource. + */ + links: Record<string, string>; + + private get _proxy(): BundleContext { + this._context = this._context || new BundleContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a BundleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a BundleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a BundleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance + */ + fetch(callback?: (error: Error | null, item?: BundleInstance) => any): Promise<BundleInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BundleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a BundleInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance + */ + update(callback?: (error: Error | null, item?: BundleInstance) => any): Promise<BundleInstance>; + /** + * Update a BundleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance + */ + update(params: BundleContextUpdateOptions, callback?: (error: Error | null, item?: BundleInstance) => any): Promise<BundleInstance>; + + update(params?: any, callback?: (error: Error | null, item?: BundleInstance) => any): Promise<BundleInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a BundleInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>>; + /** + * Update a BundleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance with HTTP metadata + */ + updateWithHttpInfo(params: BundleContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the bundleCopies. + */ + bundleCopies(): BundleCopyListInstance { + return this._proxy.bundleCopies; + } + + /** + * Access the evaluations. + */ + evaluations(): EvaluationListInstance { + return this._proxy.evaluations; + } + + /** + * Access the itemAssignments. + */ + itemAssignments(): ItemAssignmentListInstance { + return this._proxy.itemAssignments; + } + + /** + * Access the replaceItems. + */ + replaceItems(): ReplaceItemsListInstance { + return this._proxy.replaceItems; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + regulationSid: this.regulationSid, + friendlyName: this.friendlyName, + status: this.status, + validUntil: this.validUntil, + email: this.email, + statusCallback: this.statusCallback, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BundleSolution { +} + +export interface BundleListInstance { + _version: V2; + _solution: BundleSolution; + _uri: string; + + (sid: string, ): BundleContext; + get(sid: string, ): BundleContext; + + + + + + + + + /** + * Create a BundleInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance + */ + create(params: BundleListInstanceCreateOptions, callback?: (error: Error | null, item?: BundleInstance) => any): Promise<BundleInstance>; + + /** + * Create a BundleInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleInstance with HTTP metadata + */ + createWithHttpInfo(params: BundleListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>>; + + + + + /** + * Streams BundleInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BundleInstance, done: (err?: Error) => void) => void): void; + each(params: BundleListInstanceEachOptions, callback?: (item: BundleInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BundleInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BundleInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BundleListInstanceEachOptions, callback?: (item: BundleInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BundleInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BundlePage) => any): Promise<BundlePage>; + /** + * Retrieve a single target page of BundleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<BundlePage>) => any): Promise<ApiResponse<BundlePage>>; + /** + * Lists BundleInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BundleInstance[]) => any): Promise<BundleInstance[]>; + list(params: BundleListInstanceOptions, callback?: (error: Error | null, items: BundleInstance[]) => any): Promise<BundleInstance[]>; + /** + * Lists BundleInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BundleInstance[]>) => any): Promise<ApiResponse<BundleInstance[]>>; + listWithHttpInfo(params: BundleListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<BundleInstance[]>) => any): Promise<ApiResponse<BundleInstance[]>>; + /** + * Retrieve a single page of BundleInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BundlePage) => any): Promise<BundlePage>; + page(params: BundleListInstancePageOptions, callback?: (error: Error | null, items: BundlePage) => any): Promise<BundlePage>; + /** + * Retrieve a single page of BundleInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BundlePage>) => any): Promise<ApiResponse<BundlePage>>; + pageWithHttpInfo(params: BundleListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<BundlePage>) => any): Promise<ApiResponse<BundlePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BundleListInstance(version: V2): BundleListInstance { + const instance = ((sid, ) => instance.get(sid, )) as BundleListInstance; + + instance.get = function get(sid, ): BundleContext { + return new BundleContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/RegulatoryCompliance/Bundles`; + + instance.create = function create(params: BundleListInstanceCreateOptions, callback?: (error: Error | null, items: BundleInstance) => any): Promise<BundleInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Email"] = params["email"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["regulationSid"] !== undefined) + data["RegulationSid"] = params["regulationSid"]; + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["endUserType"] !== undefined) + data["EndUserType"] = params["endUserType"]; + if (params["numberType"] !== undefined) + data["NumberType"] = params["numberType"]; + if (params["isTest"] !== undefined) + data["IsTest"] = serialize.bool(params["isTest"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BundleInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: BundleListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<BundleInstance>) => any): Promise<ApiResponse<BundleInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Email"] = params["email"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["regulationSid"] !== undefined) + data["RegulationSid"] = params["regulationSid"]; + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["endUserType"] !== undefined) + data["EndUserType"] = params["endUserType"]; + if (params["numberType"] !== undefined) + data["NumberType"] = params["numberType"]; + if (params["isTest"] !== undefined) + data["IsTest"] = serialize.bool(params["isTest"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BundleResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BundleInstance> => ({ + ...response, + body: new BundleInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: BundleListInstancePageOptions | ((error: Error | null, items: BundlePage) => any), callback?: (error: Error | null, items: BundlePage) => any): Promise<BundlePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["bundleSids"] !== undefined) + data["BundleSids"] = params["bundleSids"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["regulationSid"] !== undefined) + data["RegulationSid"] = params["regulationSid"]; + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["numberType"] !== undefined) + data["NumberType"] = params["numberType"]; + if (params["endUserType"] !== undefined) + data["EndUserType"] = params["endUserType"]; + if (params["hasValidUntilDate"] !== undefined) + data["HasValidUntilDate"] = serialize.bool(params["hasValidUntilDate"]); + if (params["sortBy"] !== undefined) + data["SortBy"] = params["sortBy"]; + if (params["sortDirection"] !== undefined) + data["SortDirection"] = params["sortDirection"]; + if (params["validUntilDate"] !== undefined) + data["ValidUntilDate"] = serialize.iso8601DateTime(params["validUntilDate"]); + if (params["validUntilDateBefore"] !== undefined) + data["ValidUntilDate<"] = serialize.iso8601DateTime(params["validUntilDateBefore"]); + if (params["validUntilDateAfter"] !== undefined) + data["ValidUntilDate>"] = serialize.iso8601DateTime(params["validUntilDateAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BundlePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BundlePage) => any): Promise<BundlePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BundlePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BundleListInstancePageOptions | ((error: Error | null, items: ApiResponse<BundlePage>) => any), callback?: (error: Error | null, items: ApiResponse<BundlePage>) => any): Promise<ApiResponse<BundlePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["bundleSids"] !== undefined) + data["BundleSids"] = params["bundleSids"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["regulationSid"] !== undefined) + data["RegulationSid"] = params["regulationSid"]; + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["numberType"] !== undefined) + data["NumberType"] = params["numberType"]; + if (params["endUserType"] !== undefined) + data["EndUserType"] = params["endUserType"]; + if (params["hasValidUntilDate"] !== undefined) + data["HasValidUntilDate"] = serialize.bool(params["hasValidUntilDate"]); + if (params["sortBy"] !== undefined) + data["SortBy"] = params["sortBy"]; + if (params["sortDirection"] !== undefined) + data["SortDirection"] = params["sortDirection"]; + if (params["validUntilDate"] !== undefined) + data["ValidUntilDate"] = serialize.iso8601DateTime(params["validUntilDate"]); + if (params["validUntilDateBefore"] !== undefined) + data["ValidUntilDate<"] = serialize.iso8601DateTime(params["validUntilDateBefore"]); + if (params["validUntilDateAfter"] !== undefined) + data["ValidUntilDate>"] = serialize.iso8601DateTime(params["validUntilDateAfter"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<BundlePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BundlePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<BundlePage>) => any): Promise<ApiResponse<BundlePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<BundlePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BundlePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class BundlePage extends Page<V2, BundlePayload, BundleResource, BundleInstance> { +/** +* Initialize the BundlePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: BundleSolution) { + super(version, response, solution); + } + + /** + * Build an instance of BundleInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BundleResource): BundleInstance { + + return new BundleInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/bundle/bundleCopy.ts b/rest/numbers/v2/bundle/bundleCopy.ts new file mode 100644 index 000000000..2d37b563d --- /dev/null +++ b/rest/numbers/v2/bundle/bundleCopy.ts @@ -0,0 +1,562 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The verification status of the Bundle resource. + */ +export type BundleCopyStatus = 'draft'|'pending-review'|'in-review'|'twilio-rejected'|'twilio-approved'|'provisionally-approved'; + + +/** + * Options to pass to create a BundleCopyInstance + */ +export interface BundleCopyListInstanceCreateOptions { + /** The string that you assigned to describe the copied bundle. */ + "friendlyName"?: string; +} + +/** + * Options to pass to each + */ +export interface BundleCopyListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BundleCopyInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BundleCopyListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BundleCopyListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface BundleCopySolution { + bundleSid: string; +} + +export interface BundleCopyListInstance { + _version: V2; + _solution: BundleCopySolution; + _uri: string; + + + + /** + * Create a BundleCopyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleCopyInstance + */ + create(callback?: (error: Error | null, item?: BundleCopyInstance) => any): Promise<BundleCopyInstance>; + /** + * Create a BundleCopyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleCopyInstance + */ + create(params: BundleCopyListInstanceCreateOptions, callback?: (error: Error | null, item?: BundleCopyInstance) => any): Promise<BundleCopyInstance>; + + /** + * Create a BundleCopyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleCopyInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BundleCopyInstance>) => any): Promise<ApiResponse<BundleCopyInstance>>; + /** + * Create a BundleCopyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleCopyInstance with HTTP metadata + */ + createWithHttpInfo(params: BundleCopyListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<BundleCopyInstance>) => any): Promise<ApiResponse<BundleCopyInstance>>; + + + + + /** + * Streams BundleCopyInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleCopyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BundleCopyInstance, done: (err?: Error) => void) => void): void; + each(params: BundleCopyListInstanceEachOptions, callback?: (item: BundleCopyInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BundleCopyInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleCopyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BundleCopyInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BundleCopyListInstanceEachOptions, callback?: (item: BundleCopyInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BundleCopyInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BundleCopyPage) => any): Promise<BundleCopyPage>; + /** + * Retrieve a single target page of BundleCopyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<BundleCopyPage>) => any): Promise<ApiResponse<BundleCopyPage>>; + /** + * Lists BundleCopyInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleCopyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BundleCopyInstance[]) => any): Promise<BundleCopyInstance[]>; + list(params: BundleCopyListInstanceOptions, callback?: (error: Error | null, items: BundleCopyInstance[]) => any): Promise<BundleCopyInstance[]>; + /** + * Lists BundleCopyInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleCopyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BundleCopyInstance[]>) => any): Promise<ApiResponse<BundleCopyInstance[]>>; + listWithHttpInfo(params: BundleCopyListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<BundleCopyInstance[]>) => any): Promise<ApiResponse<BundleCopyInstance[]>>; + /** + * Retrieve a single page of BundleCopyInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleCopyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BundleCopyPage) => any): Promise<BundleCopyPage>; + page(params: BundleCopyListInstancePageOptions, callback?: (error: Error | null, items: BundleCopyPage) => any): Promise<BundleCopyPage>; + /** + * Retrieve a single page of BundleCopyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BundleCopyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BundleCopyPage>) => any): Promise<ApiResponse<BundleCopyPage>>; + pageWithHttpInfo(params: BundleCopyListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<BundleCopyPage>) => any): Promise<ApiResponse<BundleCopyPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BundleCopyListInstance(version: V2, bundleSid: string): BundleCopyListInstance { + if (!isValidPathParam(bundleSid)) { + throw new Error('Parameter \'bundleSid\' is not valid.'); + } + + const instance = {} as BundleCopyListInstance; + + instance._version = version; + instance._solution = { bundleSid, }; + instance._uri = `/RegulatoryCompliance/Bundles/${bundleSid}/Copies`; + + instance.create = function create(params?: BundleCopyListInstanceCreateOptions | ((error: Error | null, items: BundleCopyInstance) => any), callback?: (error: Error | null, items: BundleCopyInstance) => any): Promise<BundleCopyInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BundleCopyInstance(operationVersion, payload, instance._solution.bundleSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: BundleCopyListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<BundleCopyInstance>) => any), callback?: (error: Error | null, items: ApiResponse<BundleCopyInstance>) => any): Promise<ApiResponse<BundleCopyInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BundleCopyResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BundleCopyInstance> => ({ + ...response, + body: new BundleCopyInstance(operationVersion, response.body, instance._solution.bundleSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: BundleCopyListInstancePageOptions | ((error: Error | null, items: BundleCopyPage) => any), callback?: (error: Error | null, items: BundleCopyPage) => any): Promise<BundleCopyPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BundleCopyPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BundleCopyPage) => any): Promise<BundleCopyPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BundleCopyPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BundleCopyListInstancePageOptions | ((error: Error | null, items: ApiResponse<BundleCopyPage>) => any), callback?: (error: Error | null, items: ApiResponse<BundleCopyPage>) => any): Promise<ApiResponse<BundleCopyPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<BundleCopyPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BundleCopyPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<BundleCopyPage>) => any): Promise<ApiResponse<BundleCopyPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<BundleCopyPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BundleCopyPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface BundleCopyPayload extends TwilioResponsePayload { + results: BundleCopyResource[]; +} + +interface BundleCopyResource { + sid: string; + account_sid: string; + regulation_sid: string; + friendly_name: string; + status: BundleCopyStatus; + valid_until: Date; + email: string; + status_callback: string; + date_created: Date; + date_updated: Date; +} + +export class BundleCopyInstance { + + constructor(protected _version: V2, payload: BundleCopyResource, bundleSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.regulationSid = (payload.regulation_sid); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.validUntil = deserialize.iso8601DateTime(payload.valid_until); + this.email = (payload.email); + this.statusCallback = (payload.status_callback); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The unique string that we created to identify the Bundle resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + */ + accountSid: string; + /** + * The unique string of a regulation that is associated to the Bundle resource. + */ + regulationSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + status: BundleCopyStatus; + /** + * The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + */ + validUntil: Date; + /** + * The email address that will receive updates when the Bundle resource changes status. + */ + email: string; + /** + * The URL we call to inform your application of status changes. + */ + statusCallback: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + regulationSid: this.regulationSid, + friendlyName: this.friendlyName, + status: this.status, + validUntil: this.validUntil, + email: this.email, + statusCallback: this.statusCallback, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class BundleCopyPage extends Page<V2, BundleCopyPayload, BundleCopyResource, BundleCopyInstance> { +/** +* Initialize the BundleCopyPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: BundleCopySolution) { + super(version, response, solution); + } + + /** + * Build an instance of BundleCopyInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BundleCopyResource): BundleCopyInstance { + + return new BundleCopyInstance( + this._version, + payload, + this._solution.bundleSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/bundle/evaluation.ts b/rest/numbers/v2/bundle/evaluation.ts new file mode 100644 index 000000000..5863760c4 --- /dev/null +++ b/rest/numbers/v2/bundle/evaluation.ts @@ -0,0 +1,626 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The compliance status of the Evaluation resource. + */ +export type EvaluationStatus = 'compliant'|'noncompliant'; + + + + +/** + * Options to pass to each + */ +export interface EvaluationListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EvaluationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EvaluationListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EvaluationListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EvaluationContext { + + /** + * Fetch a EvaluationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EvaluationInstance + */ + fetch(callback?: (error: Error | null, item?: EvaluationInstance) => any): Promise<EvaluationInstance> + + /** + * Fetch a EvaluationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EvaluationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EvaluationInstance>) => any): Promise<ApiResponse<EvaluationInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EvaluationContextSolution { + "bundleSid": string; + "sid": string; +} + +export class EvaluationContextImpl implements EvaluationContext { + protected _solution: EvaluationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, bundleSid: string, sid: string) { + if (!isValidPathParam(bundleSid)) { + throw new Error('Parameter \'bundleSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { bundleSid, sid, }; + this._uri = `/RegulatoryCompliance/Bundles/${bundleSid}/Evaluations/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: EvaluationInstance) => any): Promise<EvaluationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EvaluationInstance(operationVersion, payload, instance._solution.bundleSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EvaluationInstance>) => any): Promise<ApiResponse<EvaluationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EvaluationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EvaluationInstance> => ({ + ...response, + body: new EvaluationInstance(operationVersion, response.body, instance._solution.bundleSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EvaluationPayload extends TwilioResponsePayload { + results: EvaluationResource[]; +} + +interface EvaluationResource { + sid: string; + account_sid: string; + regulation_sid: string; + bundle_sid: string; + status: EvaluationStatus; + results: Array<any>; + date_created: Date; + url: string; +} + +export class EvaluationInstance { + protected _solution: EvaluationContextSolution; + protected _context?: EvaluationContext; + + constructor(protected _version: V2, payload: EvaluationResource, bundleSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.regulationSid = (payload.regulation_sid); + this.bundleSid = (payload.bundle_sid); + this.status = payload.status; + this.results = (payload.results); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { bundleSid, sid: sid, }; + } + + /** + * The unique string that identifies the Evaluation resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + */ + accountSid: string; + /** + * The unique string of a regulation that is associated to the Bundle resource. + */ + regulationSid: string; + /** + * The unique string that we created to identify the Bundle resource. + */ + bundleSid: string; + status: EvaluationStatus; + /** + * The results of the Evaluation which includes the valid and invalid attributes. + */ + results: Array<any>; + dateCreated: Date; + url: string; + + private get _proxy(): EvaluationContext { + this._context = this._context || new EvaluationContextImpl(this._version, this._solution.bundleSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a EvaluationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EvaluationInstance + */ + fetch(callback?: (error: Error | null, item?: EvaluationInstance) => any): Promise<EvaluationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EvaluationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EvaluationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EvaluationInstance>) => any): Promise<ApiResponse<EvaluationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + regulationSid: this.regulationSid, + bundleSid: this.bundleSid, + status: this.status, + results: this.results, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EvaluationSolution { + bundleSid: string; +} + +export interface EvaluationListInstance { + _version: V2; + _solution: EvaluationSolution; + _uri: string; + + (sid: string, ): EvaluationContext; + get(sid: string, ): EvaluationContext; + + + + + /** + * Create a EvaluationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EvaluationInstance + */ + create(callback?: (error: Error | null, item?: EvaluationInstance) => any): Promise<EvaluationInstance> + + /** + * Create a EvaluationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EvaluationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EvaluationInstance>) => any): Promise<ApiResponse<EvaluationInstance>> + + + + + /** + * Streams EvaluationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EvaluationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EvaluationInstance, done: (err?: Error) => void) => void): void; + each(params: EvaluationListInstanceEachOptions, callback?: (item: EvaluationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EvaluationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EvaluationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EvaluationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EvaluationListInstanceEachOptions, callback?: (item: EvaluationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EvaluationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EvaluationPage) => any): Promise<EvaluationPage>; + /** + * Retrieve a single target page of EvaluationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EvaluationPage>) => any): Promise<ApiResponse<EvaluationPage>>; + /** + * Lists EvaluationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EvaluationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EvaluationInstance[]) => any): Promise<EvaluationInstance[]>; + list(params: EvaluationListInstanceOptions, callback?: (error: Error | null, items: EvaluationInstance[]) => any): Promise<EvaluationInstance[]>; + /** + * Lists EvaluationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EvaluationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EvaluationInstance[]>) => any): Promise<ApiResponse<EvaluationInstance[]>>; + listWithHttpInfo(params: EvaluationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EvaluationInstance[]>) => any): Promise<ApiResponse<EvaluationInstance[]>>; + /** + * Retrieve a single page of EvaluationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EvaluationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EvaluationPage) => any): Promise<EvaluationPage>; + page(params: EvaluationListInstancePageOptions, callback?: (error: Error | null, items: EvaluationPage) => any): Promise<EvaluationPage>; + /** + * Retrieve a single page of EvaluationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EvaluationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EvaluationPage>) => any): Promise<ApiResponse<EvaluationPage>>; + pageWithHttpInfo(params: EvaluationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EvaluationPage>) => any): Promise<ApiResponse<EvaluationPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EvaluationListInstance(version: V2, bundleSid: string): EvaluationListInstance { + if (!isValidPathParam(bundleSid)) { + throw new Error('Parameter \'bundleSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as EvaluationListInstance; + + instance.get = function get(sid, ): EvaluationContext { + return new EvaluationContextImpl(version, bundleSid, sid); + } + + instance._version = version; + instance._solution = { bundleSid, }; + instance._uri = `/RegulatoryCompliance/Bundles/${bundleSid}/Evaluations`; + + instance.create = function create( callback?: (error: Error | null, items: EvaluationInstance) => any): Promise<EvaluationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new EvaluationInstance(operationVersion, payload, instance._solution.bundleSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<EvaluationInstance>) => any): Promise<ApiResponse<EvaluationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<EvaluationResource>({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse<EvaluationInstance> => ({ + ...response, + body: new EvaluationInstance(operationVersion, response.body, instance._solution.bundleSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: EvaluationListInstancePageOptions | ((error: Error | null, items: EvaluationPage) => any), callback?: (error: Error | null, items: EvaluationPage) => any): Promise<EvaluationPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EvaluationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EvaluationPage) => any): Promise<EvaluationPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EvaluationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EvaluationListInstancePageOptions | ((error: Error | null, items: ApiResponse<EvaluationPage>) => any), callback?: (error: Error | null, items: ApiResponse<EvaluationPage>) => any): Promise<ApiResponse<EvaluationPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EvaluationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EvaluationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EvaluationPage>) => any): Promise<ApiResponse<EvaluationPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EvaluationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EvaluationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EvaluationPage extends Page<V2, EvaluationPayload, EvaluationResource, EvaluationInstance> { +/** +* Initialize the EvaluationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: EvaluationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EvaluationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EvaluationResource): EvaluationInstance { + + return new EvaluationInstance( + this._version, + payload, + this._solution.bundleSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/bundle/itemAssignment.ts b/rest/numbers/v2/bundle/itemAssignment.ts new file mode 100644 index 000000000..722e09766 --- /dev/null +++ b/rest/numbers/v2/bundle/itemAssignment.ts @@ -0,0 +1,739 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a ItemAssignmentInstance + */ +export interface ItemAssignmentListInstanceCreateOptions { + /** The SID of an object bag that holds information of the different items. */ + "objectSid": string; +} + +/** + * Options to pass to each + */ +export interface ItemAssignmentListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ItemAssignmentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ItemAssignmentListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ItemAssignmentListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ItemAssignmentContext { + + /** + * Remove a ItemAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ItemAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ItemAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ItemAssignmentInstance + */ + fetch(callback?: (error: Error | null, item?: ItemAssignmentInstance) => any): Promise<ItemAssignmentInstance> + + /** + * Fetch a ItemAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ItemAssignmentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ItemAssignmentInstance>) => any): Promise<ApiResponse<ItemAssignmentInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ItemAssignmentContextSolution { + "bundleSid": string; + "sid": string; +} + +export class ItemAssignmentContextImpl implements ItemAssignmentContext { + protected _solution: ItemAssignmentContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, bundleSid: string, sid: string) { + if (!isValidPathParam(bundleSid)) { + throw new Error('Parameter \'bundleSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { bundleSid, sid, }; + this._uri = `/RegulatoryCompliance/Bundles/${bundleSid}/ItemAssignments/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ItemAssignmentInstance) => any): Promise<ItemAssignmentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ItemAssignmentInstance(operationVersion, payload, instance._solution.bundleSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ItemAssignmentInstance>) => any): Promise<ApiResponse<ItemAssignmentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ItemAssignmentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ItemAssignmentInstance> => ({ + ...response, + body: new ItemAssignmentInstance(operationVersion, response.body, instance._solution.bundleSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ItemAssignmentPayload extends TwilioResponsePayload { + results: ItemAssignmentResource[]; +} + +interface ItemAssignmentResource { + sid: string; + bundle_sid: string; + account_sid: string; + object_sid: string; + date_created: Date; + url: string; +} + +export class ItemAssignmentInstance { + protected _solution: ItemAssignmentContextSolution; + protected _context?: ItemAssignmentContext; + + constructor(protected _version: V2, payload: ItemAssignmentResource, bundleSid: string, sid?: string) { + + this.sid = (payload.sid); + this.bundleSid = (payload.bundle_sid); + this.accountSid = (payload.account_sid); + this.objectSid = (payload.object_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { bundleSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Item Assignment resource. + */ + sid: string; + /** + * The unique string that we created to identify the Bundle resource. + */ + bundleSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + */ + accountSid: string; + /** + * The SID of an object bag that holds information of the different items. + */ + objectSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Identity resource. + */ + url: string; + + private get _proxy(): ItemAssignmentContext { + this._context = this._context || new ItemAssignmentContextImpl(this._version, this._solution.bundleSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ItemAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ItemAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ItemAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ItemAssignmentInstance + */ + fetch(callback?: (error: Error | null, item?: ItemAssignmentInstance) => any): Promise<ItemAssignmentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ItemAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ItemAssignmentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ItemAssignmentInstance>) => any): Promise<ApiResponse<ItemAssignmentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + bundleSid: this.bundleSid, + accountSid: this.accountSid, + objectSid: this.objectSid, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ItemAssignmentSolution { + bundleSid: string; +} + +export interface ItemAssignmentListInstance { + _version: V2; + _solution: ItemAssignmentSolution; + _uri: string; + + (sid: string, ): ItemAssignmentContext; + get(sid: string, ): ItemAssignmentContext; + + + + + + + /** + * Create a ItemAssignmentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ItemAssignmentInstance + */ + create(params: ItemAssignmentListInstanceCreateOptions, callback?: (error: Error | null, item?: ItemAssignmentInstance) => any): Promise<ItemAssignmentInstance>; + + /** + * Create a ItemAssignmentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ItemAssignmentInstance with HTTP metadata + */ + createWithHttpInfo(params: ItemAssignmentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ItemAssignmentInstance>) => any): Promise<ApiResponse<ItemAssignmentInstance>>; + + + + + /** + * Streams ItemAssignmentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ItemAssignmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ItemAssignmentInstance, done: (err?: Error) => void) => void): void; + each(params: ItemAssignmentListInstanceEachOptions, callback?: (item: ItemAssignmentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ItemAssignmentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ItemAssignmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ItemAssignmentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ItemAssignmentListInstanceEachOptions, callback?: (item: ItemAssignmentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ItemAssignmentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ItemAssignmentPage) => any): Promise<ItemAssignmentPage>; + /** + * Retrieve a single target page of ItemAssignmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ItemAssignmentPage>) => any): Promise<ApiResponse<ItemAssignmentPage>>; + /** + * Lists ItemAssignmentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ItemAssignmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ItemAssignmentInstance[]) => any): Promise<ItemAssignmentInstance[]>; + list(params: ItemAssignmentListInstanceOptions, callback?: (error: Error | null, items: ItemAssignmentInstance[]) => any): Promise<ItemAssignmentInstance[]>; + /** + * Lists ItemAssignmentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ItemAssignmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ItemAssignmentInstance[]>) => any): Promise<ApiResponse<ItemAssignmentInstance[]>>; + listWithHttpInfo(params: ItemAssignmentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ItemAssignmentInstance[]>) => any): Promise<ApiResponse<ItemAssignmentInstance[]>>; + /** + * Retrieve a single page of ItemAssignmentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ItemAssignmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ItemAssignmentPage) => any): Promise<ItemAssignmentPage>; + page(params: ItemAssignmentListInstancePageOptions, callback?: (error: Error | null, items: ItemAssignmentPage) => any): Promise<ItemAssignmentPage>; + /** + * Retrieve a single page of ItemAssignmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ItemAssignmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ItemAssignmentPage>) => any): Promise<ApiResponse<ItemAssignmentPage>>; + pageWithHttpInfo(params: ItemAssignmentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ItemAssignmentPage>) => any): Promise<ApiResponse<ItemAssignmentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ItemAssignmentListInstance(version: V2, bundleSid: string): ItemAssignmentListInstance { + if (!isValidPathParam(bundleSid)) { + throw new Error('Parameter \'bundleSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ItemAssignmentListInstance; + + instance.get = function get(sid, ): ItemAssignmentContext { + return new ItemAssignmentContextImpl(version, bundleSid, sid); + } + + instance._version = version; + instance._solution = { bundleSid, }; + instance._uri = `/RegulatoryCompliance/Bundles/${bundleSid}/ItemAssignments`; + + instance.create = function create(params: ItemAssignmentListInstanceCreateOptions, callback?: (error: Error | null, items: ItemAssignmentInstance) => any): Promise<ItemAssignmentInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["objectSid"] === null || params["objectSid"] === undefined) { + throw new Error('Required parameter "params[\'objectSid\']" missing.'); + } + + let data: any = {}; + + + + data["ObjectSid"] = params["objectSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ItemAssignmentInstance(operationVersion, payload, instance._solution.bundleSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ItemAssignmentListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ItemAssignmentInstance>) => any): Promise<ApiResponse<ItemAssignmentInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["objectSid"] === null || params["objectSid"] === undefined) { + throw new Error('Required parameter "params[\'objectSid\']" missing.'); + } + + let data: any = {}; + + + + data["ObjectSid"] = params["objectSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ItemAssignmentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ItemAssignmentInstance> => ({ + ...response, + body: new ItemAssignmentInstance(operationVersion, response.body, instance._solution.bundleSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ItemAssignmentListInstancePageOptions | ((error: Error | null, items: ItemAssignmentPage) => any), callback?: (error: Error | null, items: ItemAssignmentPage) => any): Promise<ItemAssignmentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ItemAssignmentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ItemAssignmentPage) => any): Promise<ItemAssignmentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ItemAssignmentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ItemAssignmentListInstancePageOptions | ((error: Error | null, items: ApiResponse<ItemAssignmentPage>) => any), callback?: (error: Error | null, items: ApiResponse<ItemAssignmentPage>) => any): Promise<ApiResponse<ItemAssignmentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ItemAssignmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ItemAssignmentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ItemAssignmentPage>) => any): Promise<ApiResponse<ItemAssignmentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ItemAssignmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ItemAssignmentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ItemAssignmentPage extends Page<V2, ItemAssignmentPayload, ItemAssignmentResource, ItemAssignmentInstance> { +/** +* Initialize the ItemAssignmentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: ItemAssignmentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ItemAssignmentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ItemAssignmentResource): ItemAssignmentInstance { + + return new ItemAssignmentInstance( + this._version, + payload, + this._solution.bundleSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/bundle/replaceItems.ts b/rest/numbers/v2/bundle/replaceItems.ts new file mode 100644 index 000000000..6069fa436 --- /dev/null +++ b/rest/numbers/v2/bundle/replaceItems.ts @@ -0,0 +1,265 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The verification status of the Bundle resource. + */ +export type ReplaceItemsStatus = 'draft'|'pending-review'|'in-review'|'twilio-rejected'|'twilio-approved'|'provisionally-approved'; + + +/** + * Options to pass to create a ReplaceItemsInstance + */ +export interface ReplaceItemsListInstanceCreateOptions { + /** The source bundle sid to copy the item assignments from. */ + "fromBundleSid": string; +} + + +export interface ReplaceItemsSolution { + bundleSid: string; +} + +export interface ReplaceItemsListInstance { + _version: V2; + _solution: ReplaceItemsSolution; + _uri: string; + + + + /** + * Create a ReplaceItemsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReplaceItemsInstance + */ + create(params: ReplaceItemsListInstanceCreateOptions, callback?: (error: Error | null, item?: ReplaceItemsInstance) => any): Promise<ReplaceItemsInstance>; + + /** + * Create a ReplaceItemsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReplaceItemsInstance with HTTP metadata + */ + createWithHttpInfo(params: ReplaceItemsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ReplaceItemsInstance>) => any): Promise<ApiResponse<ReplaceItemsInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ReplaceItemsListInstance(version: V2, bundleSid: string): ReplaceItemsListInstance { + if (!isValidPathParam(bundleSid)) { + throw new Error('Parameter \'bundleSid\' is not valid.'); + } + + const instance = {} as ReplaceItemsListInstance; + + instance._version = version; + instance._solution = { bundleSid, }; + instance._uri = `/RegulatoryCompliance/Bundles/${bundleSid}/ReplaceItems`; + + instance.create = function create(params: ReplaceItemsListInstanceCreateOptions, callback?: (error: Error | null, items: ReplaceItemsInstance) => any): Promise<ReplaceItemsInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["fromBundleSid"] === null || params["fromBundleSid"] === undefined) { + throw new Error('Required parameter "params[\'fromBundleSid\']" missing.'); + } + + let data: any = {}; + + + + data["FromBundleSid"] = params["fromBundleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ReplaceItemsInstance(operationVersion, payload, instance._solution.bundleSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ReplaceItemsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ReplaceItemsInstance>) => any): Promise<ApiResponse<ReplaceItemsInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["fromBundleSid"] === null || params["fromBundleSid"] === undefined) { + throw new Error('Required parameter "params[\'fromBundleSid\']" missing.'); + } + + let data: any = {}; + + + + data["FromBundleSid"] = params["fromBundleSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ReplaceItemsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ReplaceItemsInstance> => ({ + ...response, + body: new ReplaceItemsInstance(operationVersion, response.body, instance._solution.bundleSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ReplaceItemsPayload extends ReplaceItemsResource {} + +interface ReplaceItemsResource { + sid: string; + account_sid: string; + regulation_sid: string; + friendly_name: string; + status: ReplaceItemsStatus; + valid_until: Date; + email: string; + status_callback: string; + date_created: Date; + date_updated: Date; +} + +export class ReplaceItemsInstance { + + constructor(protected _version: V2, payload: ReplaceItemsResource, bundleSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.regulationSid = (payload.regulation_sid); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.validUntil = deserialize.iso8601DateTime(payload.valid_until); + this.email = (payload.email); + this.statusCallback = (payload.status_callback); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The unique string that we created to identify the Bundle resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + */ + accountSid: string; + /** + * The unique string of a regulation that is associated to the Bundle resource. + */ + regulationSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + status: ReplaceItemsStatus; + /** + * The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + */ + validUntil: Date; + /** + * The email address that will receive updates when the Bundle resource changes status. + */ + email: string; + /** + * The URL we call to inform your application of status changes. + */ + statusCallback: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + regulationSid: this.regulationSid, + friendlyName: this.friendlyName, + status: this.status, + validUntil: this.validUntil, + email: this.email, + statusCallback: this.statusCallback, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/numbers/v2/bundleClone.ts b/rest/numbers/v2/bundleClone.ts new file mode 100644 index 000000000..0ed3595ad --- /dev/null +++ b/rest/numbers/v2/bundleClone.ts @@ -0,0 +1,367 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The verification status of the Bundle resource. + */ +export type BundleCloneStatus = 'draft'|'pending-review'|'in-review'|'twilio-rejected'|'twilio-approved'|'provisionally-approved'; + + +/** + * Options to pass to create a BundleCloneInstance + */ +export interface BundleCloneContextCreateOptions { + /** The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. */ + "targetAccountSid": string; + /** If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved */ + "moveToDraft"?: boolean; + /** The string that you assigned to describe the cloned bundle. */ + "friendlyName"?: string; +} + +export interface BundleCloneContext { + + /** + * Create a BundleCloneInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleCloneInstance + */ + create(params: BundleCloneContextCreateOptions, callback?: (error: Error | null, item?: BundleCloneInstance) => any): Promise<BundleCloneInstance>; + + /** + * Create a BundleCloneInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleCloneInstance with HTTP metadata + */ + createWithHttpInfo(params: BundleCloneContextCreateOptions, callback?: (error: Error | null, item?: ApiResponse<BundleCloneInstance>) => any): Promise<ApiResponse<BundleCloneInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BundleCloneContextSolution { + "bundleSid": string; +} + +export class BundleCloneContextImpl implements BundleCloneContext { + protected _solution: BundleCloneContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, bundleSid: string) { + if (!isValidPathParam(bundleSid)) { + throw new Error('Parameter \'bundleSid\' is not valid.'); + } + + this._solution = { bundleSid, }; + this._uri = `/RegulatoryCompliance/Bundles/${bundleSid}/Clones`; + } + + create(params: BundleCloneContextCreateOptions,callback?: (error: Error | null, item?: BundleCloneInstance) => any): Promise<BundleCloneInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["targetAccountSid"] === null || params["targetAccountSid"] === undefined) { + throw new Error('Required parameter "params[\'targetAccountSid\']" missing.'); + } + + let data: any = {}; + + + + data["TargetAccountSid"] = params["targetAccountSid"]; + if (params["moveToDraft"] !== undefined) + data["MoveToDraft"] = serialize.bool(params["moveToDraft"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BundleCloneInstance(operationVersion, payload, instance._solution.bundleSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params: BundleCloneContextCreateOptions,callback?: (error: Error | null, item?: ApiResponse<BundleCloneInstance>) => any): Promise<ApiResponse<BundleCloneInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["targetAccountSid"] === null || params["targetAccountSid"] === undefined) { + throw new Error('Required parameter "params[\'targetAccountSid\']" missing.'); + } + + let data: any = {}; + + + + data["TargetAccountSid"] = params["targetAccountSid"]; + if (params["moveToDraft"] !== undefined) + data["MoveToDraft"] = serialize.bool(params["moveToDraft"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BundleCloneResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BundleCloneInstance> => ({ + ...response, + body: new BundleCloneInstance(operationVersion, response.body, instance._solution.bundleSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BundleClonePayload extends BundleCloneResource {} + +interface BundleCloneResource { + bundle_sid: string; + account_sid: string; + regulation_sid: string; + friendly_name: string; + status: BundleCloneStatus; + valid_until: Date; + email: string; + status_callback: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class BundleCloneInstance { + protected _solution: BundleCloneContextSolution; + protected _context?: BundleCloneContext; + + constructor(protected _version: V2, payload: BundleCloneResource, bundleSid?: string) { + + this.bundleSid = (payload.bundle_sid); + this.accountSid = (payload.account_sid); + this.regulationSid = (payload.regulation_sid); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.validUntil = deserialize.iso8601DateTime(payload.valid_until); + this.email = (payload.email); + this.statusCallback = (payload.status_callback); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { bundleSid: bundleSid, }; + } + + /** + * The unique string that we created to identify the Bundle resource. + */ + bundleSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + */ + accountSid: string; + /** + * The unique string of a regulation that is associated to the Bundle resource. + */ + regulationSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + status: BundleCloneStatus; + /** + * The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + */ + validUntil: Date; + /** + * The email address that will receive updates when the Bundle resource changes status. + */ + email: string; + /** + * The URL we call to inform your application of status changes. + */ + statusCallback: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): BundleCloneContext { + this._context = this._context || new BundleCloneContextImpl(this._version, this._solution.bundleSid); + return this._context; + } + + /** + * Create a BundleCloneInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleCloneInstance + */ + create(params: BundleCloneContextCreateOptions, callback?: (error: Error | null, item?: BundleCloneInstance) => any): Promise<BundleCloneInstance>; + + create(params?: any, callback?: (error: Error | null, item?: BundleCloneInstance) => any): Promise<BundleCloneInstance> + { + return this._proxy.create(params, callback); + } + + /** + * Create a BundleCloneInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BundleCloneInstance with HTTP metadata + */ + createWithHttpInfo(params: BundleCloneContextCreateOptions, callback?: (error: Error | null, item?: ApiResponse<BundleCloneInstance>) => any): Promise<ApiResponse<BundleCloneInstance>>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<BundleCloneInstance>) => any): Promise<ApiResponse<BundleCloneInstance>> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + bundleSid: this.bundleSid, + accountSid: this.accountSid, + regulationSid: this.regulationSid, + friendlyName: this.friendlyName, + status: this.status, + validUntil: this.validUntil, + email: this.email, + statusCallback: this.statusCallback, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BundleCloneSolution { +} + +export interface BundleCloneListInstance { + _version: V2; + _solution: BundleCloneSolution; + _uri: string; + + (bundleSid: string, ): BundleCloneContext; + get(bundleSid: string, ): BundleCloneContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BundleCloneListInstance(version: V2): BundleCloneListInstance { + const instance = ((bundleSid, ) => instance.get(bundleSid, )) as BundleCloneListInstance; + + instance.get = function get(bundleSid, ): BundleCloneContext { + return new BundleCloneContextImpl(version, bundleSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/numbers/v2/endUser.ts b/rest/numbers/v2/endUser.ts new file mode 100644 index 000000000..264b09d87 --- /dev/null +++ b/rest/numbers/v2/endUser.ts @@ -0,0 +1,931 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The type of end user of the Bundle resource - can be `individual` or `business`. + */ +export type EndUserType = 'individual'|'business'; + + + + +/** + * Options to pass to update a EndUserInstance + */ +export interface EndUserContextUpdateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The set of parameters that are the attributes of the End User resource which are derived End User Types. */ + "attributes"?: any; +} + +/** + * Options to pass to create a EndUserInstance + */ +export interface EndUserListInstanceCreateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName": string; + /** */ + "type": EndUserType; + /** The set of parameters that are the attributes of the End User resource which are derived End User Types. */ + "attributes"?: any; +} + +/** + * Options to pass to each + */ +export interface EndUserListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EndUserInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EndUserListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EndUserListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EndUserContext { + + /** + * Remove a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + fetch(callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance> + + /** + * Fetch a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> + + /** + * Update a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + update(callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance>; + /** + * Update a EndUserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + update(params: EndUserContextUpdateOptions, callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance>; + + /** + * Update a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>>; + /** + * Update a EndUserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + updateWithHttpInfo(params: EndUserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EndUserContextSolution { + "sid": string; +} + +export class EndUserContextImpl implements EndUserContext { + protected _solution: EndUserContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/RegulatoryCompliance/EndUsers/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EndUserInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EndUserResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EndUserInstance> => ({ + ...response, + body: new EndUserInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: EndUserContextUpdateOptions | ((error: Error | null, item?: EndUserInstance) => any),callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new EndUserInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: EndUserContextUpdateOptions | ((error: Error | null, item?: ApiResponse<EndUserInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<EndUserResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<EndUserInstance> => ({ + ...response, + body: new EndUserInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EndUserPayload extends TwilioResponsePayload { + results: EndUserResource[]; +} + +interface EndUserResource { + sid: string; + account_sid: string; + friendly_name: string; + type: EndUserType; + attributes: any; + date_created: Date; + date_updated: Date; + url: string; +} + +export class EndUserInstance { + protected _solution: EndUserContextSolution; + protected _context?: EndUserContext; + + constructor(protected _version: V2, payload: EndUserResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.type = payload.type; + this.attributes = (payload.attributes); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string created by Twilio to identify the End User resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the End User resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + type: EndUserType; + /** + * The set of parameters that are the attributes of the End Users resource which are listed in the End User Types. + */ + attributes: any; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the End User resource. + */ + url: string; + + private get _proxy(): EndUserContext { + this._context = this._context || new EndUserContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + fetch(callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + update(callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance>; + /** + * Update a EndUserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + update(params: EndUserContextUpdateOptions, callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance>; + + update(params?: any, callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>>; + /** + * Update a EndUserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + updateWithHttpInfo(params: EndUserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + type: this.type, + attributes: this.attributes, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EndUserSolution { +} + +export interface EndUserListInstance { + _version: V2; + _solution: EndUserSolution; + _uri: string; + + (sid: string, ): EndUserContext; + get(sid: string, ): EndUserContext; + + + + + + + + + /** + * Create a EndUserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + create(params: EndUserListInstanceCreateOptions, callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance>; + + /** + * Create a EndUserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + createWithHttpInfo(params: EndUserListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>>; + + + + + /** + * Streams EndUserInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EndUserInstance, done: (err?: Error) => void) => void): void; + each(params: EndUserListInstanceEachOptions, callback?: (item: EndUserInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EndUserInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EndUserInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EndUserListInstanceEachOptions, callback?: (item: EndUserInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EndUserInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EndUserPage) => any): Promise<EndUserPage>; + /** + * Retrieve a single target page of EndUserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EndUserPage>) => any): Promise<ApiResponse<EndUserPage>>; + /** + * Lists EndUserInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EndUserInstance[]) => any): Promise<EndUserInstance[]>; + list(params: EndUserListInstanceOptions, callback?: (error: Error | null, items: EndUserInstance[]) => any): Promise<EndUserInstance[]>; + /** + * Lists EndUserInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EndUserInstance[]>) => any): Promise<ApiResponse<EndUserInstance[]>>; + listWithHttpInfo(params: EndUserListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EndUserInstance[]>) => any): Promise<ApiResponse<EndUserInstance[]>>; + /** + * Retrieve a single page of EndUserInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EndUserPage) => any): Promise<EndUserPage>; + page(params: EndUserListInstancePageOptions, callback?: (error: Error | null, items: EndUserPage) => any): Promise<EndUserPage>; + /** + * Retrieve a single page of EndUserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EndUserPage>) => any): Promise<ApiResponse<EndUserPage>>; + pageWithHttpInfo(params: EndUserListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EndUserPage>) => any): Promise<ApiResponse<EndUserPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EndUserListInstance(version: V2): EndUserListInstance { + const instance = ((sid, ) => instance.get(sid, )) as EndUserListInstance; + + instance.get = function get(sid, ): EndUserContext { + return new EndUserContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/RegulatoryCompliance/EndUsers`; + + instance.create = function create(params: EndUserListInstanceCreateOptions, callback?: (error: Error | null, items: EndUserInstance) => any): Promise<EndUserInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new EndUserInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: EndUserListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<EndUserResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<EndUserInstance> => ({ + ...response, + body: new EndUserInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: EndUserListInstancePageOptions | ((error: Error | null, items: EndUserPage) => any), callback?: (error: Error | null, items: EndUserPage) => any): Promise<EndUserPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EndUserPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EndUserPage) => any): Promise<EndUserPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EndUserPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EndUserListInstancePageOptions | ((error: Error | null, items: ApiResponse<EndUserPage>) => any), callback?: (error: Error | null, items: ApiResponse<EndUserPage>) => any): Promise<ApiResponse<EndUserPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EndUserPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EndUserPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EndUserPage>) => any): Promise<ApiResponse<EndUserPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EndUserPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EndUserPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EndUserPage extends Page<V2, EndUserPayload, EndUserResource, EndUserInstance> { +/** +* Initialize the EndUserPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: EndUserSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EndUserInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EndUserResource): EndUserInstance { + + return new EndUserInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/endUserType.ts b/rest/numbers/v2/endUserType.ts new file mode 100644 index 000000000..9bf288210 --- /dev/null +++ b/rest/numbers/v2/endUserType.ts @@ -0,0 +1,544 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface EndUserTypeListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EndUserTypeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EndUserTypeListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EndUserTypeListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EndUserTypeContext { + + /** + * Fetch a EndUserTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserTypeInstance + */ + fetch(callback?: (error: Error | null, item?: EndUserTypeInstance) => any): Promise<EndUserTypeInstance> + + /** + * Fetch a EndUserTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserTypeInstance>) => any): Promise<ApiResponse<EndUserTypeInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EndUserTypeContextSolution { + "sid": string; +} + +export class EndUserTypeContextImpl implements EndUserTypeContext { + protected _solution: EndUserTypeContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/RegulatoryCompliance/EndUserTypes/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: EndUserTypeInstance) => any): Promise<EndUserTypeInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EndUserTypeInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserTypeInstance>) => any): Promise<ApiResponse<EndUserTypeInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EndUserTypeResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EndUserTypeInstance> => ({ + ...response, + body: new EndUserTypeInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EndUserTypePayload extends TwilioResponsePayload { + end_user_types: EndUserTypeResource[]; +} + +interface EndUserTypeResource { + sid: string; + friendly_name: string; + machine_name: string; + fields: Array<any>; + url: string; +} + +export class EndUserTypeInstance { + protected _solution: EndUserTypeContextSolution; + protected _context?: EndUserTypeContext; + + constructor(protected _version: V2, payload: EndUserTypeResource, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.machineName = (payload.machine_name); + this.fields = (payload.fields); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that identifies the End-User Type resource. + */ + sid: string; + /** + * A human-readable description that is assigned to describe the End-User Type resource. Examples can include first name, last name, email, business name, etc + */ + friendlyName: string; + /** + * A machine-readable description of the End-User Type resource. Examples can include first_name, last_name, email, business_name, etc. + */ + machineName: string; + /** + * The required information for creating an End-User. The required fields will change as regulatory needs change and will differ for businesses and individuals. + */ + fields: Array<any>; + /** + * The absolute URL of the End-User Type resource. + */ + url: string; + + private get _proxy(): EndUserTypeContext { + this._context = this._context || new EndUserTypeContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a EndUserTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserTypeInstance + */ + fetch(callback?: (error: Error | null, item?: EndUserTypeInstance) => any): Promise<EndUserTypeInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EndUserTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserTypeInstance>) => any): Promise<ApiResponse<EndUserTypeInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + machineName: this.machineName, + fields: this.fields, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EndUserTypeSolution { +} + +export interface EndUserTypeListInstance { + _version: V2; + _solution: EndUserTypeSolution; + _uri: string; + + (sid: string, ): EndUserTypeContext; + get(sid: string, ): EndUserTypeContext; + + + + + + /** + * Streams EndUserTypeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EndUserTypeInstance, done: (err?: Error) => void) => void): void; + each(params: EndUserTypeListInstanceEachOptions, callback?: (item: EndUserTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EndUserTypeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EndUserTypeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EndUserTypeListInstanceEachOptions, callback?: (item: EndUserTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EndUserTypeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EndUserTypePage) => any): Promise<EndUserTypePage>; + /** + * Retrieve a single target page of EndUserTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EndUserTypePage>) => any): Promise<ApiResponse<EndUserTypePage>>; + /** + * Lists EndUserTypeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EndUserTypeInstance[]) => any): Promise<EndUserTypeInstance[]>; + list(params: EndUserTypeListInstanceOptions, callback?: (error: Error | null, items: EndUserTypeInstance[]) => any): Promise<EndUserTypeInstance[]>; + /** + * Lists EndUserTypeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EndUserTypeInstance[]>) => any): Promise<ApiResponse<EndUserTypeInstance[]>>; + listWithHttpInfo(params: EndUserTypeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EndUserTypeInstance[]>) => any): Promise<ApiResponse<EndUserTypeInstance[]>>; + /** + * Retrieve a single page of EndUserTypeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EndUserTypePage) => any): Promise<EndUserTypePage>; + page(params: EndUserTypeListInstancePageOptions, callback?: (error: Error | null, items: EndUserTypePage) => any): Promise<EndUserTypePage>; + /** + * Retrieve a single page of EndUserTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EndUserTypePage>) => any): Promise<ApiResponse<EndUserTypePage>>; + pageWithHttpInfo(params: EndUserTypeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EndUserTypePage>) => any): Promise<ApiResponse<EndUserTypePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EndUserTypeListInstance(version: V2): EndUserTypeListInstance { + const instance = ((sid, ) => instance.get(sid, )) as EndUserTypeListInstance; + + instance.get = function get(sid, ): EndUserTypeContext { + return new EndUserTypeContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/RegulatoryCompliance/EndUserTypes`; + + instance.page = function page(params?: EndUserTypeListInstancePageOptions | ((error: Error | null, items: EndUserTypePage) => any), callback?: (error: Error | null, items: EndUserTypePage) => any): Promise<EndUserTypePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EndUserTypePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EndUserTypePage) => any): Promise<EndUserTypePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EndUserTypePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EndUserTypeListInstancePageOptions | ((error: Error | null, items: ApiResponse<EndUserTypePage>) => any), callback?: (error: Error | null, items: ApiResponse<EndUserTypePage>) => any): Promise<ApiResponse<EndUserTypePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EndUserTypePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EndUserTypePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EndUserTypePage>) => any): Promise<ApiResponse<EndUserTypePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EndUserTypePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EndUserTypePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EndUserTypePage extends Page<V2, EndUserTypePayload, EndUserTypeResource, EndUserTypeInstance> { +/** +* Initialize the EndUserTypePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: EndUserTypeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EndUserTypeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EndUserTypeResource): EndUserTypeInstance { + + return new EndUserTypeInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/hostedNumberOrder.ts b/rest/numbers/v2/hostedNumberOrder.ts new file mode 100644 index 000000000..8e636e5ed --- /dev/null +++ b/rest/numbers/v2/hostedNumberOrder.ts @@ -0,0 +1,1170 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../interfaces"; + + +/** + * Status of this resource. It can hold one of the values: 1. Twilio Processing 2. Received, 3. Pending LOA, 4. Carrier Processing, 5. Completed, 6. Action Required, 7. Failed. See the [HostedNumberOrders Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values) section for more information on each of these statuses. + */ +export type HostedNumberOrderStatus = 'twilio-processing'|'received'|'pending-verification'|'verified'|'pending-loa'|'carrier-processing'|'testing'|'completed'|'failed'|'action-required'; + +/** + * The method used to verify ownership of the number to be hosted. Can be: `phone-call` or `phone-bill` and the default is `phone-call`. + */ +export type HostedNumberOrderVerificationType = 'phone-call'; + + + + +/** + * Options to pass to update a HostedNumberOrderInstance + */ +export interface HostedNumberOrderContextUpdateOptions { + /** */ + "status": HostedNumberOrderStatus; + /** The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. */ + "verificationCallDelay"?: number; + /** The numerical extension to dial when making the ownership verification call. */ + "verificationCallExtension"?: string; +} + +/** + * Options to pass to create a HostedNumberOrderInstance + */ +export interface HostedNumberOrderListInstanceCreateOptions { + /** The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format */ + "phoneNumber": string; + /** The contact phone number of the person authorized to sign the Authorization Document. */ + "contactPhoneNumber": string; + /** Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. */ + "addressSid": string; + /** Optional. Email of the owner of this phone number that is being hosted. */ + "email": string; + /** This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. */ + "accountSid"?: string; + /** A 128 character string that is a human readable text that describes this resource. */ + "friendlyName"?: string; + /** Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. */ + "ccEmails"?: Array<string>; + /** The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. */ + "smsUrl"?: string; + /** The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. */ + "smsMethod"?: string; + /** A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. */ + "smsFallbackUrl"?: string; + /** Used to specify that the SMS capability will be hosted on Twilio\\\'s platform. */ + "smsCapability"?: boolean; + /** The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. */ + "smsFallbackMethod"?: string; + /** Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. */ + "statusCallbackUrl"?: string; + /** Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. */ + "statusCallbackMethod"?: string; + /** Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. */ + "smsApplicationSid"?: string; + /** The title of the person authorized to sign the Authorization Document for this phone number. */ + "contactTitle"?: string; +} + +/** + * Options to pass to each + */ +export interface HostedNumberOrderListInstanceEachOptions { + /** The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. */ + "status"?: HostedNumberOrderStatus; + /** Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. */ + "smsCapability"?: boolean; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 128 characters. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: HostedNumberOrderInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface HostedNumberOrderListInstanceOptions { + /** The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. */ + "status"?: HostedNumberOrderStatus; + /** Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. */ + "smsCapability"?: boolean; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 128 characters. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface HostedNumberOrderListInstancePageOptions { + /** The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. */ + "status"?: HostedNumberOrderStatus; + /** Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. */ + "smsCapability"?: boolean; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 128 characters. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface HostedNumberOrderContext { + + /** + * Remove a HostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a HostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a HostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + fetch(callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> + + /** + * Fetch a HostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> + + /** + * Update a HostedNumberOrderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + update(params: HostedNumberOrderContextUpdateOptions, callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance>; + + /** + * Update a HostedNumberOrderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + updateWithHttpInfo(params: HostedNumberOrderContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface HostedNumberOrderContextSolution { + "sid": string; +} + +export class HostedNumberOrderContextImpl implements HostedNumberOrderContext { + protected _solution: HostedNumberOrderContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/HostedNumber/Orders/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new HostedNumberOrderInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<HostedNumberOrderResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<HostedNumberOrderInstance> => ({ + ...response, + body: new HostedNumberOrderInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: HostedNumberOrderContextUpdateOptions,callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + if (params["verificationCallDelay"] !== undefined) + data["VerificationCallDelay"] = params["verificationCallDelay"]; + if (params["verificationCallExtension"] !== undefined) + data["VerificationCallExtension"] = params["verificationCallExtension"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new HostedNumberOrderInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: HostedNumberOrderContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + if (params["verificationCallDelay"] !== undefined) + data["VerificationCallDelay"] = params["verificationCallDelay"]; + if (params["verificationCallExtension"] !== undefined) + data["VerificationCallExtension"] = params["verificationCallExtension"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<HostedNumberOrderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<HostedNumberOrderInstance> => ({ + ...response, + body: new HostedNumberOrderInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface HostedNumberOrderPayload extends TwilioResponsePayload { + items: HostedNumberOrderResource[]; +} + +interface HostedNumberOrderResource { + sid: string; + account_sid: string; + incoming_phone_number_sid: string; + address_sid: string; + signing_document_sid: string; + phone_number: string; + capabilities: PhoneNumberCapabilities; + friendly_name: string; + status: HostedNumberOrderStatus; + failure_reason: string; + date_created: Date; + date_updated: Date; + email: string; + cc_emails: Array<string>; + url: string; + contact_title: string; + contact_phone_number: string; + bulk_hosting_request_sid: string; + next_step: string; + verification_attempts: number; + verification_call_sids: Array<string>; + verification_call_delay: number; + verification_call_extension: string; + verification_code: string; + verification_type: HostedNumberOrderVerificationType; +} + +export class HostedNumberOrderInstance { + protected _solution: HostedNumberOrderContextSolution; + protected _context?: HostedNumberOrderContext; + + constructor(protected _version: V2, payload: HostedNumberOrderResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.incomingPhoneNumberSid = (payload.incoming_phone_number_sid); + this.addressSid = (payload.address_sid); + this.signingDocumentSid = (payload.signing_document_sid); + this.phoneNumber = (payload.phone_number); + this.capabilities = (payload.capabilities); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.failureReason = (payload.failure_reason); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.email = (payload.email); + this.ccEmails = (payload.cc_emails); + this.url = (payload.url); + this.contactTitle = (payload.contact_title); + this.contactPhoneNumber = (payload.contact_phone_number); + this.bulkHostingRequestSid = (payload.bulk_hosting_request_sid); + this.nextStep = (payload.next_step); + this.verificationAttempts = deserialize.integer(payload.verification_attempts); + this.verificationCallSids = (payload.verification_call_sids); + this.verificationCallDelay = deserialize.integer(payload.verification_call_delay); + this.verificationCallExtension = (payload.verification_call_extension); + this.verificationCode = (payload.verification_code); + this.verificationType = payload.verification_type; + + this._solution = { sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this HostedNumberOrder. + */ + sid: string; + /** + * A 34 character string that uniquely identifies the account. + */ + accountSid: string; + /** + * A 34 character string that uniquely identifies the [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the phone number being hosted. + */ + incomingPhoneNumberSid: string; + /** + * A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + */ + addressSid: string; + /** + * A 34 character string that uniquely identifies the [Authorization Document](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource) the user needs to sign. + */ + signingDocumentSid: string; + /** + * Phone number to be hosted. This must be in [E.164](https://en.wikipedia.org/wiki/E.164) format, e.g., +16175551212 + */ + phoneNumber: string; + capabilities: PhoneNumberCapabilities; + /** + * A 128 character string that is a human-readable text that describes this resource. + */ + friendlyName: string; + status: HostedNumberOrderStatus; + /** + * A message that explains why a hosted_number_order went to status \"action-required\" + */ + failureReason: string; + /** + * The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * Email of the owner of this phone number that is being hosted. + */ + email: string; + /** + * A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + */ + ccEmails: Array<string>; + /** + * The URL of this HostedNumberOrder. + */ + url: string; + /** + * The title of the person authorized to sign the Authorization Document for this phone number. + */ + contactTitle: string; + /** + * The contact phone number of the person authorized to sign the Authorization Document. + */ + contactPhoneNumber: string; + /** + * A 34 character string that uniquely identifies the bulk hosting request associated with this HostedNumberOrder. + */ + bulkHostingRequestSid: string; + /** + * The next step you need to take to complete the hosted number order and request it successfully. + */ + nextStep: string; + /** + * The number of attempts made to verify ownership via a call for the hosted phone number. + */ + verificationAttempts: number; + /** + * The Call SIDs that identify the calls placed to verify ownership. + */ + verificationCallSids: Array<string>; + /** + * The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + */ + verificationCallDelay: number; + /** + * The numerical extension to dial when making the ownership verification call. + */ + verificationCallExtension: string; + /** + * The digits the user must pass in the ownership verification call. + */ + verificationCode: string; + verificationType: HostedNumberOrderVerificationType; + + private get _proxy(): HostedNumberOrderContext { + this._context = this._context || new HostedNumberOrderContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a HostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a HostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a HostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + fetch(callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a HostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a HostedNumberOrderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + update(params: HostedNumberOrderContextUpdateOptions, callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance>; + + update(params?: any, callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a HostedNumberOrderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + updateWithHttpInfo(params: HostedNumberOrderContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + incomingPhoneNumberSid: this.incomingPhoneNumberSid, + addressSid: this.addressSid, + signingDocumentSid: this.signingDocumentSid, + phoneNumber: this.phoneNumber, + capabilities: this.capabilities, + friendlyName: this.friendlyName, + status: this.status, + failureReason: this.failureReason, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + email: this.email, + ccEmails: this.ccEmails, + url: this.url, + contactTitle: this.contactTitle, + contactPhoneNumber: this.contactPhoneNumber, + bulkHostingRequestSid: this.bulkHostingRequestSid, + nextStep: this.nextStep, + verificationAttempts: this.verificationAttempts, + verificationCallSids: this.verificationCallSids, + verificationCallDelay: this.verificationCallDelay, + verificationCallExtension: this.verificationCallExtension, + verificationCode: this.verificationCode, + verificationType: this.verificationType, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface HostedNumberOrderSolution { +} + +export interface HostedNumberOrderListInstance { + _version: V2; + _solution: HostedNumberOrderSolution; + _uri: string; + + (sid: string, ): HostedNumberOrderContext; + get(sid: string, ): HostedNumberOrderContext; + + + + + + + + + /** + * Create a HostedNumberOrderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + create(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance>; + + /** + * Create a HostedNumberOrderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + createWithHttpInfo(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>>; + + + + + /** + * Streams HostedNumberOrderInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: HostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + each(params: HostedNumberOrderListInstanceEachOptions, callback?: (item: HostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + /** + * Streams HostedNumberOrderInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: HostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: HostedNumberOrderListInstanceEachOptions, callback?: (item: HostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of HostedNumberOrderInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: HostedNumberOrderPage) => any): Promise<HostedNumberOrderPage>; + /** + * Retrieve a single target page of HostedNumberOrderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderPage>) => any): Promise<ApiResponse<HostedNumberOrderPage>>; + /** + * Lists HostedNumberOrderInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: HostedNumberOrderInstance[]) => any): Promise<HostedNumberOrderInstance[]>; + list(params: HostedNumberOrderListInstanceOptions, callback?: (error: Error | null, items: HostedNumberOrderInstance[]) => any): Promise<HostedNumberOrderInstance[]>; + /** + * Lists HostedNumberOrderInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderInstance[]>) => any): Promise<ApiResponse<HostedNumberOrderInstance[]>>; + listWithHttpInfo(params: HostedNumberOrderListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderInstance[]>) => any): Promise<ApiResponse<HostedNumberOrderInstance[]>>; + /** + * Retrieve a single page of HostedNumberOrderInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: HostedNumberOrderPage) => any): Promise<HostedNumberOrderPage>; + page(params: HostedNumberOrderListInstancePageOptions, callback?: (error: Error | null, items: HostedNumberOrderPage) => any): Promise<HostedNumberOrderPage>; + /** + * Retrieve a single page of HostedNumberOrderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderPage>) => any): Promise<ApiResponse<HostedNumberOrderPage>>; + pageWithHttpInfo(params: HostedNumberOrderListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderPage>) => any): Promise<ApiResponse<HostedNumberOrderPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function HostedNumberOrderListInstance(version: V2): HostedNumberOrderListInstance { + const instance = ((sid, ) => instance.get(sid, )) as HostedNumberOrderListInstance; + + instance.get = function get(sid, ): HostedNumberOrderContext { + return new HostedNumberOrderContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/HostedNumber/Orders`; + + instance.create = function create(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, items: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + if (params["contactPhoneNumber"] === null || params["contactPhoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'contactPhoneNumber\']" missing.'); + } + + if (params["addressSid"] === null || params["addressSid"] === undefined) { + throw new Error('Required parameter "params[\'addressSid\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + + data["ContactPhoneNumber"] = params["contactPhoneNumber"]; + + data["AddressSid"] = params["addressSid"]; + + data["Email"] = params["email"]; + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsCapability"] !== undefined) + data["SmsCapability"] = serialize.bool(params["smsCapability"]); + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["contactTitle"] !== undefined) + data["ContactTitle"] = params["contactTitle"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new HostedNumberOrderInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + if (params["contactPhoneNumber"] === null || params["contactPhoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'contactPhoneNumber\']" missing.'); + } + + if (params["addressSid"] === null || params["addressSid"] === undefined) { + throw new Error('Required parameter "params[\'addressSid\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + + data["ContactPhoneNumber"] = params["contactPhoneNumber"]; + + data["AddressSid"] = params["addressSid"]; + + data["Email"] = params["email"]; + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsCapability"] !== undefined) + data["SmsCapability"] = serialize.bool(params["smsCapability"]); + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["contactTitle"] !== undefined) + data["ContactTitle"] = params["contactTitle"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<HostedNumberOrderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<HostedNumberOrderInstance> => ({ + ...response, + body: new HostedNumberOrderInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: HostedNumberOrderListInstancePageOptions | ((error: Error | null, items: HostedNumberOrderPage) => any), callback?: (error: Error | null, items: HostedNumberOrderPage) => any): Promise<HostedNumberOrderPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["smsCapability"] !== undefined) + data["SmsCapability"] = serialize.bool(params["smsCapability"]); + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["incomingPhoneNumberSid"] !== undefined) + data["IncomingPhoneNumberSid"] = params["incomingPhoneNumberSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new HostedNumberOrderPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: HostedNumberOrderPage) => any): Promise<HostedNumberOrderPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new HostedNumberOrderPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: HostedNumberOrderListInstancePageOptions | ((error: Error | null, items: ApiResponse<HostedNumberOrderPage>) => any), callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderPage>) => any): Promise<ApiResponse<HostedNumberOrderPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["smsCapability"] !== undefined) + data["SmsCapability"] = serialize.bool(params["smsCapability"]); + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["incomingPhoneNumberSid"] !== undefined) + data["IncomingPhoneNumberSid"] = params["incomingPhoneNumberSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<HostedNumberOrderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new HostedNumberOrderPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<HostedNumberOrderPage>) => any): Promise<ApiResponse<HostedNumberOrderPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<HostedNumberOrderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new HostedNumberOrderPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class HostedNumberOrderPage extends Page<V2, HostedNumberOrderPayload, HostedNumberOrderResource, HostedNumberOrderInstance> { +/** +* Initialize the HostedNumberOrderPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: HostedNumberOrderSolution) { + super(version, response, solution); + } + + /** + * Build an instance of HostedNumberOrderInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: HostedNumberOrderResource): HostedNumberOrderInstance { + + return new HostedNumberOrderInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/regulation.ts b/rest/numbers/v2/regulation.ts new file mode 100644 index 000000000..5657ec131 --- /dev/null +++ b/rest/numbers/v2/regulation.ts @@ -0,0 +1,677 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The type of End User the regulation requires - can be `individual` or `business`. + */ +export type RegulationEndUserType = 'individual'|'business'; + + +/** + * Options to pass to fetch a RegulationInstance + */ +export interface RegulationContextFetchOptions { + /** A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields */ + "includeConstraints"?: boolean; +} + +/** + * Options to pass to each + */ +export interface RegulationListInstanceEachOptions { + /** The type of End User the regulation requires - can be `individual` or `business`. */ + "endUserType"?: RegulationEndUserType; + /** The ISO country code of the phone number\'s country. */ + "isoCountry"?: string; + /** The type of phone number that the regulatory requiremnt is restricting. */ + "numberType"?: string; + /** A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields */ + "includeConstraints"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RegulationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RegulationListInstanceOptions { + /** The type of End User the regulation requires - can be `individual` or `business`. */ + "endUserType"?: RegulationEndUserType; + /** The ISO country code of the phone number\'s country. */ + "isoCountry"?: string; + /** The type of phone number that the regulatory requiremnt is restricting. */ + "numberType"?: string; + /** A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields */ + "includeConstraints"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RegulationListInstancePageOptions { + /** The type of End User the regulation requires - can be `individual` or `business`. */ + "endUserType"?: RegulationEndUserType; + /** The ISO country code of the phone number\'s country. */ + "isoCountry"?: string; + /** The type of phone number that the regulatory requiremnt is restricting. */ + "numberType"?: string; + /** A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields */ + "includeConstraints"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RegulationContext { + + /** + * Fetch a RegulationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RegulationInstance + */ + fetch(callback?: (error: Error | null, item?: RegulationInstance) => any): Promise<RegulationInstance>; + /** + * Fetch a RegulationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RegulationInstance + */ + fetch(params: RegulationContextFetchOptions, callback?: (error: Error | null, item?: RegulationInstance) => any): Promise<RegulationInstance>; + + /** + * Fetch a RegulationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RegulationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RegulationInstance>) => any): Promise<ApiResponse<RegulationInstance>>; + /** + * Fetch a RegulationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RegulationInstance with HTTP metadata + */ + fetchWithHttpInfo(params: RegulationContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<RegulationInstance>) => any): Promise<ApiResponse<RegulationInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RegulationContextSolution { + "sid": string; +} + +export class RegulationContextImpl implements RegulationContext { + protected _solution: RegulationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/RegulatoryCompliance/Regulations/${sid}`; + } + + fetch(params?: RegulationContextFetchOptions | ((error: Error | null, item?: RegulationInstance) => any),callback?: (error: Error | null, item?: RegulationInstance) => any): Promise<RegulationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["includeConstraints"] !== undefined) + data["IncludeConstraints"] = serialize.bool(params["includeConstraints"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new RegulationInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: RegulationContextFetchOptions | ((error: Error | null, item?: ApiResponse<RegulationInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<RegulationInstance>) => any): Promise<ApiResponse<RegulationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["includeConstraints"] !== undefined) + data["IncludeConstraints"] = serialize.bool(params["includeConstraints"]); + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RegulationResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RegulationInstance> => ({ + ...response, + body: new RegulationInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RegulationPayload extends TwilioResponsePayload { + results: RegulationResource[]; +} + +interface RegulationResource { + sid: string; + friendly_name: string; + iso_country: string; + number_type: string; + end_user_type: RegulationEndUserType; + requirements: any; + url: string; +} + +export class RegulationInstance { + protected _solution: RegulationContextSolution; + protected _context?: RegulationContext; + + constructor(protected _version: V2, payload: RegulationResource, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.isoCountry = (payload.iso_country); + this.numberType = (payload.number_type); + this.endUserType = payload.end_user_type; + this.requirements = (payload.requirements); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that identifies the Regulation resource. + */ + sid: string; + /** + * A human-readable description that is assigned to describe the Regulation resource. Examples can include Germany: Mobile - Business. + */ + friendlyName: string; + /** + * The ISO country code of the phone number\'s country. + */ + isoCountry: string; + /** + * The type of phone number restricted by the regulatory requirement. For example, Germany mobile phone numbers provisioned by businesses require a business name with commercial register proof from the Handelsregisterauszug and a proof of address from Handelsregisterauszug or a trade license by Gewerbeanmeldung. + */ + numberType: string; + endUserType: RegulationEndUserType; + /** + * The SID of an object that holds the regulatory information of the phone number country, phone number type, and end user type. + */ + requirements: any; + /** + * The absolute URL of the Regulation resource. + */ + url: string; + + private get _proxy(): RegulationContext { + this._context = this._context || new RegulationContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a RegulationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RegulationInstance + */ + fetch(callback?: (error: Error | null, item?: RegulationInstance) => any): Promise<RegulationInstance>; + /** + * Fetch a RegulationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RegulationInstance + */ + fetch(params: RegulationContextFetchOptions, callback?: (error: Error | null, item?: RegulationInstance) => any): Promise<RegulationInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: RegulationInstance) => any): Promise<RegulationInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a RegulationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RegulationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RegulationInstance>) => any): Promise<ApiResponse<RegulationInstance>>; + /** + * Fetch a RegulationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RegulationInstance with HTTP metadata + */ + fetchWithHttpInfo(params: RegulationContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<RegulationInstance>) => any): Promise<ApiResponse<RegulationInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<RegulationInstance>) => any): Promise<ApiResponse<RegulationInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + isoCountry: this.isoCountry, + numberType: this.numberType, + endUserType: this.endUserType, + requirements: this.requirements, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RegulationSolution { +} + +export interface RegulationListInstance { + _version: V2; + _solution: RegulationSolution; + _uri: string; + + (sid: string, ): RegulationContext; + get(sid: string, ): RegulationContext; + + + + + + /** + * Streams RegulationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RegulationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RegulationInstance, done: (err?: Error) => void) => void): void; + each(params: RegulationListInstanceEachOptions, callback?: (item: RegulationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RegulationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RegulationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RegulationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RegulationListInstanceEachOptions, callback?: (item: RegulationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RegulationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RegulationPage) => any): Promise<RegulationPage>; + /** + * Retrieve a single target page of RegulationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RegulationPage>) => any): Promise<ApiResponse<RegulationPage>>; + /** + * Lists RegulationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RegulationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RegulationInstance[]) => any): Promise<RegulationInstance[]>; + list(params: RegulationListInstanceOptions, callback?: (error: Error | null, items: RegulationInstance[]) => any): Promise<RegulationInstance[]>; + /** + * Lists RegulationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RegulationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RegulationInstance[]>) => any): Promise<ApiResponse<RegulationInstance[]>>; + listWithHttpInfo(params: RegulationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RegulationInstance[]>) => any): Promise<ApiResponse<RegulationInstance[]>>; + /** + * Retrieve a single page of RegulationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RegulationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RegulationPage) => any): Promise<RegulationPage>; + page(params: RegulationListInstancePageOptions, callback?: (error: Error | null, items: RegulationPage) => any): Promise<RegulationPage>; + /** + * Retrieve a single page of RegulationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RegulationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RegulationPage>) => any): Promise<ApiResponse<RegulationPage>>; + pageWithHttpInfo(params: RegulationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RegulationPage>) => any): Promise<ApiResponse<RegulationPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RegulationListInstance(version: V2): RegulationListInstance { + const instance = ((sid, ) => instance.get(sid, )) as RegulationListInstance; + + instance.get = function get(sid, ): RegulationContext { + return new RegulationContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/RegulatoryCompliance/Regulations`; + + instance.page = function page(params?: RegulationListInstancePageOptions | ((error: Error | null, items: RegulationPage) => any), callback?: (error: Error | null, items: RegulationPage) => any): Promise<RegulationPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["endUserType"] !== undefined) + data["EndUserType"] = params["endUserType"]; + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["numberType"] !== undefined) + data["NumberType"] = params["numberType"]; + if (params["includeConstraints"] !== undefined) + data["IncludeConstraints"] = serialize.bool(params["includeConstraints"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RegulationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RegulationPage) => any): Promise<RegulationPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RegulationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RegulationListInstancePageOptions | ((error: Error | null, items: ApiResponse<RegulationPage>) => any), callback?: (error: Error | null, items: ApiResponse<RegulationPage>) => any): Promise<ApiResponse<RegulationPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["endUserType"] !== undefined) + data["EndUserType"] = params["endUserType"]; + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["numberType"] !== undefined) + data["NumberType"] = params["numberType"]; + if (params["includeConstraints"] !== undefined) + data["IncludeConstraints"] = serialize.bool(params["includeConstraints"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RegulationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RegulationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RegulationPage>) => any): Promise<ApiResponse<RegulationPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RegulationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RegulationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RegulationPage extends Page<V2, RegulationPayload, RegulationResource, RegulationInstance> { +/** +* Initialize the RegulationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: RegulationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RegulationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RegulationResource): RegulationInstance { + + return new RegulationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/supportingDocument.ts b/rest/numbers/v2/supportingDocument.ts new file mode 100644 index 000000000..87a9a29f2 --- /dev/null +++ b/rest/numbers/v2/supportingDocument.ts @@ -0,0 +1,959 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The verification status of the Supporting Document resource. + */ +export type SupportingDocumentStatus = 'draft'|'pending-review'|'rejected'|'approved'|'expired'|'provisionally-approved'; + + + + +/** + * Options to pass to update a SupportingDocumentInstance + */ +export interface SupportingDocumentContextUpdateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. */ + "attributes"?: any; +} + +/** + * Options to pass to create a SupportingDocumentInstance + */ +export interface SupportingDocumentListInstanceCreateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName": string; + /** The type of the Supporting Document. */ + "type": string; + /** The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. */ + "attributes"?: any; +} + +/** + * Options to pass to each + */ +export interface SupportingDocumentListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SupportingDocumentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SupportingDocumentListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SupportingDocumentListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SupportingDocumentContext { + + /** + * Remove a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + fetch(callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> + + /** + * Fetch a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> + + /** + * Update a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + update(callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance>; + /** + * Update a SupportingDocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + update(params: SupportingDocumentContextUpdateOptions, callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance>; + + /** + * Update a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>>; + /** + * Update a SupportingDocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(params: SupportingDocumentContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SupportingDocumentContextSolution { + "sid": string; +} + +export class SupportingDocumentContextImpl implements SupportingDocumentContext { + protected _solution: SupportingDocumentContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/RegulatoryCompliance/SupportingDocuments/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SupportingDocumentInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SupportingDocumentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SupportingDocumentInstance> => ({ + ...response, + body: new SupportingDocumentInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SupportingDocumentContextUpdateOptions | ((error: Error | null, item?: SupportingDocumentInstance) => any),callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SupportingDocumentInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SupportingDocumentContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SupportingDocumentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SupportingDocumentInstance> => ({ + ...response, + body: new SupportingDocumentInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SupportingDocumentPayload extends TwilioResponsePayload { + results: SupportingDocumentResource[]; +} + +interface SupportingDocumentResource { + sid: string; + account_sid: string; + friendly_name: string; + mime_type: string; + status: SupportingDocumentStatus; + failure_reason: string; + errors: Array<any>; + type: string; + attributes: any; + date_created: Date; + date_updated: Date; + url: string; +} + +export class SupportingDocumentInstance { + protected _solution: SupportingDocumentContextSolution; + protected _context?: SupportingDocumentContext; + + constructor(protected _version: V2, payload: SupportingDocumentResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.mimeType = (payload.mime_type); + this.status = payload.status; + this.failureReason = (payload.failure_reason); + this.errors = (payload.errors); + this.type = (payload.type); + this.attributes = (payload.attributes); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string created by Twilio to identify the Supporting Document resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The image type uploaded in the Supporting Document container. + */ + mimeType: string; + status: SupportingDocumentStatus; + /** + * The failure reason of the Supporting Document Resource. + */ + failureReason: string; + /** + * A list of errors that occurred during the registering RC Bundle + */ + errors: Array<any>; + /** + * The type of the Supporting Document. + */ + type: string; + /** + * The set of parameters that are the attributes of the Supporting Documents resource which are listed in the Supporting Document Types. + */ + attributes: any; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Supporting Document resource. + */ + url: string; + + private get _proxy(): SupportingDocumentContext { + this._context = this._context || new SupportingDocumentContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + fetch(callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + update(callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance>; + /** + * Update a SupportingDocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + update(params: SupportingDocumentContextUpdateOptions, callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>>; + /** + * Update a SupportingDocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(params: SupportingDocumentContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + mimeType: this.mimeType, + status: this.status, + failureReason: this.failureReason, + errors: this.errors, + type: this.type, + attributes: this.attributes, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SupportingDocumentSolution { +} + +export interface SupportingDocumentListInstance { + _version: V2; + _solution: SupportingDocumentSolution; + _uri: string; + + (sid: string, ): SupportingDocumentContext; + get(sid: string, ): SupportingDocumentContext; + + + + + + + + + /** + * Create a SupportingDocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + create(params: SupportingDocumentListInstanceCreateOptions, callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance>; + + /** + * Create a SupportingDocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + createWithHttpInfo(params: SupportingDocumentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>>; + + + + + /** + * Streams SupportingDocumentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SupportingDocumentInstance, done: (err?: Error) => void) => void): void; + each(params: SupportingDocumentListInstanceEachOptions, callback?: (item: SupportingDocumentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SupportingDocumentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SupportingDocumentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SupportingDocumentListInstanceEachOptions, callback?: (item: SupportingDocumentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SupportingDocumentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SupportingDocumentPage) => any): Promise<SupportingDocumentPage>; + /** + * Retrieve a single target page of SupportingDocumentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentPage>) => any): Promise<ApiResponse<SupportingDocumentPage>>; + /** + * Lists SupportingDocumentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SupportingDocumentInstance[]) => any): Promise<SupportingDocumentInstance[]>; + list(params: SupportingDocumentListInstanceOptions, callback?: (error: Error | null, items: SupportingDocumentInstance[]) => any): Promise<SupportingDocumentInstance[]>; + /** + * Lists SupportingDocumentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SupportingDocumentInstance[]>) => any): Promise<ApiResponse<SupportingDocumentInstance[]>>; + listWithHttpInfo(params: SupportingDocumentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentInstance[]>) => any): Promise<ApiResponse<SupportingDocumentInstance[]>>; + /** + * Retrieve a single page of SupportingDocumentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SupportingDocumentPage) => any): Promise<SupportingDocumentPage>; + page(params: SupportingDocumentListInstancePageOptions, callback?: (error: Error | null, items: SupportingDocumentPage) => any): Promise<SupportingDocumentPage>; + /** + * Retrieve a single page of SupportingDocumentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SupportingDocumentPage>) => any): Promise<ApiResponse<SupportingDocumentPage>>; + pageWithHttpInfo(params: SupportingDocumentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentPage>) => any): Promise<ApiResponse<SupportingDocumentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SupportingDocumentListInstance(version: V2): SupportingDocumentListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SupportingDocumentListInstance; + + instance.get = function get(sid, ): SupportingDocumentContext { + return new SupportingDocumentContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/RegulatoryCompliance/SupportingDocuments`; + + instance.create = function create(params: SupportingDocumentListInstanceCreateOptions, callback?: (error: Error | null, items: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SupportingDocumentInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SupportingDocumentListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SupportingDocumentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SupportingDocumentInstance> => ({ + ...response, + body: new SupportingDocumentInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SupportingDocumentListInstancePageOptions | ((error: Error | null, items: SupportingDocumentPage) => any), callback?: (error: Error | null, items: SupportingDocumentPage) => any): Promise<SupportingDocumentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SupportingDocumentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SupportingDocumentPage) => any): Promise<SupportingDocumentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SupportingDocumentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SupportingDocumentListInstancePageOptions | ((error: Error | null, items: ApiResponse<SupportingDocumentPage>) => any), callback?: (error: Error | null, items: ApiResponse<SupportingDocumentPage>) => any): Promise<ApiResponse<SupportingDocumentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SupportingDocumentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SupportingDocumentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SupportingDocumentPage>) => any): Promise<ApiResponse<SupportingDocumentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SupportingDocumentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SupportingDocumentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SupportingDocumentPage extends Page<V2, SupportingDocumentPayload, SupportingDocumentResource, SupportingDocumentInstance> { +/** +* Initialize the SupportingDocumentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: SupportingDocumentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SupportingDocumentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SupportingDocumentResource): SupportingDocumentInstance { + + return new SupportingDocumentInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v2/supportingDocumentType.ts b/rest/numbers/v2/supportingDocumentType.ts new file mode 100644 index 000000000..0d1112bd8 --- /dev/null +++ b/rest/numbers/v2/supportingDocumentType.ts @@ -0,0 +1,544 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface SupportingDocumentTypeListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SupportingDocumentTypeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SupportingDocumentTypeListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SupportingDocumentTypeListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SupportingDocumentTypeContext { + + /** + * Fetch a SupportingDocumentTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentTypeInstance + */ + fetch(callback?: (error: Error | null, item?: SupportingDocumentTypeInstance) => any): Promise<SupportingDocumentTypeInstance> + + /** + * Fetch a SupportingDocumentTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentTypeInstance>) => any): Promise<ApiResponse<SupportingDocumentTypeInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SupportingDocumentTypeContextSolution { + "sid": string; +} + +export class SupportingDocumentTypeContextImpl implements SupportingDocumentTypeContext { + protected _solution: SupportingDocumentTypeContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/RegulatoryCompliance/SupportingDocumentTypes/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: SupportingDocumentTypeInstance) => any): Promise<SupportingDocumentTypeInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SupportingDocumentTypeInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentTypeInstance>) => any): Promise<ApiResponse<SupportingDocumentTypeInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SupportingDocumentTypeResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SupportingDocumentTypeInstance> => ({ + ...response, + body: new SupportingDocumentTypeInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SupportingDocumentTypePayload extends TwilioResponsePayload { + supporting_document_types: SupportingDocumentTypeResource[]; +} + +interface SupportingDocumentTypeResource { + sid: string; + friendly_name: string; + machine_name: string; + fields: Array<any>; + url: string; +} + +export class SupportingDocumentTypeInstance { + protected _solution: SupportingDocumentTypeContextSolution; + protected _context?: SupportingDocumentTypeContext; + + constructor(protected _version: V2, payload: SupportingDocumentTypeResource, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.machineName = (payload.machine_name); + this.fields = (payload.fields); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that identifies the Supporting Document Type resource. + */ + sid: string; + /** + * A human-readable description of the Supporting Document Type resource. + */ + friendlyName: string; + /** + * The machine-readable description of the Supporting Document Type resource. + */ + machineName: string; + /** + * The required information for creating a Supporting Document. The required fields will change as regulatory needs change and will differ for businesses and individuals. + */ + fields: Array<any>; + /** + * The absolute URL of the Supporting Document Type resource. + */ + url: string; + + private get _proxy(): SupportingDocumentTypeContext { + this._context = this._context || new SupportingDocumentTypeContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a SupportingDocumentTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentTypeInstance + */ + fetch(callback?: (error: Error | null, item?: SupportingDocumentTypeInstance) => any): Promise<SupportingDocumentTypeInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SupportingDocumentTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentTypeInstance>) => any): Promise<ApiResponse<SupportingDocumentTypeInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + machineName: this.machineName, + fields: this.fields, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SupportingDocumentTypeSolution { +} + +export interface SupportingDocumentTypeListInstance { + _version: V2; + _solution: SupportingDocumentTypeSolution; + _uri: string; + + (sid: string, ): SupportingDocumentTypeContext; + get(sid: string, ): SupportingDocumentTypeContext; + + + + + + /** + * Streams SupportingDocumentTypeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SupportingDocumentTypeInstance, done: (err?: Error) => void) => void): void; + each(params: SupportingDocumentTypeListInstanceEachOptions, callback?: (item: SupportingDocumentTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SupportingDocumentTypeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SupportingDocumentTypeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SupportingDocumentTypeListInstanceEachOptions, callback?: (item: SupportingDocumentTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SupportingDocumentTypeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SupportingDocumentTypePage) => any): Promise<SupportingDocumentTypePage>; + /** + * Retrieve a single target page of SupportingDocumentTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypePage>) => any): Promise<ApiResponse<SupportingDocumentTypePage>>; + /** + * Lists SupportingDocumentTypeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SupportingDocumentTypeInstance[]) => any): Promise<SupportingDocumentTypeInstance[]>; + list(params: SupportingDocumentTypeListInstanceOptions, callback?: (error: Error | null, items: SupportingDocumentTypeInstance[]) => any): Promise<SupportingDocumentTypeInstance[]>; + /** + * Lists SupportingDocumentTypeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypeInstance[]>) => any): Promise<ApiResponse<SupportingDocumentTypeInstance[]>>; + listWithHttpInfo(params: SupportingDocumentTypeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypeInstance[]>) => any): Promise<ApiResponse<SupportingDocumentTypeInstance[]>>; + /** + * Retrieve a single page of SupportingDocumentTypeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SupportingDocumentTypePage) => any): Promise<SupportingDocumentTypePage>; + page(params: SupportingDocumentTypeListInstancePageOptions, callback?: (error: Error | null, items: SupportingDocumentTypePage) => any): Promise<SupportingDocumentTypePage>; + /** + * Retrieve a single page of SupportingDocumentTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypePage>) => any): Promise<ApiResponse<SupportingDocumentTypePage>>; + pageWithHttpInfo(params: SupportingDocumentTypeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypePage>) => any): Promise<ApiResponse<SupportingDocumentTypePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SupportingDocumentTypeListInstance(version: V2): SupportingDocumentTypeListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SupportingDocumentTypeListInstance; + + instance.get = function get(sid, ): SupportingDocumentTypeContext { + return new SupportingDocumentTypeContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/RegulatoryCompliance/SupportingDocumentTypes`; + + instance.page = function page(params?: SupportingDocumentTypeListInstancePageOptions | ((error: Error | null, items: SupportingDocumentTypePage) => any), callback?: (error: Error | null, items: SupportingDocumentTypePage) => any): Promise<SupportingDocumentTypePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SupportingDocumentTypePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SupportingDocumentTypePage) => any): Promise<SupportingDocumentTypePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SupportingDocumentTypePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SupportingDocumentTypeListInstancePageOptions | ((error: Error | null, items: ApiResponse<SupportingDocumentTypePage>) => any), callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypePage>) => any): Promise<ApiResponse<SupportingDocumentTypePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SupportingDocumentTypePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SupportingDocumentTypePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SupportingDocumentTypePage>) => any): Promise<ApiResponse<SupportingDocumentTypePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SupportingDocumentTypePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SupportingDocumentTypePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SupportingDocumentTypePage extends Page<V2, SupportingDocumentTypePayload, SupportingDocumentTypeResource, SupportingDocumentTypeInstance> { +/** +* Initialize the SupportingDocumentTypePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: SupportingDocumentTypeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SupportingDocumentTypeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SupportingDocumentTypeResource): SupportingDocumentTypeInstance { + + return new SupportingDocumentTypeInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/numbers/v3/hostedNumberOrder.ts b/rest/numbers/v3/hostedNumberOrder.ts new file mode 100644 index 000000000..db06b1900 --- /dev/null +++ b/rest/numbers/v3/hostedNumberOrder.ts @@ -0,0 +1,449 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../interfaces"; + + +export type HostedNumberOrderStatus = 'twilio-processing'|'received'|'pending-verification'|'verified'|'pending-loa'|'carrier-processing'|'testing'|'completed'|'failed'|'action-required'; + +export type HostedNumberOrderVerificationType = 'phone-call'|'phone-bill'; + + +/** + * Options to pass to create a HostedNumberOrderInstance + */ +export interface HostedNumberOrderListInstanceCreateOptions { + /** The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format */ + "phoneNumber": string; + /** Used to specify that the SMS capability will be hosted on Twilio\\\'s platform. */ + "smsCapability": boolean; + /** This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. */ + "accountSid"?: string; + /** A 64 character string that is a human readable text that describes this resource. */ + "friendlyName"?: string; + /** Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName"?: string; + /** Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. */ + "ccEmails"?: Array<string>; + /** The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. */ + "smsUrl"?: string; + /** The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. */ + "smsMethod"?: string; + /** A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. */ + "smsFallbackUrl"?: string; + /** The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. */ + "smsFallbackMethod"?: string; + /** Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. */ + "statusCallbackUrl"?: string; + /** Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. */ + "statusCallbackMethod"?: string; + /** Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. */ + "smsApplicationSid"?: string; + /** Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. */ + "addressSid"?: string; + /** Optional. Email of the owner of this phone number that is being hosted. */ + "email"?: string; + /** */ + "verificationType"?: HostedNumberOrderVerificationType; + /** Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. */ + "verificationDocumentSid"?: string; +} + + +export interface HostedNumberOrderSolution { +} + +export interface HostedNumberOrderListInstance { + _version: V3; + _solution: HostedNumberOrderSolution; + _uri: string; + + + + /** + * Create a HostedNumberOrderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + create(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance>; + + /** + * Create a HostedNumberOrderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + createWithHttpInfo(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function HostedNumberOrderListInstance(version: V3): HostedNumberOrderListInstance { + const instance = {} as HostedNumberOrderListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/HostedNumbers/HostedNumberOrders`; + + instance.create = function create(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, items: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + if (params["smsCapability"] === null || params["smsCapability"] === undefined) { + throw new Error('Required parameter "params[\'smsCapability\']" missing.'); + } + + let data: any = {}; + + + + data["phoneNumber"] = params["phoneNumber"]; + + data["smsCapability"] = serialize.bool(params["smsCapability"]); + if (params["accountSid"] !== undefined) + data["accountSid"] = params["accountSid"]; + if (params["friendlyName"] !== undefined) + data["friendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["uniqueName"] = params["uniqueName"]; + if (params["ccEmails"] !== undefined) + data["ccEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + if (params["smsUrl"] !== undefined) + data["smsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["smsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["smsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["smsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["statusCallbackUrl"] !== undefined) + data["statusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["statusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["smsApplicationSid"] !== undefined) + data["smsApplicationSid"] = params["smsApplicationSid"]; + if (params["addressSid"] !== undefined) + data["addressSid"] = params["addressSid"]; + if (params["email"] !== undefined) + data["email"] = params["email"]; + if (params["verificationType"] !== undefined) + data["verificationType"] = params["verificationType"]; + if (params["verificationDocumentSid"] !== undefined) + data["verificationDocumentSid"] = params["verificationDocumentSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new HostedNumberOrderInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + if (params["smsCapability"] === null || params["smsCapability"] === undefined) { + throw new Error('Required parameter "params[\'smsCapability\']" missing.'); + } + + let data: any = {}; + + + + data["phoneNumber"] = params["phoneNumber"]; + + data["smsCapability"] = serialize.bool(params["smsCapability"]); + if (params["accountSid"] !== undefined) + data["accountSid"] = params["accountSid"]; + if (params["friendlyName"] !== undefined) + data["friendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["uniqueName"] = params["uniqueName"]; + if (params["ccEmails"] !== undefined) + data["ccEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + if (params["smsUrl"] !== undefined) + data["smsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["smsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["smsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["smsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["statusCallbackUrl"] !== undefined) + data["statusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["statusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["smsApplicationSid"] !== undefined) + data["smsApplicationSid"] = params["smsApplicationSid"]; + if (params["addressSid"] !== undefined) + data["addressSid"] = params["addressSid"]; + if (params["email"] !== undefined) + data["email"] = params["email"]; + if (params["verificationType"] !== undefined) + data["verificationType"] = params["verificationType"]; + if (params["verificationDocumentSid"] !== undefined) + data["verificationDocumentSid"] = params["verificationDocumentSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<HostedNumberOrderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<HostedNumberOrderInstance> => ({ + ...response, + body: new HostedNumberOrderInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + + +interface HostedNumberOrderResource { + sid: string; + accountSid: string; + incomingPhoneNumberSid: string; + addressSid: string; + signingDocumentSid: string; + phoneNumber: string; + capabilities: PhoneNumberCapabilities; + friendlyName: string; + uniqueName: string; + status: HostedNumberOrderStatus; + failureReason: string; + dateCreated: Date; + dateUpdated: Date; + verificationAttempts: number; + email: string; + ccEmails: Array<string>; + url: string; + verificationType: HostedNumberOrderVerificationType; + verificationDocumentSid: string; + extension: string; + callDelay: number; + verificationCode: string; + verificationCallSids: Array<string>; +} + +export class HostedNumberOrderInstance { + + constructor(protected _version: V3, _payload: HostedNumberOrderResource) { + const payload = _payload; + this.sid = (payload.sid); + this.accountSid = (payload.accountSid); + this.incomingPhoneNumberSid = (payload.incomingPhoneNumberSid); + this.addressSid = (payload.addressSid); + this.signingDocumentSid = (payload.signingDocumentSid); + this.phoneNumber = (payload.phoneNumber); + this.capabilities = (payload.capabilities); + this.friendlyName = (payload.friendlyName); + this.uniqueName = (payload.uniqueName); + this.status = payload.status; + this.failureReason = (payload.failureReason); + this.dateCreated = deserialize.iso8601DateTime(payload.dateCreated); + this.dateUpdated = deserialize.iso8601DateTime(payload.dateUpdated); + this.verificationAttempts = deserialize.integer(payload.verificationAttempts); + this.email = (payload.email); + this.ccEmails = (payload.ccEmails); + this.url = (payload.url); + this.verificationType = payload.verificationType; + this.verificationDocumentSid = (payload.verificationDocumentSid); + this.extension = (payload.extension); + this.callDelay = deserialize.integer(payload.callDelay); + this.verificationCode = (payload.verificationCode); + this.verificationCallSids = (payload.verificationCallSids); + + } + + /** + * A 34 character string that uniquely identifies this HostedNumberOrder. + */ + sid: string; + /** + * A 34 character string that uniquely identifies the account. + */ + accountSid: string; + /** + * A 34 character string that uniquely identifies the [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the phone number being hosted. + */ + incomingPhoneNumberSid: string; + /** + * A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + */ + addressSid: string; + /** + * A 34 character string that uniquely identifies the [Authorization Document](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource) the user needs to sign. + */ + signingDocumentSid: string; + /** + * Phone number to be hosted. This must be in [E.164](https://en.wikipedia.org/wiki/E.164) format, e.g., +16175551212 + */ + phoneNumber: string; + capabilities: PhoneNumberCapabilities; + /** + * A 64 character string that is a human-readable text that describes this resource. + */ + friendlyName: string; + /** + * Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + */ + uniqueName: string; + status: HostedNumberOrderStatus; + /** + * A message that explains why a hosted_number_order went to status \"action-required\" + */ + failureReason: string; + /** + * The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The number of attempts made to verify ownership of the phone number that is being hosted. + */ + verificationAttempts: number; + /** + * Email of the owner of this phone number that is being hosted. + */ + email: string; + /** + * A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + */ + ccEmails: Array<string>; + /** + * The URL of this HostedNumberOrder. + */ + url: string; + verificationType: HostedNumberOrderVerificationType; + /** + * A 34 character string that uniquely identifies the Identity Document resource that represents the document for verifying ownership of the number to be hosted. + */ + verificationDocumentSid: string; + /** + * A numerical extension to be used when making the ownership verification call. + */ + extension: string; + /** + * A value between 0-30 specifying the number of seconds to delay initiating the ownership verification call. + */ + callDelay: number; + /** + * A verification code provided in the response for a user to enter when they pick up the phone call. + */ + verificationCode: string; + /** + * A list of 34 character strings that are unique identifiers for the calls placed as part of ownership verification. + */ + verificationCallSids: Array<string>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + incomingPhoneNumberSid: this.incomingPhoneNumberSid, + addressSid: this.addressSid, + signingDocumentSid: this.signingDocumentSid, + phoneNumber: this.phoneNumber, + capabilities: this.capabilities, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + status: this.status, + failureReason: this.failureReason, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + verificationAttempts: this.verificationAttempts, + email: this.email, + ccEmails: this.ccEmails, + url: this.url, + verificationType: this.verificationType, + verificationDocumentSid: this.verificationDocumentSid, + extension: this.extension, + callDelay: this.callDelay, + verificationCode: this.verificationCode, + verificationCallSids: this.verificationCallSids, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/oauth/V1.ts b/rest/oauth/V1.ts new file mode 100644 index 000000000..40772688b --- /dev/null +++ b/rest/oauth/V1.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Oauth + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import OauthBase from "../OauthBase"; +import Version from "../../base/Version"; +import { AuthorizeListInstance } from "./v1/authorize"; +import { TokenListInstance } from "./v1/token"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Oauth + * + * @param domain - The Twilio (Twilio.Oauth) domain + */ + constructor(domain: OauthBase) { + super(domain, "v1"); + } + + /** authorize - { Twilio.Oauth.V1.AuthorizeListInstance } resource */ + protected _authorize?: AuthorizeListInstance; + /** token - { Twilio.Oauth.V1.TokenListInstance } resource */ + protected _token?: TokenListInstance; + + /** Getter for authorize resource */ + get authorize(): AuthorizeListInstance { + this._authorize = this._authorize || AuthorizeListInstance(this); + return this._authorize; + } + + /** Getter for token resource */ + get token(): TokenListInstance { + this._token = this._token || TokenListInstance(this); + return this._token; + } + +} diff --git a/rest/oauth/V2.ts b/rest/oauth/V2.ts new file mode 100644 index 000000000..d9bfe3e40 --- /dev/null +++ b/rest/oauth/V2.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * User OAuth API + * User OAuth API + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import OauthBase from "../OauthBase"; +import Version from "../../base/Version"; +import { AuthorizeListInstance } from "./v2/authorize"; +import { TokenListInstance } from "./v2/token"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Oauth + * + * @param domain - The Twilio (Twilio.Oauth) domain + */ + constructor(domain: OauthBase) { + super(domain, "v2"); + } + + /** authorize - { Twilio.Oauth.V2.AuthorizeListInstance } resource */ + protected _authorize?: AuthorizeListInstance; + /** token - { Twilio.Oauth.V2.TokenListInstance } resource */ + protected _token?: TokenListInstance; + + /** Getter for authorize resource */ + get authorize(): AuthorizeListInstance { + this._authorize = this._authorize || AuthorizeListInstance(this); + return this._authorize; + } + + /** Getter for token resource */ + get token(): TokenListInstance { + this._token = this._token || TokenListInstance(this); + return this._token; + } + +} diff --git a/rest/oauth/v1/authorize.ts b/rest/oauth/v1/authorize.ts new file mode 100644 index 000000000..adfbed019 --- /dev/null +++ b/rest/oauth/v1/authorize.ts @@ -0,0 +1,231 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Oauth + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a AuthorizeInstance + */ +export interface AuthorizeListInstanceFetchOptions { + /** Response Type */ + "responseType"?: string; + /** The Client Identifier */ + "clientId"?: string; + /** The url to which response will be redirected to */ + "redirectUri"?: string; + /** The scope of the access request */ + "scope"?: string; + /** An opaque value which can be used to maintain state between the request and callback */ + "state"?: string; +} + + +export interface AuthorizeSolution { +} + +export interface AuthorizeListInstance { + _version: V1; + _solution: AuthorizeSolution; + _uri: string; + + + + /** + * Fetch a AuthorizeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance + */ + fetch(callback?: (error: Error | null, item?: AuthorizeInstance) => any): Promise<AuthorizeInstance>; + /** + * Fetch a AuthorizeInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance + */ + fetch(params: AuthorizeListInstanceFetchOptions, callback?: (error: Error | null, item?: AuthorizeInstance) => any): Promise<AuthorizeInstance>; + + /** + * Fetch a AuthorizeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizeInstance>) => any): Promise<ApiResponse<AuthorizeInstance>>; + /** + * Fetch a AuthorizeInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance with HTTP metadata + */ + fetchWithHttpInfo(params: AuthorizeListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse<AuthorizeInstance>) => any): Promise<ApiResponse<AuthorizeInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AuthorizeListInstance(version: V1): AuthorizeListInstance { + const instance = {} as AuthorizeListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/authorize`; + + instance.fetch = function fetch(params?: AuthorizeListInstanceFetchOptions | ((error: Error | null, items: AuthorizeInstance) => any), callback?: (error: Error | null, items: AuthorizeInstance) => any): Promise<AuthorizeInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["responseType"] !== undefined) + data["ResponseType"] = params["responseType"]; + if (params["clientId"] !== undefined) + data["ClientId"] = params["clientId"]; + if (params["redirectUri"] !== undefined) + data["RedirectUri"] = params["redirectUri"]; + if (params["scope"] !== undefined) + data["Scope"] = params["scope"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new AuthorizeInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params?: AuthorizeListInstanceFetchOptions | ((error: Error | null, items: ApiResponse<AuthorizeInstance>) => any), callback?: (error: Error | null, items: ApiResponse<AuthorizeInstance>) => any): Promise<ApiResponse<AuthorizeInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["responseType"] !== undefined) + data["ResponseType"] = params["responseType"]; + if (params["clientId"] !== undefined) + data["ClientId"] = params["clientId"]; + if (params["redirectUri"] !== undefined) + data["RedirectUri"] = params["redirectUri"]; + if (params["scope"] !== undefined) + data["Scope"] = params["scope"]; + if (params["state"] !== undefined) + data["State"] = params["state"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AuthorizeResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AuthorizeInstance> => ({ + ...response, + body: new AuthorizeInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface AuthorizePayload extends AuthorizeResource {} + +interface AuthorizeResource { + redirect_to: string; +} + +export class AuthorizeInstance { + + constructor(protected _version: V1, payload: AuthorizeResource) { + + this.redirectTo = (payload.redirect_to); + + } + + /** + * The callback URL + */ + redirectTo: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + redirectTo: this.redirectTo, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/oauth/v1/oauthAuthorizationServer.ts b/rest/oauth/v1/oauthAuthorizationServer.ts new file mode 100644 index 000000000..a4236812b --- /dev/null +++ b/rest/oauth/v1/oauthAuthorizationServer.ts @@ -0,0 +1,171 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Oauth + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface OauthAuthorizationServerSolution { +} + +export interface OauthAuthorizationServerListInstance { + _version: V1; + _solution: OauthAuthorizationServerSolution; + _uri: string; + + + + /** + * Fetch a OauthAuthorizationServerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OauthAuthorizationServerInstance + */ + fetch(callback?: (error: Error | null, item?: OauthAuthorizationServerInstance) => any): Promise<OauthAuthorizationServerInstance> + + /** + * Fetch a OauthAuthorizationServerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OauthAuthorizationServerInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OauthAuthorizationServerInstance>) => any): Promise<ApiResponse<OauthAuthorizationServerInstance>> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OauthAuthorizationServerListInstance(version: V1): OauthAuthorizationServerListInstance { + const instance = {} as OauthAuthorizationServerListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/oauth-authorization-server`; + + instance.fetch = function fetch( callback?: (error: Error | null, items: OauthAuthorizationServerInstance) => any): Promise<OauthAuthorizationServerInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OauthAuthorizationServerInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<OauthAuthorizationServerInstance>) => any): Promise<ApiResponse<OauthAuthorizationServerInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<OauthAuthorizationServerResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<OauthAuthorizationServerInstance> => ({ + ...response, + body: new OauthAuthorizationServerInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface OauthAuthorizationServerPayload extends OauthAuthorizationServerResource {} + +interface OauthAuthorizationServerResource { + issuer: string; + authorization_endpoint: string; + token_endpoint: string; + response_types_supported: Array<string>; + grant_types_supported: Array<string>; + code_challenge_methods_supported: Array<string>; + token_endpoint_auth_methods_supported: Array<string>; +} + +export class OauthAuthorizationServerInstance { + + constructor(protected _version: V1, payload: OauthAuthorizationServerResource) { + + this.issuer = (payload.issuer); + this.authorizationEndpoint = (payload.authorization_endpoint); + this.tokenEndpoint = (payload.token_endpoint); + this.responseTypesSupported = (payload.response_types_supported); + this.grantTypesSupported = (payload.grant_types_supported); + this.codeChallengeMethodsSupported = (payload.code_challenge_methods_supported); + this.tokenEndpointAuthMethodsSupported = (payload.token_endpoint_auth_methods_supported); + + } + + issuer: string; + authorizationEndpoint: string; + tokenEndpoint: string; + responseTypesSupported: Array<string>; + grantTypesSupported: Array<string>; + codeChallengeMethodsSupported: Array<string>; + tokenEndpointAuthMethodsSupported: Array<string>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + issuer: this.issuer, + authorizationEndpoint: this.authorizationEndpoint, + tokenEndpoint: this.tokenEndpoint, + responseTypesSupported: this.responseTypesSupported, + grantTypesSupported: this.grantTypesSupported, + codeChallengeMethodsSupported: this.codeChallengeMethodsSupported, + tokenEndpointAuthMethodsSupported: this.tokenEndpointAuthMethodsSupported, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/oauth/v1/token.ts b/rest/oauth/v1/token.ts new file mode 100644 index 000000000..1ec0ea350 --- /dev/null +++ b/rest/oauth/v1/token.ts @@ -0,0 +1,270 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Oauth + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a TokenInstance + */ +export interface TokenListInstanceCreateOptions { + /** Grant type is a credential representing resource owner\\\'s authorization which can be used by client to obtain access token. */ + "grantType": string; + /** A 34 character string that uniquely identifies this OAuth App. */ + "clientId": string; + /** The credential for confidential OAuth App. */ + "clientSecret"?: string; + /** JWT token related to the authorization code grant type. */ + "code"?: string; + /** The redirect uri */ + "redirectUri"?: string; + /** The targeted audience uri */ + "audience"?: string; + /** JWT token related to refresh access token. */ + "refreshToken"?: string; + /** The scope of token */ + "scope"?: string; +} + + +export interface TokenSolution { +} + +export interface TokenListInstance { + _version: V1; + _solution: TokenSolution; + _uri: string; + + + + /** + * Create a TokenInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance + */ + create(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, item?: TokenInstance) => any): Promise<TokenInstance>; + + /** + * Create a TokenInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance with HTTP metadata + */ + createWithHttpInfo(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TokenInstance>) => any): Promise<ApiResponse<TokenInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TokenListInstance(version: V1): TokenListInstance { + const instance = {} as TokenListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/token`; + + instance.create = function create(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, items: TokenInstance) => any): Promise<TokenInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["grantType"] === null || params["grantType"] === undefined) { + throw new Error('Required parameter "params[\'grantType\']" missing.'); + } + + if (params["clientId"] === null || params["clientId"] === undefined) { + throw new Error('Required parameter "params[\'clientId\']" missing.'); + } + + let data: any = {}; + + + + data["GrantType"] = params["grantType"]; + + data["ClientId"] = params["clientId"]; + if (params["clientSecret"] !== undefined) + data["ClientSecret"] = params["clientSecret"]; + if (params["code"] !== undefined) + data["Code"] = params["code"]; + if (params["redirectUri"] !== undefined) + data["RedirectUri"] = params["redirectUri"]; + if (params["audience"] !== undefined) + data["Audience"] = params["audience"]; + if (params["refreshToken"] !== undefined) + data["RefreshToken"] = params["refreshToken"]; + if (params["scope"] !== undefined) + data["Scope"] = params["scope"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TokenInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<TokenInstance>) => any): Promise<ApiResponse<TokenInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["grantType"] === null || params["grantType"] === undefined) { + throw new Error('Required parameter "params[\'grantType\']" missing.'); + } + + if (params["clientId"] === null || params["clientId"] === undefined) { + throw new Error('Required parameter "params[\'clientId\']" missing.'); + } + + let data: any = {}; + + + + data["GrantType"] = params["grantType"]; + + data["ClientId"] = params["clientId"]; + if (params["clientSecret"] !== undefined) + data["ClientSecret"] = params["clientSecret"]; + if (params["code"] !== undefined) + data["Code"] = params["code"]; + if (params["redirectUri"] !== undefined) + data["RedirectUri"] = params["redirectUri"]; + if (params["audience"] !== undefined) + data["Audience"] = params["audience"]; + if (params["refreshToken"] !== undefined) + data["RefreshToken"] = params["refreshToken"]; + if (params["scope"] !== undefined) + data["Scope"] = params["scope"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TokenResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TokenInstance> => ({ + ...response, + body: new TokenInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TokenPayload extends TokenResource {} + +interface TokenResource { + access_token: string; + refresh_token: string; + id_token: string; + token_type: string; + expires_in: number; +} + +export class TokenInstance { + + constructor(protected _version: V1, payload: TokenResource) { + + this.accessToken = (payload.access_token); + this.refreshToken = (payload.refresh_token); + this.idToken = (payload.id_token); + this.tokenType = (payload.token_type); + this.expiresIn = (payload.expires_in); + + } + + /** + * Token which carries the necessary information to access a Twilio resource directly. + */ + accessToken: string; + /** + * Token which carries the information necessary to get a new access token. + */ + refreshToken: string; + /** + * Token which carries the information necessary of user profile. + */ + idToken: string; + /** + * Token type + */ + tokenType: string; + expiresIn: number; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accessToken: this.accessToken, + refreshToken: this.refreshToken, + idToken: this.idToken, + tokenType: this.tokenType, + expiresIn: this.expiresIn, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/oauth/v2/authorize.ts b/rest/oauth/v2/authorize.ts new file mode 100644 index 000000000..d5c498a5a --- /dev/null +++ b/rest/oauth/v2/authorize.ts @@ -0,0 +1,243 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * User OAuth API + * User OAuth API + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a AuthorizeInstance + */ +export interface AuthorizeListInstanceFetchOptions { + /** */ + "responseType"?: string; + /** */ + "clientId"?: string; + /** */ + "redirectUri"?: string; + /** */ + "scope"?: string; + /** */ + "state"?: string; + /** */ + "codeChallenge"?: string; + /** */ + "codeChallengeMethod"?: 'S256'; +} + + +export interface AuthorizeSolution { +} + +export interface AuthorizeListInstance { + _version: V2; + _solution: AuthorizeSolution; + _uri: string; + + + + /** + * Fetch a AuthorizeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance + */ + fetch(callback?: (error: Error | null, item?: AuthorizeInstance) => any): Promise<AuthorizeInstance>; + /** + * Fetch a AuthorizeInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance + */ + fetch(params: AuthorizeListInstanceFetchOptions, callback?: (error: Error | null, item?: AuthorizeInstance) => any): Promise<AuthorizeInstance>; + + /** + * Fetch a AuthorizeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizeInstance>) => any): Promise<ApiResponse<AuthorizeInstance>>; + /** + * Fetch a AuthorizeInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance with HTTP metadata + */ + fetchWithHttpInfo(params: AuthorizeListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse<AuthorizeInstance>) => any): Promise<ApiResponse<AuthorizeInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AuthorizeListInstance(version: V2): AuthorizeListInstance { + const instance = {} as AuthorizeListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/authorize`; + + instance.fetch = function fetch(params?: AuthorizeListInstanceFetchOptions | ((error: Error | null, items: AuthorizeInstance) => any), callback?: (error: Error | null, items: AuthorizeInstance) => any): Promise<AuthorizeInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["responseType"] !== undefined) + data["response_type"] = params["responseType"]; + if (params["clientId"] !== undefined) + data["client_id"] = params["clientId"]; + if (params["redirectUri"] !== undefined) + data["redirect_uri"] = params["redirectUri"]; + if (params["scope"] !== undefined) + data["scope"] = params["scope"]; + if (params["state"] !== undefined) + data["state"] = params["state"]; + if (params["codeChallenge"] !== undefined) + data["code_challenge"] = params["codeChallenge"]; + if (params["codeChallengeMethod"] !== undefined) + data["code_challenge_method"] = params["codeChallengeMethod"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new AuthorizeInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params?: AuthorizeListInstanceFetchOptions | ((error: Error | null, items: ApiResponse<AuthorizeInstance>) => any), callback?: (error: Error | null, items: ApiResponse<AuthorizeInstance>) => any): Promise<ApiResponse<AuthorizeInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["responseType"] !== undefined) + data["response_type"] = params["responseType"]; + if (params["clientId"] !== undefined) + data["client_id"] = params["clientId"]; + if (params["redirectUri"] !== undefined) + data["redirect_uri"] = params["redirectUri"]; + if (params["scope"] !== undefined) + data["scope"] = params["scope"]; + if (params["state"] !== undefined) + data["state"] = params["state"]; + if (params["codeChallenge"] !== undefined) + data["code_challenge"] = params["codeChallenge"]; + if (params["codeChallengeMethod"] !== undefined) + data["code_challenge_method"] = params["codeChallengeMethod"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AuthorizeResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AuthorizeInstance> => ({ + ...response, + body: new AuthorizeInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface AuthorizePayload extends AuthorizeResource {} + +interface AuthorizeResource { + redirect_to: string; +} + +export class AuthorizeInstance { + + constructor(protected _version: V2, payload: AuthorizeResource) { + + this.redirectTo = (payload.redirect_to); + + } + + /** + * The callback URL + */ + redirectTo: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + redirectTo: this.redirectTo, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/oauth/v2/token.ts b/rest/oauth/v2/token.ts new file mode 100644 index 000000000..a35c54d4b --- /dev/null +++ b/rest/oauth/v2/token.ts @@ -0,0 +1,288 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * User OAuth API + * User OAuth API + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a TokenInstance + */ +export interface TokenListInstanceCreateOptions { + /** Optional Account SID to perform on behalf of requests. */ + "accountSid"?: string; + /** Grant type is a credential representing resource owner\\\'s authorization which can be used by client to obtain access token. */ + "grantType"?: string; + /** A 34 character string that uniquely identifies this OAuth App. */ + "clientId"?: string; + /** The credential for confidential OAuth App. */ + "clientSecret"?: string; + /** JWT token related to the authorization code grant type. */ + "code"?: string; + /** The redirect uri */ + "redirectUri"?: string; + /** The targeted audience uri */ + "audience"?: string; + /** JWT token related to refresh access token. */ + "refreshToken"?: string; + /** The scope of token */ + "scope"?: string; + /** The PKCE code verifier used to generate the code_challenge in the authorization request. */ + "codeVerifier"?: string; +} + + +export interface TokenSolution { +} + +export interface TokenListInstance { + _version: V2; + _solution: TokenSolution; + _uri: string; + + + + /** + * Create a TokenInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance + */ + create(callback?: (error: Error | null, item?: TokenInstance) => any): Promise<TokenInstance>; + /** + * Create a TokenInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance + */ + create(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, item?: TokenInstance) => any): Promise<TokenInstance>; + + /** + * Create a TokenInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TokenInstance>) => any): Promise<ApiResponse<TokenInstance>>; + /** + * Create a TokenInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance with HTTP metadata + */ + createWithHttpInfo(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TokenInstance>) => any): Promise<ApiResponse<TokenInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TokenListInstance(version: V2): TokenListInstance { + const instance = {} as TokenListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/token`; + + instance.create = function create(params?: TokenListInstanceCreateOptions | ((error: Error | null, items: TokenInstance) => any), callback?: (error: Error | null, items: TokenInstance) => any): Promise<TokenInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["accountSid"] !== undefined) + data["account_sid"] = params["accountSid"]; + + if (params["grantType"] !== undefined) + data["grant_type"] = params["grantType"]; + if (params["clientId"] !== undefined) + data["client_id"] = params["clientId"]; + if (params["clientSecret"] !== undefined) + data["client_secret"] = params["clientSecret"]; + if (params["code"] !== undefined) + data["code"] = params["code"]; + if (params["redirectUri"] !== undefined) + data["redirect_uri"] = params["redirectUri"]; + if (params["audience"] !== undefined) + data["audience"] = params["audience"]; + if (params["refreshToken"] !== undefined) + data["refresh_token"] = params["refreshToken"]; + if (params["scope"] !== undefined) + data["scope"] = params["scope"]; + if (params["codeVerifier"] !== undefined) + data["code_verifier"] = params["codeVerifier"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TokenInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: TokenListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<TokenInstance>) => any), callback?: (error: Error | null, items: ApiResponse<TokenInstance>) => any): Promise<ApiResponse<TokenInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["accountSid"] !== undefined) + data["account_sid"] = params["accountSid"]; + + if (params["grantType"] !== undefined) + data["grant_type"] = params["grantType"]; + if (params["clientId"] !== undefined) + data["client_id"] = params["clientId"]; + if (params["clientSecret"] !== undefined) + data["client_secret"] = params["clientSecret"]; + if (params["code"] !== undefined) + data["code"] = params["code"]; + if (params["redirectUri"] !== undefined) + data["redirect_uri"] = params["redirectUri"]; + if (params["audience"] !== undefined) + data["audience"] = params["audience"]; + if (params["refreshToken"] !== undefined) + data["refresh_token"] = params["refreshToken"]; + if (params["scope"] !== undefined) + data["scope"] = params["scope"]; + if (params["codeVerifier"] !== undefined) + data["code_verifier"] = params["codeVerifier"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TokenResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TokenInstance> => ({ + ...response, + body: new TokenInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TokenPayload extends TokenResource {} + +interface TokenResource { + access_token: string; + refresh_token: string; + id_token: string; + token_type: string; + expires_in: number; +} + +export class TokenInstance { + + constructor(protected _version: V2, payload: TokenResource) { + + this.accessToken = (payload.access_token); + this.refreshToken = (payload.refresh_token); + this.idToken = (payload.id_token); + this.tokenType = (payload.token_type); + this.expiresIn = (payload.expires_in); + + } + + /** + * Token which carries the necessary information to access a Twilio resource directly. + */ + accessToken: string; + /** + * Token which carries the information necessary to get a new access token. + */ + refreshToken: string; + /** + * Token which carries the information necessary of user profile. + */ + idToken: string; + /** + * Token type + */ + tokenType: string; + expiresIn: number; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accessToken: this.accessToken, + refreshToken: this.refreshToken, + idToken: this.idToken, + tokenType: this.tokenType, + expiresIn: this.expiresIn, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/preview/HostedNumbers.ts b/rest/preview/HostedNumbers.ts new file mode 100644 index 000000000..bed391401 --- /dev/null +++ b/rest/preview/HostedNumbers.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import PreviewBase from "../PreviewBase"; +import Version from "../../base/Version"; +import { AuthorizationDocumentListInstance } from "./hosted_numbers/authorizationDocument"; +import { HostedNumberOrderListInstance } from "./hosted_numbers/hostedNumberOrder"; + +export default class HostedNumbers extends Version { + /** + * Initialize the HostedNumbers version of Preview + * + * @param domain - The Twilio (Twilio.Preview) domain + */ + constructor(domain: PreviewBase) { + super(domain, "HostedNumbers"); + } + + /** authorizationDocuments - { Twilio.Preview.HostedNumbers.AuthorizationDocumentListInstance } resource */ + protected _authorizationDocuments?: AuthorizationDocumentListInstance; + /** hostedNumberOrders - { Twilio.Preview.HostedNumbers.HostedNumberOrderListInstance } resource */ + protected _hostedNumberOrders?: HostedNumberOrderListInstance; + + /** Getter for authorizationDocuments resource */ + get authorizationDocuments(): AuthorizationDocumentListInstance { + this._authorizationDocuments = this._authorizationDocuments || AuthorizationDocumentListInstance(this); + return this._authorizationDocuments; + } + + /** Getter for hostedNumberOrders resource */ + get hostedNumberOrders(): HostedNumberOrderListInstance { + this._hostedNumberOrders = this._hostedNumberOrders || HostedNumberOrderListInstance(this); + return this._hostedNumberOrders; + } + +} diff --git a/rest/preview/Marketplace.ts b/rest/preview/Marketplace.ts new file mode 100644 index 000000000..b37655b14 --- /dev/null +++ b/rest/preview/Marketplace.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import PreviewBase from "../PreviewBase"; +import Version from "../../base/Version"; +import { AvailableAddOnListInstance } from "./marketplace/availableAddOn"; +import { InstalledAddOnListInstance } from "./marketplace/installedAddOn"; + +export default class Marketplace extends Version { + /** + * Initialize the Marketplace version of Preview + * + * @param domain - The Twilio (Twilio.Preview) domain + */ + constructor(domain: PreviewBase) { + super(domain, "marketplace"); + } + + /** availableAddOns - { Twilio.Preview.Marketplace.AvailableAddOnListInstance } resource */ + protected _availableAddOns?: AvailableAddOnListInstance; + /** installedAddOns - { Twilio.Preview.Marketplace.InstalledAddOnListInstance } resource */ + protected _installedAddOns?: InstalledAddOnListInstance; + + /** Getter for availableAddOns resource */ + get availableAddOns(): AvailableAddOnListInstance { + this._availableAddOns = this._availableAddOns || AvailableAddOnListInstance(this); + return this._availableAddOns; + } + + /** Getter for installedAddOns resource */ + get installedAddOns(): InstalledAddOnListInstance { + this._installedAddOns = this._installedAddOns || InstalledAddOnListInstance(this); + return this._installedAddOns; + } + +} diff --git a/rest/preview/Wireless.ts b/rest/preview/Wireless.ts new file mode 100644 index 000000000..df210b1fe --- /dev/null +++ b/rest/preview/Wireless.ts @@ -0,0 +1,56 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import PreviewBase from "../PreviewBase"; +import Version from "../../base/Version"; +import { CommandListInstance } from "./wireless/command"; +import { RatePlanListInstance } from "./wireless/ratePlan"; +import { SimListInstance } from "./wireless/sim"; + +export default class Wireless extends Version { + /** + * Initialize the Wireless version of Preview + * + * @param domain - The Twilio (Twilio.Preview) domain + */ + constructor(domain: PreviewBase) { + super(domain, "wireless"); + } + + /** commands - { Twilio.Preview.Wireless.CommandListInstance } resource */ + protected _commands?: CommandListInstance; + /** ratePlans - { Twilio.Preview.Wireless.RatePlanListInstance } resource */ + protected _ratePlans?: RatePlanListInstance; + /** sims - { Twilio.Preview.Wireless.SimListInstance } resource */ + protected _sims?: SimListInstance; + + /** Getter for commands resource */ + get commands(): CommandListInstance { + this._commands = this._commands || CommandListInstance(this); + return this._commands; + } + + /** Getter for ratePlans resource */ + get ratePlans(): RatePlanListInstance { + this._ratePlans = this._ratePlans || RatePlanListInstance(this); + return this._ratePlans; + } + + /** Getter for sims resource */ + get sims(): SimListInstance { + this._sims = this._sims || SimListInstance(this); + return this._sims; + } + +} diff --git a/rest/preview/hosted_numbers/authorizationDocument.ts b/rest/preview/hosted_numbers/authorizationDocument.ts new file mode 100644 index 000000000..bfad2d1d9 --- /dev/null +++ b/rest/preview/hosted_numbers/authorizationDocument.ts @@ -0,0 +1,961 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import HostedNumbers from "../HostedNumbers"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { DependentHostedNumberOrderListInstance } from "./authorizationDocument/dependentHostedNumberOrder"; + + +/** + * Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + */ +export type AuthorizationDocumentStatus = 'opened'|'signing'|'signed'|'canceled'|'failed'; + + + +/** + * Options to pass to update a AuthorizationDocumentInstance + */ +export interface AuthorizationDocumentContextUpdateOptions { + /** A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio\\\'s platform. */ + "hostedNumberOrderSids"?: Array<string>; + /** A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. */ + "addressSid"?: string; + /** Email that this AuthorizationDocument will be sent to for signing. */ + "email"?: string; + /** Email recipients who will be informed when an Authorization Document has been sent and signed */ + "ccEmails"?: Array<string>; + /** */ + "status"?: AuthorizationDocumentStatus; + /** The title of the person authorized to sign the Authorization Document for this phone number. */ + "contactTitle"?: string; + /** The contact phone number of the person authorized to sign the Authorization Document. */ + "contactPhoneNumber"?: string; +} + +/** + * Options to pass to create a AuthorizationDocumentInstance + */ +export interface AuthorizationDocumentListInstanceCreateOptions { + /** A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio\\\'s platform. */ + "hostedNumberOrderSids": Array<string>; + /** A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. */ + "addressSid": string; + /** Email that this AuthorizationDocument will be sent to for signing. */ + "email": string; + /** The title of the person authorized to sign the Authorization Document for this phone number. */ + "contactTitle": string; + /** The contact phone number of the person authorized to sign the Authorization Document. */ + "contactPhoneNumber": string; + /** Email recipients who will be informed when an Authorization Document has been sent and signed. */ + "ccEmails"?: Array<string>; +} + +/** + * Options to pass to each + */ +export interface AuthorizationDocumentListInstanceEachOptions { + /** Email that this AuthorizationDocument will be sent to for signing. */ + "email"?: string; + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: AuthorizationDocumentStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AuthorizationDocumentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AuthorizationDocumentListInstanceOptions { + /** Email that this AuthorizationDocument will be sent to for signing. */ + "email"?: string; + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: AuthorizationDocumentStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AuthorizationDocumentListInstancePageOptions { + /** Email that this AuthorizationDocument will be sent to for signing. */ + "email"?: string; + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: AuthorizationDocumentStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AuthorizationDocumentContext { + dependentHostedNumberOrders: DependentHostedNumberOrderListInstance; + + /** + * Fetch a AuthorizationDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance + */ + fetch(callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance> + + /** + * Fetch a AuthorizationDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>> + + /** + * Update a AuthorizationDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance + */ + update(callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance>; + /** + * Update a AuthorizationDocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance + */ + update(params: AuthorizationDocumentContextUpdateOptions, callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance>; + + /** + * Update a AuthorizationDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>>; + /** + * Update a AuthorizationDocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(params: AuthorizationDocumentContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AuthorizationDocumentContextSolution { + "sid": string; +} + +export class AuthorizationDocumentContextImpl implements AuthorizationDocumentContext { + protected _solution: AuthorizationDocumentContextSolution; + protected _uri: string; + + protected _dependentHostedNumberOrders?: DependentHostedNumberOrderListInstance; + + constructor(protected _version: HostedNumbers, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/AuthorizationDocuments/${sid}`; + } + + get dependentHostedNumberOrders(): DependentHostedNumberOrderListInstance { + this._dependentHostedNumberOrders = this._dependentHostedNumberOrders || DependentHostedNumberOrderListInstance(this._version, this._solution.sid); + return this._dependentHostedNumberOrders; + } + + fetch(callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AuthorizationDocumentInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AuthorizationDocumentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AuthorizationDocumentInstance> => ({ + ...response, + body: new AuthorizationDocumentInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: AuthorizationDocumentContextUpdateOptions | ((error: Error | null, item?: AuthorizationDocumentInstance) => any),callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["hostedNumberOrderSids"] !== undefined) + data["HostedNumberOrderSids"] = serialize.map(params["hostedNumberOrderSids"], (e: string) => (e)); + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["contactTitle"] !== undefined) + data["ContactTitle"] = params["contactTitle"]; + if (params["contactPhoneNumber"] !== undefined) + data["ContactPhoneNumber"] = params["contactPhoneNumber"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AuthorizationDocumentInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: AuthorizationDocumentContextUpdateOptions | ((error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["hostedNumberOrderSids"] !== undefined) + data["HostedNumberOrderSids"] = serialize.map(params["hostedNumberOrderSids"], (e: string) => (e)); + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["contactTitle"] !== undefined) + data["ContactTitle"] = params["contactTitle"]; + if (params["contactPhoneNumber"] !== undefined) + data["ContactPhoneNumber"] = params["contactPhoneNumber"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<AuthorizationDocumentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<AuthorizationDocumentInstance> => ({ + ...response, + body: new AuthorizationDocumentInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AuthorizationDocumentPayload extends TwilioResponsePayload { + items: AuthorizationDocumentResource[]; +} + +interface AuthorizationDocumentResource { + sid: string; + address_sid: string; + status: AuthorizationDocumentStatus; + email: string; + cc_emails: Array<string>; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class AuthorizationDocumentInstance { + protected _solution: AuthorizationDocumentContextSolution; + protected _context?: AuthorizationDocumentContext; + + constructor(protected _version: HostedNumbers, payload: AuthorizationDocumentResource, sid?: string) { + + this.sid = (payload.sid); + this.addressSid = (payload.address_sid); + this.status = payload.status; + this.email = (payload.email); + this.ccEmails = (payload.cc_emails); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this AuthorizationDocument. + */ + sid: string; + /** + * A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + */ + addressSid: string; + status: AuthorizationDocumentStatus; + /** + * Email that this AuthorizationDocument will be sent to for signing. + */ + email: string; + /** + * Email recipients who will be informed when an Authorization Document has been sent and signed. + */ + ccEmails: Array<string>; + /** + * The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + url: string; + links: Record<string, string>; + + private get _proxy(): AuthorizationDocumentContext { + this._context = this._context || new AuthorizationDocumentContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a AuthorizationDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance + */ + fetch(callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AuthorizationDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a AuthorizationDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance + */ + update(callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance>; + /** + * Update a AuthorizationDocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance + */ + update(params: AuthorizationDocumentContextUpdateOptions, callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance>; + + update(params?: any, callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a AuthorizationDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>>; + /** + * Update a AuthorizationDocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(params: AuthorizationDocumentContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the dependentHostedNumberOrders. + */ + dependentHostedNumberOrders(): DependentHostedNumberOrderListInstance { + return this._proxy.dependentHostedNumberOrders; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + addressSid: this.addressSid, + status: this.status, + email: this.email, + ccEmails: this.ccEmails, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AuthorizationDocumentSolution { +} + +export interface AuthorizationDocumentListInstance { + _version: HostedNumbers; + _solution: AuthorizationDocumentSolution; + _uri: string; + + (sid: string, ): AuthorizationDocumentContext; + get(sid: string, ): AuthorizationDocumentContext; + + + + + + + /** + * Create a AuthorizationDocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance + */ + create(params: AuthorizationDocumentListInstanceCreateOptions, callback?: (error: Error | null, item?: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance>; + + /** + * Create a AuthorizationDocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizationDocumentInstance with HTTP metadata + */ + createWithHttpInfo(params: AuthorizationDocumentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>>; + + + + + /** + * Streams AuthorizationDocumentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AuthorizationDocumentInstance, done: (err?: Error) => void) => void): void; + each(params: AuthorizationDocumentListInstanceEachOptions, callback?: (item: AuthorizationDocumentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AuthorizationDocumentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AuthorizationDocumentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AuthorizationDocumentListInstanceEachOptions, callback?: (item: AuthorizationDocumentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AuthorizationDocumentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AuthorizationDocumentPage) => any): Promise<AuthorizationDocumentPage>; + /** + * Retrieve a single target page of AuthorizationDocumentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentPage>) => any): Promise<ApiResponse<AuthorizationDocumentPage>>; + /** + * Lists AuthorizationDocumentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AuthorizationDocumentInstance[]) => any): Promise<AuthorizationDocumentInstance[]>; + list(params: AuthorizationDocumentListInstanceOptions, callback?: (error: Error | null, items: AuthorizationDocumentInstance[]) => any): Promise<AuthorizationDocumentInstance[]>; + /** + * Lists AuthorizationDocumentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentInstance[]>) => any): Promise<ApiResponse<AuthorizationDocumentInstance[]>>; + listWithHttpInfo(params: AuthorizationDocumentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentInstance[]>) => any): Promise<ApiResponse<AuthorizationDocumentInstance[]>>; + /** + * Retrieve a single page of AuthorizationDocumentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AuthorizationDocumentPage) => any): Promise<AuthorizationDocumentPage>; + page(params: AuthorizationDocumentListInstancePageOptions, callback?: (error: Error | null, items: AuthorizationDocumentPage) => any): Promise<AuthorizationDocumentPage>; + /** + * Retrieve a single page of AuthorizationDocumentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AuthorizationDocumentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentPage>) => any): Promise<ApiResponse<AuthorizationDocumentPage>>; + pageWithHttpInfo(params: AuthorizationDocumentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentPage>) => any): Promise<ApiResponse<AuthorizationDocumentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AuthorizationDocumentListInstance(version: HostedNumbers): AuthorizationDocumentListInstance { + const instance = ((sid, ) => instance.get(sid, )) as AuthorizationDocumentListInstance; + + instance.get = function get(sid, ): AuthorizationDocumentContext { + return new AuthorizationDocumentContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/AuthorizationDocuments`; + + instance.create = function create(params: AuthorizationDocumentListInstanceCreateOptions, callback?: (error: Error | null, items: AuthorizationDocumentInstance) => any): Promise<AuthorizationDocumentInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["hostedNumberOrderSids"] === null || params["hostedNumberOrderSids"] === undefined) { + throw new Error('Required parameter "params[\'hostedNumberOrderSids\']" missing.'); + } + + if (params["addressSid"] === null || params["addressSid"] === undefined) { + throw new Error('Required parameter "params[\'addressSid\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + if (params["contactTitle"] === null || params["contactTitle"] === undefined) { + throw new Error('Required parameter "params[\'contactTitle\']" missing.'); + } + + if (params["contactPhoneNumber"] === null || params["contactPhoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'contactPhoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["HostedNumberOrderSids"] = serialize.map(params["hostedNumberOrderSids"], (e: string) => (e)); + + data["AddressSid"] = params["addressSid"]; + + data["Email"] = params["email"]; + + data["ContactTitle"] = params["contactTitle"]; + + data["ContactPhoneNumber"] = params["contactPhoneNumber"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AuthorizationDocumentInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AuthorizationDocumentListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentInstance>) => any): Promise<ApiResponse<AuthorizationDocumentInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["hostedNumberOrderSids"] === null || params["hostedNumberOrderSids"] === undefined) { + throw new Error('Required parameter "params[\'hostedNumberOrderSids\']" missing.'); + } + + if (params["addressSid"] === null || params["addressSid"] === undefined) { + throw new Error('Required parameter "params[\'addressSid\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + if (params["contactTitle"] === null || params["contactTitle"] === undefined) { + throw new Error('Required parameter "params[\'contactTitle\']" missing.'); + } + + if (params["contactPhoneNumber"] === null || params["contactPhoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'contactPhoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["HostedNumberOrderSids"] = serialize.map(params["hostedNumberOrderSids"], (e: string) => (e)); + + data["AddressSid"] = params["addressSid"]; + + data["Email"] = params["email"]; + + data["ContactTitle"] = params["contactTitle"]; + + data["ContactPhoneNumber"] = params["contactPhoneNumber"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<AuthorizationDocumentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<AuthorizationDocumentInstance> => ({ + ...response, + body: new AuthorizationDocumentInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AuthorizationDocumentListInstancePageOptions | ((error: Error | null, items: AuthorizationDocumentPage) => any), callback?: (error: Error | null, items: AuthorizationDocumentPage) => any): Promise<AuthorizationDocumentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AuthorizationDocumentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AuthorizationDocumentPage) => any): Promise<AuthorizationDocumentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AuthorizationDocumentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AuthorizationDocumentListInstancePageOptions | ((error: Error | null, items: ApiResponse<AuthorizationDocumentPage>) => any), callback?: (error: Error | null, items: ApiResponse<AuthorizationDocumentPage>) => any): Promise<ApiResponse<AuthorizationDocumentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AuthorizationDocumentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthorizationDocumentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AuthorizationDocumentPage>) => any): Promise<ApiResponse<AuthorizationDocumentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AuthorizationDocumentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AuthorizationDocumentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AuthorizationDocumentPage extends Page<HostedNumbers, AuthorizationDocumentPayload, AuthorizationDocumentResource, AuthorizationDocumentInstance> { +/** +* Initialize the AuthorizationDocumentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: HostedNumbers, response: Response<string>, solution: AuthorizationDocumentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AuthorizationDocumentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AuthorizationDocumentResource): AuthorizationDocumentInstance { + + return new AuthorizationDocumentInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/preview/hosted_numbers/authorizationDocument/dependentHostedNumberOrder.ts b/rest/preview/hosted_numbers/authorizationDocument/dependentHostedNumberOrder.ts new file mode 100644 index 000000000..bf7cd40dd --- /dev/null +++ b/rest/preview/hosted_numbers/authorizationDocument/dependentHostedNumberOrder.ts @@ -0,0 +1,583 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import HostedNumbers from "../../HostedNumbers"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../interfaces"; + + +/** + * Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + */ +export type DependentHostedNumberOrderStatus = 'twilio-processing'|'received'|'pending-verification'|'verified'|'pending-loa'|'carrier-processing'|'testing'|'completed'|'failed'|'action-required'; + +/** + * The method used for verifying ownership of the number to be hosted. One of phone-call (default) or phone-bill. + */ +export type DependentHostedNumberOrderVerificationType = 'phone-call'|'phone-bill'; + + +/** + * Options to pass to each + */ +export interface DependentHostedNumberOrderListInstanceEachOptions { + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: DependentHostedNumberOrderStatus; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; + /** Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DependentHostedNumberOrderListInstanceOptions { + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: DependentHostedNumberOrderStatus; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; + /** Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DependentHostedNumberOrderListInstancePageOptions { + /** Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. */ + "status"?: DependentHostedNumberOrderStatus; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; + /** Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface DependentHostedNumberOrderSolution { + signingDocumentSid: string; +} + +export interface DependentHostedNumberOrderListInstance { + _version: HostedNumbers; + _solution: DependentHostedNumberOrderSolution; + _uri: string; + + + + + /** + * Streams DependentHostedNumberOrderInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + each(params: DependentHostedNumberOrderListInstanceEachOptions, callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DependentHostedNumberOrderInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DependentHostedNumberOrderListInstanceEachOptions, callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DependentHostedNumberOrderInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage>; + /** + * Retrieve a single target page of DependentHostedNumberOrderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderPage>) => any): Promise<ApiResponse<DependentHostedNumberOrderPage>>; + /** + * Lists DependentHostedNumberOrderInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DependentHostedNumberOrderInstance[]) => any): Promise<DependentHostedNumberOrderInstance[]>; + list(params: DependentHostedNumberOrderListInstanceOptions, callback?: (error: Error | null, items: DependentHostedNumberOrderInstance[]) => any): Promise<DependentHostedNumberOrderInstance[]>; + /** + * Lists DependentHostedNumberOrderInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderInstance[]>) => any): Promise<ApiResponse<DependentHostedNumberOrderInstance[]>>; + listWithHttpInfo(params: DependentHostedNumberOrderListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderInstance[]>) => any): Promise<ApiResponse<DependentHostedNumberOrderInstance[]>>; + /** + * Retrieve a single page of DependentHostedNumberOrderInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage>; + page(params: DependentHostedNumberOrderListInstancePageOptions, callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage>; + /** + * Retrieve a single page of DependentHostedNumberOrderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DependentHostedNumberOrderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderPage>) => any): Promise<ApiResponse<DependentHostedNumberOrderPage>>; + pageWithHttpInfo(params: DependentHostedNumberOrderListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderPage>) => any): Promise<ApiResponse<DependentHostedNumberOrderPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DependentHostedNumberOrderListInstance(version: HostedNumbers, signingDocumentSid: string): DependentHostedNumberOrderListInstance { + if (!isValidPathParam(signingDocumentSid)) { + throw new Error('Parameter \'signingDocumentSid\' is not valid.'); + } + + const instance = {} as DependentHostedNumberOrderListInstance; + + instance._version = version; + instance._solution = { signingDocumentSid, }; + instance._uri = `/AuthorizationDocuments/${signingDocumentSid}/DependentHostedNumberOrders`; + + instance.page = function page(params?: DependentHostedNumberOrderListInstancePageOptions | ((error: Error | null, items: DependentHostedNumberOrderPage) => any), callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["incomingPhoneNumberSid"] !== undefined) + data["IncomingPhoneNumberSid"] = params["incomingPhoneNumberSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DependentHostedNumberOrderPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DependentHostedNumberOrderPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DependentHostedNumberOrderListInstancePageOptions | ((error: Error | null, items: ApiResponse<DependentHostedNumberOrderPage>) => any), callback?: (error: Error | null, items: ApiResponse<DependentHostedNumberOrderPage>) => any): Promise<ApiResponse<DependentHostedNumberOrderPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["incomingPhoneNumberSid"] !== undefined) + data["IncomingPhoneNumberSid"] = params["incomingPhoneNumberSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<DependentHostedNumberOrderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DependentHostedNumberOrderPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<DependentHostedNumberOrderPage>) => any): Promise<ApiResponse<DependentHostedNumberOrderPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<DependentHostedNumberOrderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DependentHostedNumberOrderPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface DependentHostedNumberOrderPayload extends TwilioResponsePayload { + items: DependentHostedNumberOrderResource[]; +} + +interface DependentHostedNumberOrderResource { + sid: string; + account_sid: string; + incoming_phone_number_sid: string; + address_sid: string; + signing_document_sid: string; + phone_number: string; + capabilities: PhoneNumberCapabilities; + friendly_name: string; + unique_name: string; + status: DependentHostedNumberOrderStatus; + failure_reason: string; + date_created: Date; + date_updated: Date; + verification_attempts: number; + email: string; + cc_emails: Array<string>; + verification_type: DependentHostedNumberOrderVerificationType; + verification_document_sid: string; + extension: string; + call_delay: number; + verification_code: string; + verification_call_sids: Array<string>; +} + +export class DependentHostedNumberOrderInstance { + + constructor(protected _version: HostedNumbers, payload: DependentHostedNumberOrderResource, signingDocumentSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.incomingPhoneNumberSid = (payload.incoming_phone_number_sid); + this.addressSid = (payload.address_sid); + this.signingDocumentSid = (payload.signing_document_sid); + this.phoneNumber = (payload.phone_number); + this.capabilities = (payload.capabilities); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.status = payload.status; + this.failureReason = (payload.failure_reason); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.verificationAttempts = deserialize.integer(payload.verification_attempts); + this.email = (payload.email); + this.ccEmails = (payload.cc_emails); + this.verificationType = payload.verification_type; + this.verificationDocumentSid = (payload.verification_document_sid); + this.extension = (payload.extension); + this.callDelay = deserialize.integer(payload.call_delay); + this.verificationCode = (payload.verification_code); + this.verificationCallSids = (payload.verification_call_sids); + + } + + /** + * A 34 character string that uniquely identifies this Authorization Document + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + */ + incomingPhoneNumberSid: string; + /** + * A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + */ + addressSid: string; + /** + * A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + */ + signingDocumentSid: string; + /** + * An E164 formatted phone number hosted by this HostedNumberOrder. + */ + phoneNumber: string; + capabilities: PhoneNumberCapabilities; + /** + * A human readable description of this resource, up to 64 characters. + */ + friendlyName: string; + /** + * Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + */ + uniqueName: string; + status: DependentHostedNumberOrderStatus; + /** + * A message that explains why a hosted_number_order went to status \"action-required\" + */ + failureReason: string; + /** + * The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The number of attempts made to verify ownership of the phone number that is being hosted. + */ + verificationAttempts: number; + /** + * Email of the owner of this phone number that is being hosted. + */ + email: string; + /** + * Email recipients who will be informed when an Authorization Document has been sent and signed + */ + ccEmails: Array<string>; + verificationType: DependentHostedNumberOrderVerificationType; + /** + * A 34 character string that uniquely identifies the Identity Document resource that represents the document for verifying ownership of the number to be hosted. + */ + verificationDocumentSid: string; + /** + * A numerical extension to be used when making the ownership verification call. + */ + extension: string; + /** + * A value between 0-30 specifying the number of seconds to delay initiating the ownership verification call. + */ + callDelay: number; + /** + * The digits passed during the ownership verification call. + */ + verificationCode: string; + /** + * A list of 34 character strings that are unique identifiers for the calls placed as part of ownership verification. + */ + verificationCallSids: Array<string>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + incomingPhoneNumberSid: this.incomingPhoneNumberSid, + addressSid: this.addressSid, + signingDocumentSid: this.signingDocumentSid, + phoneNumber: this.phoneNumber, + capabilities: this.capabilities, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + status: this.status, + failureReason: this.failureReason, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + verificationAttempts: this.verificationAttempts, + email: this.email, + ccEmails: this.ccEmails, + verificationType: this.verificationType, + verificationDocumentSid: this.verificationDocumentSid, + extension: this.extension, + callDelay: this.callDelay, + verificationCode: this.verificationCode, + verificationCallSids: this.verificationCallSids, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class DependentHostedNumberOrderPage extends Page<HostedNumbers, DependentHostedNumberOrderPayload, DependentHostedNumberOrderResource, DependentHostedNumberOrderInstance> { +/** +* Initialize the DependentHostedNumberOrderPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: HostedNumbers, response: Response<string>, solution: DependentHostedNumberOrderSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DependentHostedNumberOrderInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DependentHostedNumberOrderResource): DependentHostedNumberOrderInstance { + + return new DependentHostedNumberOrderInstance( + this._version, + payload, + this._solution.signingDocumentSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/preview/hosted_numbers/hostedNumberOrder.ts b/rest/preview/hosted_numbers/hostedNumberOrder.ts new file mode 100644 index 000000000..f0ed9bf04 --- /dev/null +++ b/rest/preview/hosted_numbers/hostedNumberOrder.ts @@ -0,0 +1,1218 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import HostedNumbers from "../HostedNumbers"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../interfaces"; + + +/** + * Status of this resource. It can hold one of the values: 1. Twilio Processing 2. Received, 3. Pending LOA, 4. Carrier Processing, 5. Completed, 6. Action Required, 7. Failed. See the [HostedNumberOrders Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values) section for more information on each of these statuses. + */ +export type HostedNumberOrderStatus = 'twilio-processing'|'received'|'pending-verification'|'verified'|'pending-loa'|'carrier-processing'|'testing'|'completed'|'failed'|'action-required'; + +/** + * The type of ownership verification required to move the number to a `verified` state. The verification methods are `phone-call` or `phone-bill`. + */ +export type HostedNumberOrderVerificationType = 'phone-call'|'phone-bill'; + + + + +/** + * Options to pass to update a HostedNumberOrderInstance + */ +export interface HostedNumberOrderContextUpdateOptions { + /** A 64 character string that is a human readable text that describes this resource. */ + "friendlyName"?: string; + /** Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName"?: string; + /** Email of the owner of this phone number that is being hosted. */ + "email"?: string; + /** Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. */ + "ccEmails"?: Array<string>; + /** */ + "status"?: HostedNumberOrderStatus; + /** A verification code that is given to the user via a phone call to the phone number that is being hosted. */ + "verificationCode"?: string; + /** */ + "verificationType"?: HostedNumberOrderVerificationType; + /** Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. */ + "verificationDocumentSid"?: string; + /** Digits to dial after connecting the verification call. */ + "extension"?: string; + /** The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. */ + "callDelay"?: number; +} + +/** + * Options to pass to create a HostedNumberOrderInstance + */ +export interface HostedNumberOrderListInstanceCreateOptions { + /** The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format */ + "phoneNumber": string; + /** Used to specify that the SMS capability will be hosted on Twilio\\\'s platform. */ + "smsCapability": boolean; + /** This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. */ + "accountSid"?: string; + /** A 64 character string that is a human readable text that describes this resource. */ + "friendlyName"?: string; + /** Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName"?: string; + /** Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. */ + "ccEmails"?: Array<string>; + /** The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. */ + "smsUrl"?: string; + /** The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. */ + "smsMethod"?: string; + /** A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. */ + "smsFallbackUrl"?: string; + /** The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. */ + "smsFallbackMethod"?: string; + /** Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. */ + "statusCallbackUrl"?: string; + /** Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. */ + "statusCallbackMethod"?: string; + /** Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. */ + "smsApplicationSid"?: string; + /** Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. */ + "addressSid"?: string; + /** Optional. Email of the owner of this phone number that is being hosted. */ + "email"?: string; + /** */ + "verificationType"?: HostedNumberOrderVerificationType; + /** Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. */ + "verificationDocumentSid"?: string; +} + +/** + * Options to pass to each + */ +export interface HostedNumberOrderListInstanceEachOptions { + /** The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. */ + "status"?: HostedNumberOrderStatus; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; + /** Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: HostedNumberOrderInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface HostedNumberOrderListInstanceOptions { + /** The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. */ + "status"?: HostedNumberOrderStatus; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; + /** Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface HostedNumberOrderListInstancePageOptions { + /** The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. */ + "status"?: HostedNumberOrderStatus; + /** An E164 formatted phone number hosted by this HostedNumberOrder. */ + "phoneNumber"?: string; + /** A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. */ + "incomingPhoneNumberSid"?: string; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; + /** Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. */ + "uniqueName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface HostedNumberOrderContext { + + /** + * Remove a HostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a HostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a HostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + fetch(callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> + + /** + * Fetch a HostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> + + /** + * Update a HostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + update(callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance>; + /** + * Update a HostedNumberOrderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + update(params: HostedNumberOrderContextUpdateOptions, callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance>; + + /** + * Update a HostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>>; + /** + * Update a HostedNumberOrderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + updateWithHttpInfo(params: HostedNumberOrderContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface HostedNumberOrderContextSolution { + "sid": string; +} + +export class HostedNumberOrderContextImpl implements HostedNumberOrderContext { + protected _solution: HostedNumberOrderContextSolution; + protected _uri: string; + + + constructor(protected _version: HostedNumbers, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/HostedNumberOrders/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new HostedNumberOrderInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<HostedNumberOrderResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<HostedNumberOrderInstance> => ({ + ...response, + body: new HostedNumberOrderInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: HostedNumberOrderContextUpdateOptions | ((error: Error | null, item?: HostedNumberOrderInstance) => any),callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["verificationCode"] !== undefined) + data["VerificationCode"] = params["verificationCode"]; + if (params["verificationType"] !== undefined) + data["VerificationType"] = params["verificationType"]; + if (params["verificationDocumentSid"] !== undefined) + data["VerificationDocumentSid"] = params["verificationDocumentSid"]; + if (params["extension"] !== undefined) + data["Extension"] = params["extension"]; + if (params["callDelay"] !== undefined) + data["CallDelay"] = params["callDelay"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new HostedNumberOrderInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: HostedNumberOrderContextUpdateOptions | ((error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["verificationCode"] !== undefined) + data["VerificationCode"] = params["verificationCode"]; + if (params["verificationType"] !== undefined) + data["VerificationType"] = params["verificationType"]; + if (params["verificationDocumentSid"] !== undefined) + data["VerificationDocumentSid"] = params["verificationDocumentSid"]; + if (params["extension"] !== undefined) + data["Extension"] = params["extension"]; + if (params["callDelay"] !== undefined) + data["CallDelay"] = params["callDelay"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<HostedNumberOrderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<HostedNumberOrderInstance> => ({ + ...response, + body: new HostedNumberOrderInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface HostedNumberOrderPayload extends TwilioResponsePayload { + items: HostedNumberOrderResource[]; +} + +interface HostedNumberOrderResource { + sid: string; + account_sid: string; + incoming_phone_number_sid: string; + address_sid: string; + signing_document_sid: string; + phone_number: string; + capabilities: PhoneNumberCapabilities; + friendly_name: string; + unique_name: string; + status: HostedNumberOrderStatus; + failure_reason: string; + date_created: Date; + date_updated: Date; + verification_attempts: number; + email: string; + cc_emails: Array<string>; + url: string; + verification_type: HostedNumberOrderVerificationType; + verification_document_sid: string; + extension: string; + call_delay: number; + verification_code: string; + verification_call_sids: Array<string>; +} + +export class HostedNumberOrderInstance { + protected _solution: HostedNumberOrderContextSolution; + protected _context?: HostedNumberOrderContext; + + constructor(protected _version: HostedNumbers, payload: HostedNumberOrderResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.incomingPhoneNumberSid = (payload.incoming_phone_number_sid); + this.addressSid = (payload.address_sid); + this.signingDocumentSid = (payload.signing_document_sid); + this.phoneNumber = (payload.phone_number); + this.capabilities = (payload.capabilities); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.status = payload.status; + this.failureReason = (payload.failure_reason); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.verificationAttempts = deserialize.integer(payload.verification_attempts); + this.email = (payload.email); + this.ccEmails = (payload.cc_emails); + this.url = (payload.url); + this.verificationType = payload.verification_type; + this.verificationDocumentSid = (payload.verification_document_sid); + this.extension = (payload.extension); + this.callDelay = deserialize.integer(payload.call_delay); + this.verificationCode = (payload.verification_code); + this.verificationCallSids = (payload.verification_call_sids); + + this._solution = { sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this HostedNumberOrder. + */ + sid: string; + /** + * A 34 character string that uniquely identifies the account. + */ + accountSid: string; + /** + * A 34 character string that uniquely identifies the [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the phone number being hosted. + */ + incomingPhoneNumberSid: string; + /** + * A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + */ + addressSid: string; + /** + * A 34 character string that uniquely identifies the [Authorization Document](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource) the user needs to sign. + */ + signingDocumentSid: string; + /** + * Phone number to be hosted. This must be in [E.164](https://en.wikipedia.org/wiki/E.164) format, e.g., +16175551212 + */ + phoneNumber: string; + capabilities: PhoneNumberCapabilities; + /** + * A 64 character string that is a human-readable text that describes this resource. + */ + friendlyName: string; + /** + * Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + */ + uniqueName: string; + status: HostedNumberOrderStatus; + /** + * A message that explains why a hosted_number_order went to status \"action-required\" + */ + failureReason: string; + /** + * The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The number of attempts made to verify ownership of the phone number that is being hosted. + */ + verificationAttempts: number; + /** + * Email of the owner of this phone number that is being hosted. + */ + email: string; + /** + * A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + */ + ccEmails: Array<string>; + /** + * The URL of this HostedNumberOrder. + */ + url: string; + verificationType: HostedNumberOrderVerificationType; + /** + * A 34 character string that uniquely identifies the Identity Document resource that represents the document for verifying ownership of the number to be hosted. + */ + verificationDocumentSid: string; + /** + * A numerical extension to be used when making the ownership verification call. + */ + extension: string; + /** + * A value between 0-30 specifying the number of seconds to delay initiating the ownership verification call. + */ + callDelay: number; + /** + * A verification code provided in the response for a user to enter when they pick up the phone call. + */ + verificationCode: string; + /** + * A list of 34 character strings that are unique identifiers for the calls placed as part of ownership verification. + */ + verificationCallSids: Array<string>; + + private get _proxy(): HostedNumberOrderContext { + this._context = this._context || new HostedNumberOrderContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a HostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a HostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a HostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + fetch(callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a HostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a HostedNumberOrderInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + update(callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance>; + /** + * Update a HostedNumberOrderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + update(params: HostedNumberOrderContextUpdateOptions, callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance>; + + update(params?: any, callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a HostedNumberOrderInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>>; + /** + * Update a HostedNumberOrderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + updateWithHttpInfo(params: HostedNumberOrderContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + incomingPhoneNumberSid: this.incomingPhoneNumberSid, + addressSid: this.addressSid, + signingDocumentSid: this.signingDocumentSid, + phoneNumber: this.phoneNumber, + capabilities: this.capabilities, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + status: this.status, + failureReason: this.failureReason, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + verificationAttempts: this.verificationAttempts, + email: this.email, + ccEmails: this.ccEmails, + url: this.url, + verificationType: this.verificationType, + verificationDocumentSid: this.verificationDocumentSid, + extension: this.extension, + callDelay: this.callDelay, + verificationCode: this.verificationCode, + verificationCallSids: this.verificationCallSids, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface HostedNumberOrderSolution { +} + +export interface HostedNumberOrderListInstance { + _version: HostedNumbers; + _solution: HostedNumberOrderSolution; + _uri: string; + + (sid: string, ): HostedNumberOrderContext; + get(sid: string, ): HostedNumberOrderContext; + + + + + + + + + /** + * Create a HostedNumberOrderInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance + */ + create(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, item?: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance>; + + /** + * Create a HostedNumberOrderInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed HostedNumberOrderInstance with HTTP metadata + */ + createWithHttpInfo(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>>; + + + + + /** + * Streams HostedNumberOrderInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: HostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + each(params: HostedNumberOrderListInstanceEachOptions, callback?: (item: HostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + /** + * Streams HostedNumberOrderInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: HostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: HostedNumberOrderListInstanceEachOptions, callback?: (item: HostedNumberOrderInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of HostedNumberOrderInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: HostedNumberOrderPage) => any): Promise<HostedNumberOrderPage>; + /** + * Retrieve a single target page of HostedNumberOrderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderPage>) => any): Promise<ApiResponse<HostedNumberOrderPage>>; + /** + * Lists HostedNumberOrderInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: HostedNumberOrderInstance[]) => any): Promise<HostedNumberOrderInstance[]>; + list(params: HostedNumberOrderListInstanceOptions, callback?: (error: Error | null, items: HostedNumberOrderInstance[]) => any): Promise<HostedNumberOrderInstance[]>; + /** + * Lists HostedNumberOrderInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderInstance[]>) => any): Promise<ApiResponse<HostedNumberOrderInstance[]>>; + listWithHttpInfo(params: HostedNumberOrderListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderInstance[]>) => any): Promise<ApiResponse<HostedNumberOrderInstance[]>>; + /** + * Retrieve a single page of HostedNumberOrderInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: HostedNumberOrderPage) => any): Promise<HostedNumberOrderPage>; + page(params: HostedNumberOrderListInstancePageOptions, callback?: (error: Error | null, items: HostedNumberOrderPage) => any): Promise<HostedNumberOrderPage>; + /** + * Retrieve a single page of HostedNumberOrderInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HostedNumberOrderListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderPage>) => any): Promise<ApiResponse<HostedNumberOrderPage>>; + pageWithHttpInfo(params: HostedNumberOrderListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderPage>) => any): Promise<ApiResponse<HostedNumberOrderPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function HostedNumberOrderListInstance(version: HostedNumbers): HostedNumberOrderListInstance { + const instance = ((sid, ) => instance.get(sid, )) as HostedNumberOrderListInstance; + + instance.get = function get(sid, ): HostedNumberOrderContext { + return new HostedNumberOrderContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/HostedNumberOrders`; + + instance.create = function create(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, items: HostedNumberOrderInstance) => any): Promise<HostedNumberOrderInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + if (params["smsCapability"] === null || params["smsCapability"] === undefined) { + throw new Error('Required parameter "params[\'smsCapability\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + + data["SmsCapability"] = serialize.bool(params["smsCapability"]); + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["verificationType"] !== undefined) + data["VerificationType"] = params["verificationType"]; + if (params["verificationDocumentSid"] !== undefined) + data["VerificationDocumentSid"] = params["verificationDocumentSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new HostedNumberOrderInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: HostedNumberOrderListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderInstance>) => any): Promise<ApiResponse<HostedNumberOrderInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + if (params["smsCapability"] === null || params["smsCapability"] === undefined) { + throw new Error('Required parameter "params[\'smsCapability\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + + data["SmsCapability"] = serialize.bool(params["smsCapability"]); + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["ccEmails"] !== undefined) + data["CcEmails"] = serialize.map(params["ccEmails"], (e: string) => (e)); + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["smsApplicationSid"] !== undefined) + data["SmsApplicationSid"] = params["smsApplicationSid"]; + if (params["addressSid"] !== undefined) + data["AddressSid"] = params["addressSid"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + if (params["verificationType"] !== undefined) + data["VerificationType"] = params["verificationType"]; + if (params["verificationDocumentSid"] !== undefined) + data["VerificationDocumentSid"] = params["verificationDocumentSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<HostedNumberOrderResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<HostedNumberOrderInstance> => ({ + ...response, + body: new HostedNumberOrderInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: HostedNumberOrderListInstancePageOptions | ((error: Error | null, items: HostedNumberOrderPage) => any), callback?: (error: Error | null, items: HostedNumberOrderPage) => any): Promise<HostedNumberOrderPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["incomingPhoneNumberSid"] !== undefined) + data["IncomingPhoneNumberSid"] = params["incomingPhoneNumberSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new HostedNumberOrderPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: HostedNumberOrderPage) => any): Promise<HostedNumberOrderPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new HostedNumberOrderPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: HostedNumberOrderListInstancePageOptions | ((error: Error | null, items: ApiResponse<HostedNumberOrderPage>) => any), callback?: (error: Error | null, items: ApiResponse<HostedNumberOrderPage>) => any): Promise<ApiResponse<HostedNumberOrderPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["incomingPhoneNumberSid"] !== undefined) + data["IncomingPhoneNumberSid"] = params["incomingPhoneNumberSid"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<HostedNumberOrderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new HostedNumberOrderPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<HostedNumberOrderPage>) => any): Promise<ApiResponse<HostedNumberOrderPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<HostedNumberOrderPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new HostedNumberOrderPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class HostedNumberOrderPage extends Page<HostedNumbers, HostedNumberOrderPayload, HostedNumberOrderResource, HostedNumberOrderInstance> { +/** +* Initialize the HostedNumberOrderPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: HostedNumbers, response: Response<string>, solution: HostedNumberOrderSolution) { + super(version, response, solution); + } + + /** + * Build an instance of HostedNumberOrderInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: HostedNumberOrderResource): HostedNumberOrderInstance { + + return new HostedNumberOrderInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/preview/marketplace/availableAddOn.ts b/rest/preview/marketplace/availableAddOn.ts new file mode 100644 index 000000000..36f1bb45e --- /dev/null +++ b/rest/preview/marketplace/availableAddOn.ts @@ -0,0 +1,573 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import Marketplace from "../Marketplace"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { AvailableAddOnExtensionListInstance } from "./availableAddOn/availableAddOnExtension"; + + + + +/** + * Options to pass to each + */ +export interface AvailableAddOnListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AvailableAddOnInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AvailableAddOnListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AvailableAddOnListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AvailableAddOnContext { + extensions: AvailableAddOnExtensionListInstance; + + /** + * Fetch a AvailableAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnInstance + */ + fetch(callback?: (error: Error | null, item?: AvailableAddOnInstance) => any): Promise<AvailableAddOnInstance> + + /** + * Fetch a AvailableAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnInstance>) => any): Promise<ApiResponse<AvailableAddOnInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AvailableAddOnContextSolution { + "sid": string; +} + +export class AvailableAddOnContextImpl implements AvailableAddOnContext { + protected _solution: AvailableAddOnContextSolution; + protected _uri: string; + + protected _extensions?: AvailableAddOnExtensionListInstance; + + constructor(protected _version: Marketplace, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/AvailableAddOns/${sid}`; + } + + get extensions(): AvailableAddOnExtensionListInstance { + this._extensions = this._extensions || AvailableAddOnExtensionListInstance(this._version, this._solution.sid); + return this._extensions; + } + + fetch(callback?: (error: Error | null, item?: AvailableAddOnInstance) => any): Promise<AvailableAddOnInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AvailableAddOnInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnInstance>) => any): Promise<ApiResponse<AvailableAddOnInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AvailableAddOnResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AvailableAddOnInstance> => ({ + ...response, + body: new AvailableAddOnInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AvailableAddOnPayload extends TwilioResponsePayload { + available_add_ons: AvailableAddOnResource[]; +} + +interface AvailableAddOnResource { + sid: string; + friendly_name: string; + description: string; + pricing_type: string; + configuration_schema: any; + url: string; + links: Record<string, string>; +} + +export class AvailableAddOnInstance { + protected _solution: AvailableAddOnContextSolution; + protected _context?: AvailableAddOnContext; + + constructor(protected _version: Marketplace, payload: AvailableAddOnResource, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.pricingType = (payload.pricing_type); + this.configurationSchema = (payload.configuration_schema); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the AvailableAddOn resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * A short description of the Add-on\'s functionality. + */ + description: string; + /** + * How customers are charged for using this Add-on. + */ + pricingType: string; + /** + * The JSON object with the configuration that must be provided when installing a given Add-on. + */ + configurationSchema: any; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): AvailableAddOnContext { + this._context = this._context || new AvailableAddOnContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a AvailableAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnInstance + */ + fetch(callback?: (error: Error | null, item?: AvailableAddOnInstance) => any): Promise<AvailableAddOnInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AvailableAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnInstance>) => any): Promise<ApiResponse<AvailableAddOnInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the extensions. + */ + extensions(): AvailableAddOnExtensionListInstance { + return this._proxy.extensions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + description: this.description, + pricingType: this.pricingType, + configurationSchema: this.configurationSchema, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AvailableAddOnSolution { +} + +export interface AvailableAddOnListInstance { + _version: Marketplace; + _solution: AvailableAddOnSolution; + _uri: string; + + (sid: string, ): AvailableAddOnContext; + get(sid: string, ): AvailableAddOnContext; + + + + + + /** + * Streams AvailableAddOnInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AvailableAddOnInstance, done: (err?: Error) => void) => void): void; + each(params: AvailableAddOnListInstanceEachOptions, callback?: (item: AvailableAddOnInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AvailableAddOnInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AvailableAddOnInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AvailableAddOnListInstanceEachOptions, callback?: (item: AvailableAddOnInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AvailableAddOnInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AvailableAddOnPage) => any): Promise<AvailableAddOnPage>; + /** + * Retrieve a single target page of AvailableAddOnInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnPage>) => any): Promise<ApiResponse<AvailableAddOnPage>>; + /** + * Lists AvailableAddOnInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AvailableAddOnInstance[]) => any): Promise<AvailableAddOnInstance[]>; + list(params: AvailableAddOnListInstanceOptions, callback?: (error: Error | null, items: AvailableAddOnInstance[]) => any): Promise<AvailableAddOnInstance[]>; + /** + * Lists AvailableAddOnInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AvailableAddOnInstance[]>) => any): Promise<ApiResponse<AvailableAddOnInstance[]>>; + listWithHttpInfo(params: AvailableAddOnListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnInstance[]>) => any): Promise<ApiResponse<AvailableAddOnInstance[]>>; + /** + * Retrieve a single page of AvailableAddOnInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AvailableAddOnPage) => any): Promise<AvailableAddOnPage>; + page(params: AvailableAddOnListInstancePageOptions, callback?: (error: Error | null, items: AvailableAddOnPage) => any): Promise<AvailableAddOnPage>; + /** + * Retrieve a single page of AvailableAddOnInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AvailableAddOnPage>) => any): Promise<ApiResponse<AvailableAddOnPage>>; + pageWithHttpInfo(params: AvailableAddOnListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnPage>) => any): Promise<ApiResponse<AvailableAddOnPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AvailableAddOnListInstance(version: Marketplace): AvailableAddOnListInstance { + const instance = ((sid, ) => instance.get(sid, )) as AvailableAddOnListInstance; + + instance.get = function get(sid, ): AvailableAddOnContext { + return new AvailableAddOnContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/AvailableAddOns`; + + instance.page = function page(params?: AvailableAddOnListInstancePageOptions | ((error: Error | null, items: AvailableAddOnPage) => any), callback?: (error: Error | null, items: AvailableAddOnPage) => any): Promise<AvailableAddOnPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AvailableAddOnPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AvailableAddOnPage) => any): Promise<AvailableAddOnPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AvailableAddOnPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AvailableAddOnListInstancePageOptions | ((error: Error | null, items: ApiResponse<AvailableAddOnPage>) => any), callback?: (error: Error | null, items: ApiResponse<AvailableAddOnPage>) => any): Promise<ApiResponse<AvailableAddOnPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AvailableAddOnPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AvailableAddOnPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AvailableAddOnPage>) => any): Promise<ApiResponse<AvailableAddOnPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AvailableAddOnPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AvailableAddOnPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AvailableAddOnPage extends Page<Marketplace, AvailableAddOnPayload, AvailableAddOnResource, AvailableAddOnInstance> { +/** +* Initialize the AvailableAddOnPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Marketplace, response: Response<string>, solution: AvailableAddOnSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AvailableAddOnInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AvailableAddOnResource): AvailableAddOnInstance { + + return new AvailableAddOnInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/preview/marketplace/availableAddOn/availableAddOnExtension.ts b/rest/preview/marketplace/availableAddOn/availableAddOnExtension.ts new file mode 100644 index 000000000..10e280d80 --- /dev/null +++ b/rest/preview/marketplace/availableAddOn/availableAddOnExtension.ts @@ -0,0 +1,562 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import Marketplace from "../../Marketplace"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface AvailableAddOnExtensionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AvailableAddOnExtensionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AvailableAddOnExtensionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AvailableAddOnExtensionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AvailableAddOnExtensionContext { + + /** + * Fetch a AvailableAddOnExtensionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnExtensionInstance + */ + fetch(callback?: (error: Error | null, item?: AvailableAddOnExtensionInstance) => any): Promise<AvailableAddOnExtensionInstance> + + /** + * Fetch a AvailableAddOnExtensionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnExtensionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnExtensionInstance>) => any): Promise<ApiResponse<AvailableAddOnExtensionInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AvailableAddOnExtensionContextSolution { + "availableAddOnSid": string; + "sid": string; +} + +export class AvailableAddOnExtensionContextImpl implements AvailableAddOnExtensionContext { + protected _solution: AvailableAddOnExtensionContextSolution; + protected _uri: string; + + + constructor(protected _version: Marketplace, availableAddOnSid: string, sid: string) { + if (!isValidPathParam(availableAddOnSid)) { + throw new Error('Parameter \'availableAddOnSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { availableAddOnSid, sid, }; + this._uri = `/AvailableAddOns/${availableAddOnSid}/Extensions/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: AvailableAddOnExtensionInstance) => any): Promise<AvailableAddOnExtensionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AvailableAddOnExtensionInstance(operationVersion, payload, instance._solution.availableAddOnSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnExtensionInstance>) => any): Promise<ApiResponse<AvailableAddOnExtensionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AvailableAddOnExtensionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AvailableAddOnExtensionInstance> => ({ + ...response, + body: new AvailableAddOnExtensionInstance(operationVersion, response.body, instance._solution.availableAddOnSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AvailableAddOnExtensionPayload extends TwilioResponsePayload { + extensions: AvailableAddOnExtensionResource[]; +} + +interface AvailableAddOnExtensionResource { + sid: string; + available_add_on_sid: string; + friendly_name: string; + product_name: string; + unique_name: string; + url: string; +} + +export class AvailableAddOnExtensionInstance { + protected _solution: AvailableAddOnExtensionContextSolution; + protected _context?: AvailableAddOnExtensionContext; + + constructor(protected _version: Marketplace, payload: AvailableAddOnExtensionResource, availableAddOnSid: string, sid?: string) { + + this.sid = (payload.sid); + this.availableAddOnSid = (payload.available_add_on_sid); + this.friendlyName = (payload.friendly_name); + this.productName = (payload.product_name); + this.uniqueName = (payload.unique_name); + this.url = (payload.url); + + this._solution = { availableAddOnSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the AvailableAddOnExtension resource. + */ + sid: string; + /** + * The SID of the AvailableAddOn resource to which this extension applies. + */ + availableAddOnSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The name of the Product this Extension is used within. + */ + productName: string; + /** + * An application-defined string that uniquely identifies the resource. + */ + uniqueName: string; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): AvailableAddOnExtensionContext { + this._context = this._context || new AvailableAddOnExtensionContextImpl(this._version, this._solution.availableAddOnSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a AvailableAddOnExtensionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnExtensionInstance + */ + fetch(callback?: (error: Error | null, item?: AvailableAddOnExtensionInstance) => any): Promise<AvailableAddOnExtensionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AvailableAddOnExtensionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AvailableAddOnExtensionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AvailableAddOnExtensionInstance>) => any): Promise<ApiResponse<AvailableAddOnExtensionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + availableAddOnSid: this.availableAddOnSid, + friendlyName: this.friendlyName, + productName: this.productName, + uniqueName: this.uniqueName, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AvailableAddOnExtensionSolution { + availableAddOnSid: string; +} + +export interface AvailableAddOnExtensionListInstance { + _version: Marketplace; + _solution: AvailableAddOnExtensionSolution; + _uri: string; + + (sid: string, ): AvailableAddOnExtensionContext; + get(sid: string, ): AvailableAddOnExtensionContext; + + + + + + /** + * Streams AvailableAddOnExtensionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AvailableAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + each(params: AvailableAddOnExtensionListInstanceEachOptions, callback?: (item: AvailableAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AvailableAddOnExtensionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AvailableAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AvailableAddOnExtensionListInstanceEachOptions, callback?: (item: AvailableAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AvailableAddOnExtensionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AvailableAddOnExtensionPage) => any): Promise<AvailableAddOnExtensionPage>; + /** + * Retrieve a single target page of AvailableAddOnExtensionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionPage>) => any): Promise<ApiResponse<AvailableAddOnExtensionPage>>; + /** + * Lists AvailableAddOnExtensionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AvailableAddOnExtensionInstance[]) => any): Promise<AvailableAddOnExtensionInstance[]>; + list(params: AvailableAddOnExtensionListInstanceOptions, callback?: (error: Error | null, items: AvailableAddOnExtensionInstance[]) => any): Promise<AvailableAddOnExtensionInstance[]>; + /** + * Lists AvailableAddOnExtensionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionInstance[]>) => any): Promise<ApiResponse<AvailableAddOnExtensionInstance[]>>; + listWithHttpInfo(params: AvailableAddOnExtensionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionInstance[]>) => any): Promise<ApiResponse<AvailableAddOnExtensionInstance[]>>; + /** + * Retrieve a single page of AvailableAddOnExtensionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AvailableAddOnExtensionPage) => any): Promise<AvailableAddOnExtensionPage>; + page(params: AvailableAddOnExtensionListInstancePageOptions, callback?: (error: Error | null, items: AvailableAddOnExtensionPage) => any): Promise<AvailableAddOnExtensionPage>; + /** + * Retrieve a single page of AvailableAddOnExtensionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AvailableAddOnExtensionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionPage>) => any): Promise<ApiResponse<AvailableAddOnExtensionPage>>; + pageWithHttpInfo(params: AvailableAddOnExtensionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionPage>) => any): Promise<ApiResponse<AvailableAddOnExtensionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AvailableAddOnExtensionListInstance(version: Marketplace, availableAddOnSid: string): AvailableAddOnExtensionListInstance { + if (!isValidPathParam(availableAddOnSid)) { + throw new Error('Parameter \'availableAddOnSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as AvailableAddOnExtensionListInstance; + + instance.get = function get(sid, ): AvailableAddOnExtensionContext { + return new AvailableAddOnExtensionContextImpl(version, availableAddOnSid, sid); + } + + instance._version = version; + instance._solution = { availableAddOnSid, }; + instance._uri = `/AvailableAddOns/${availableAddOnSid}/Extensions`; + + instance.page = function page(params?: AvailableAddOnExtensionListInstancePageOptions | ((error: Error | null, items: AvailableAddOnExtensionPage) => any), callback?: (error: Error | null, items: AvailableAddOnExtensionPage) => any): Promise<AvailableAddOnExtensionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AvailableAddOnExtensionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AvailableAddOnExtensionPage) => any): Promise<AvailableAddOnExtensionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AvailableAddOnExtensionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AvailableAddOnExtensionListInstancePageOptions | ((error: Error | null, items: ApiResponse<AvailableAddOnExtensionPage>) => any), callback?: (error: Error | null, items: ApiResponse<AvailableAddOnExtensionPage>) => any): Promise<ApiResponse<AvailableAddOnExtensionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AvailableAddOnExtensionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AvailableAddOnExtensionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AvailableAddOnExtensionPage>) => any): Promise<ApiResponse<AvailableAddOnExtensionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AvailableAddOnExtensionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AvailableAddOnExtensionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AvailableAddOnExtensionPage extends Page<Marketplace, AvailableAddOnExtensionPayload, AvailableAddOnExtensionResource, AvailableAddOnExtensionInstance> { +/** +* Initialize the AvailableAddOnExtensionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Marketplace, response: Response<string>, solution: AvailableAddOnExtensionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AvailableAddOnExtensionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AvailableAddOnExtensionResource): AvailableAddOnExtensionInstance { + + return new AvailableAddOnExtensionInstance( + this._version, + payload, + this._solution.availableAddOnSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/preview/marketplace/installedAddOn.ts b/rest/preview/marketplace/installedAddOn.ts new file mode 100644 index 000000000..2095d2d97 --- /dev/null +++ b/rest/preview/marketplace/installedAddOn.ts @@ -0,0 +1,964 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import Marketplace from "../Marketplace"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { InstalledAddOnExtensionListInstance } from "./installedAddOn/installedAddOnExtension"; + + + + + +/** + * Options to pass to update a InstalledAddOnInstance + */ +export interface InstalledAddOnContextUpdateOptions { + /** Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured */ + "configuration"?: any; + /** An application-defined string that uniquely identifies the resource. This value must be unique within the Account. */ + "uniqueName"?: string; +} + +/** + * Options to pass to create a InstalledAddOnInstance + */ +export interface InstalledAddOnListInstanceCreateOptions { + /** The SID of the AvaliableAddOn to install. */ + "availableAddOnSid": string; + /** Whether the Terms of Service were accepted. */ + "acceptTermsOfService": boolean; + /** The JSON object that represents the configuration of the new Add-on being installed. */ + "configuration"?: any; + /** An application-defined string that uniquely identifies the resource. This value must be unique within the Account. */ + "uniqueName"?: string; +} + +/** + * Options to pass to each + */ +export interface InstalledAddOnListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InstalledAddOnListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InstalledAddOnListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InstalledAddOnContext { + extensions: InstalledAddOnExtensionListInstance; + + /** + * Remove a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + fetch(callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> + + /** + * Fetch a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> + + /** + * Update a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + update(callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; + /** + * Update a InstalledAddOnInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + update(params: InstalledAddOnContextUpdateOptions, callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; + + /** + * Update a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>>; + /** + * Update a InstalledAddOnInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + updateWithHttpInfo(params: InstalledAddOnContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InstalledAddOnContextSolution { + "sid": string; +} + +export class InstalledAddOnContextImpl implements InstalledAddOnContext { + protected _solution: InstalledAddOnContextSolution; + protected _uri: string; + + protected _extensions?: InstalledAddOnExtensionListInstance; + + constructor(protected _version: Marketplace, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/InstalledAddOns/${sid}`; + } + + get extensions(): InstalledAddOnExtensionListInstance { + this._extensions = this._extensions || InstalledAddOnExtensionListInstance(this._version, this._solution.sid); + return this._extensions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<InstalledAddOnResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<InstalledAddOnInstance> => ({ + ...response, + body: new InstalledAddOnInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: InstalledAddOnContextUpdateOptions | ((error: Error | null, item?: InstalledAddOnInstance) => any),callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: InstalledAddOnContextUpdateOptions | ((error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<InstalledAddOnResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<InstalledAddOnInstance> => ({ + ...response, + body: new InstalledAddOnInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InstalledAddOnPayload extends TwilioResponsePayload { + installed_add_ons: InstalledAddOnResource[]; +} + +interface InstalledAddOnResource { + sid: string; + account_sid: string; + friendly_name: string; + description: string; + configuration: any; + unique_name: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class InstalledAddOnInstance { + protected _solution: InstalledAddOnContextSolution; + protected _context?: InstalledAddOnContext; + + constructor(protected _version: Marketplace, payload: InstalledAddOnResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.description = (payload.description); + this.configuration = (payload.configuration); + this.uniqueName = (payload.unique_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the InstalledAddOn resource. This Sid can also be found in the Console on that specific Add-ons page as the \'Available Add-on Sid\'. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the InstalledAddOn resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * A short description of the Add-on\'s functionality. + */ + description: string; + /** + * The JSON object that represents the current configuration of installed Add-on. + */ + configuration: any; + /** + * An application-defined string that uniquely identifies the resource. + */ + uniqueName: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): InstalledAddOnContext { + this._context = this._context || new InstalledAddOnContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + fetch(callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a InstalledAddOnInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + update(callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; + /** + * Update a InstalledAddOnInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + update(params: InstalledAddOnContextUpdateOptions, callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; + + update(params?: any, callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a InstalledAddOnInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>>; + /** + * Update a InstalledAddOnInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + updateWithHttpInfo(params: InstalledAddOnContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the extensions. + */ + extensions(): InstalledAddOnExtensionListInstance { + return this._proxy.extensions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + description: this.description, + configuration: this.configuration, + uniqueName: this.uniqueName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InstalledAddOnSolution { +} + +export interface InstalledAddOnListInstance { + _version: Marketplace; + _solution: InstalledAddOnSolution; + _uri: string; + + (sid: string, ): InstalledAddOnContext; + get(sid: string, ): InstalledAddOnContext; + + + + + + + + + /** + * Create a InstalledAddOnInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance + */ + create(params: InstalledAddOnListInstanceCreateOptions, callback?: (error: Error | null, item?: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; + + /** + * Create a InstalledAddOnInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnInstance with HTTP metadata + */ + createWithHttpInfo(params: InstalledAddOnListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>>; + + + + + /** + * Streams InstalledAddOnInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void): void; + each(params: InstalledAddOnListInstanceEachOptions, callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InstalledAddOnInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InstalledAddOnListInstanceEachOptions, callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InstalledAddOnInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage>; + /** + * Retrieve a single target page of InstalledAddOnInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnPage>) => any): Promise<ApiResponse<InstalledAddOnPage>>; + /** + * Lists InstalledAddOnInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InstalledAddOnInstance[]) => any): Promise<InstalledAddOnInstance[]>; + list(params: InstalledAddOnListInstanceOptions, callback?: (error: Error | null, items: InstalledAddOnInstance[]) => any): Promise<InstalledAddOnInstance[]>; + /** + * Lists InstalledAddOnInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<InstalledAddOnInstance[]>) => any): Promise<ApiResponse<InstalledAddOnInstance[]>>; + listWithHttpInfo(params: InstalledAddOnListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnInstance[]>) => any): Promise<ApiResponse<InstalledAddOnInstance[]>>; + /** + * Retrieve a single page of InstalledAddOnInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage>; + page(params: InstalledAddOnListInstancePageOptions, callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage>; + /** + * Retrieve a single page of InstalledAddOnInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<InstalledAddOnPage>) => any): Promise<ApiResponse<InstalledAddOnPage>>; + pageWithHttpInfo(params: InstalledAddOnListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnPage>) => any): Promise<ApiResponse<InstalledAddOnPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InstalledAddOnListInstance(version: Marketplace): InstalledAddOnListInstance { + const instance = ((sid, ) => instance.get(sid, )) as InstalledAddOnListInstance; + + instance.get = function get(sid, ): InstalledAddOnContext { + return new InstalledAddOnContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/InstalledAddOns`; + + instance.create = function create(params: InstalledAddOnListInstanceCreateOptions, callback?: (error: Error | null, items: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["availableAddOnSid"] === null || params["availableAddOnSid"] === undefined) { + throw new Error('Required parameter "params[\'availableAddOnSid\']" missing.'); + } + + if (params["acceptTermsOfService"] === null || params["acceptTermsOfService"] === undefined) { + throw new Error('Required parameter "params[\'acceptTermsOfService\']" missing.'); + } + + let data: any = {}; + + + + data["AvailableAddOnSid"] = params["availableAddOnSid"]; + + data["AcceptTermsOfService"] = serialize.bool(params["acceptTermsOfService"]); + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: InstalledAddOnListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnInstance>) => any): Promise<ApiResponse<InstalledAddOnInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["availableAddOnSid"] === null || params["availableAddOnSid"] === undefined) { + throw new Error('Required parameter "params[\'availableAddOnSid\']" missing.'); + } + + if (params["acceptTermsOfService"] === null || params["acceptTermsOfService"] === undefined) { + throw new Error('Required parameter "params[\'acceptTermsOfService\']" missing.'); + } + + let data: any = {}; + + + + data["AvailableAddOnSid"] = params["availableAddOnSid"]; + + data["AcceptTermsOfService"] = serialize.bool(params["acceptTermsOfService"]); + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<InstalledAddOnResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<InstalledAddOnInstance> => ({ + ...response, + body: new InstalledAddOnInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: InstalledAddOnListInstancePageOptions | ((error: Error | null, items: InstalledAddOnPage) => any), callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InstalledAddOnPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InstalledAddOnPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InstalledAddOnListInstancePageOptions | ((error: Error | null, items: ApiResponse<InstalledAddOnPage>) => any), callback?: (error: Error | null, items: ApiResponse<InstalledAddOnPage>) => any): Promise<ApiResponse<InstalledAddOnPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<InstalledAddOnPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InstalledAddOnPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<InstalledAddOnPage>) => any): Promise<ApiResponse<InstalledAddOnPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<InstalledAddOnPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InstalledAddOnPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InstalledAddOnPage extends Page<Marketplace, InstalledAddOnPayload, InstalledAddOnResource, InstalledAddOnInstance> { +/** +* Initialize the InstalledAddOnPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Marketplace, response: Response<string>, solution: InstalledAddOnSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InstalledAddOnInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InstalledAddOnResource): InstalledAddOnInstance { + + return new InstalledAddOnInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/preview/marketplace/installedAddOn/installedAddOnExtension.ts b/rest/preview/marketplace/installedAddOn/installedAddOnExtension.ts new file mode 100644 index 000000000..f17dba479 --- /dev/null +++ b/rest/preview/marketplace/installedAddOn/installedAddOnExtension.ts @@ -0,0 +1,700 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import Marketplace from "../../Marketplace"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a InstalledAddOnExtensionInstance + */ +export interface InstalledAddOnExtensionContextUpdateOptions { + /** Whether the Extension should be invoked. */ + "enabled": boolean; +} + +/** + * Options to pass to each + */ +export interface InstalledAddOnExtensionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InstalledAddOnExtensionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InstalledAddOnExtensionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InstalledAddOnExtensionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InstalledAddOnExtensionContext { + + /** + * Fetch a InstalledAddOnExtensionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance + */ + fetch(callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance> + + /** + * Fetch a InstalledAddOnExtensionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>> + + /** + * Update a InstalledAddOnExtensionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance + */ + update(params: InstalledAddOnExtensionContextUpdateOptions, callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance>; + + /** + * Update a InstalledAddOnExtensionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance with HTTP metadata + */ + updateWithHttpInfo(params: InstalledAddOnExtensionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InstalledAddOnExtensionContextSolution { + "installedAddOnSid": string; + "sid": string; +} + +export class InstalledAddOnExtensionContextImpl implements InstalledAddOnExtensionContext { + protected _solution: InstalledAddOnExtensionContextSolution; + protected _uri: string; + + + constructor(protected _version: Marketplace, installedAddOnSid: string, sid: string) { + if (!isValidPathParam(installedAddOnSid)) { + throw new Error('Parameter \'installedAddOnSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { installedAddOnSid, sid, }; + this._uri = `/InstalledAddOns/${installedAddOnSid}/Extensions/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnExtensionInstance(operationVersion, payload, instance._solution.installedAddOnSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<InstalledAddOnExtensionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<InstalledAddOnExtensionInstance> => ({ + ...response, + body: new InstalledAddOnExtensionInstance(operationVersion, response.body, instance._solution.installedAddOnSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: InstalledAddOnExtensionContextUpdateOptions,callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["enabled"] === null || params["enabled"] === undefined) { + throw new Error('Required parameter "params[\'enabled\']" missing.'); + } + + let data: any = {}; + + + + data["Enabled"] = serialize.bool(params["enabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new InstalledAddOnExtensionInstance(operationVersion, payload, instance._solution.installedAddOnSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: InstalledAddOnExtensionContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["enabled"] === null || params["enabled"] === undefined) { + throw new Error('Required parameter "params[\'enabled\']" missing.'); + } + + let data: any = {}; + + + + data["Enabled"] = serialize.bool(params["enabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<InstalledAddOnExtensionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<InstalledAddOnExtensionInstance> => ({ + ...response, + body: new InstalledAddOnExtensionInstance(operationVersion, response.body, instance._solution.installedAddOnSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InstalledAddOnExtensionPayload extends TwilioResponsePayload { + extensions: InstalledAddOnExtensionResource[]; +} + +interface InstalledAddOnExtensionResource { + sid: string; + installed_add_on_sid: string; + friendly_name: string; + product_name: string; + unique_name: string; + enabled: boolean; + url: string; +} + +export class InstalledAddOnExtensionInstance { + protected _solution: InstalledAddOnExtensionContextSolution; + protected _context?: InstalledAddOnExtensionContext; + + constructor(protected _version: Marketplace, payload: InstalledAddOnExtensionResource, installedAddOnSid: string, sid?: string) { + + this.sid = (payload.sid); + this.installedAddOnSid = (payload.installed_add_on_sid); + this.friendlyName = (payload.friendly_name); + this.productName = (payload.product_name); + this.uniqueName = (payload.unique_name); + this.enabled = (payload.enabled); + this.url = (payload.url); + + this._solution = { installedAddOnSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the InstalledAddOn Extension resource. + */ + sid: string; + /** + * The SID of the InstalledAddOn resource to which this extension applies. + */ + installedAddOnSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The name of the Product this Extension is used within. + */ + productName: string; + /** + * An application-defined string that uniquely identifies the resource. + */ + uniqueName: string; + /** + * Whether the Extension will be invoked. + */ + enabled: boolean; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): InstalledAddOnExtensionContext { + this._context = this._context || new InstalledAddOnExtensionContextImpl(this._version, this._solution.installedAddOnSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a InstalledAddOnExtensionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance + */ + fetch(callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InstalledAddOnExtensionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a InstalledAddOnExtensionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance + */ + update(params: InstalledAddOnExtensionContextUpdateOptions, callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance>; + + update(params?: any, callback?: (error: Error | null, item?: InstalledAddOnExtensionInstance) => any): Promise<InstalledAddOnExtensionInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a InstalledAddOnExtensionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InstalledAddOnExtensionInstance with HTTP metadata + */ + updateWithHttpInfo(params: InstalledAddOnExtensionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<InstalledAddOnExtensionInstance>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + installedAddOnSid: this.installedAddOnSid, + friendlyName: this.friendlyName, + productName: this.productName, + uniqueName: this.uniqueName, + enabled: this.enabled, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InstalledAddOnExtensionSolution { + installedAddOnSid: string; +} + +export interface InstalledAddOnExtensionListInstance { + _version: Marketplace; + _solution: InstalledAddOnExtensionSolution; + _uri: string; + + (sid: string, ): InstalledAddOnExtensionContext; + get(sid: string, ): InstalledAddOnExtensionContext; + + + + + + + + /** + * Streams InstalledAddOnExtensionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InstalledAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + each(params: InstalledAddOnExtensionListInstanceEachOptions, callback?: (item: InstalledAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InstalledAddOnExtensionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InstalledAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InstalledAddOnExtensionListInstanceEachOptions, callback?: (item: InstalledAddOnExtensionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InstalledAddOnExtensionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InstalledAddOnExtensionPage) => any): Promise<InstalledAddOnExtensionPage>; + /** + * Retrieve a single target page of InstalledAddOnExtensionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionPage>) => any): Promise<ApiResponse<InstalledAddOnExtensionPage>>; + /** + * Lists InstalledAddOnExtensionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InstalledAddOnExtensionInstance[]) => any): Promise<InstalledAddOnExtensionInstance[]>; + list(params: InstalledAddOnExtensionListInstanceOptions, callback?: (error: Error | null, items: InstalledAddOnExtensionInstance[]) => any): Promise<InstalledAddOnExtensionInstance[]>; + /** + * Lists InstalledAddOnExtensionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionInstance[]>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance[]>>; + listWithHttpInfo(params: InstalledAddOnExtensionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionInstance[]>) => any): Promise<ApiResponse<InstalledAddOnExtensionInstance[]>>; + /** + * Retrieve a single page of InstalledAddOnExtensionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InstalledAddOnExtensionPage) => any): Promise<InstalledAddOnExtensionPage>; + page(params: InstalledAddOnExtensionListInstancePageOptions, callback?: (error: Error | null, items: InstalledAddOnExtensionPage) => any): Promise<InstalledAddOnExtensionPage>; + /** + * Retrieve a single page of InstalledAddOnExtensionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InstalledAddOnExtensionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionPage>) => any): Promise<ApiResponse<InstalledAddOnExtensionPage>>; + pageWithHttpInfo(params: InstalledAddOnExtensionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionPage>) => any): Promise<ApiResponse<InstalledAddOnExtensionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InstalledAddOnExtensionListInstance(version: Marketplace, installedAddOnSid: string): InstalledAddOnExtensionListInstance { + if (!isValidPathParam(installedAddOnSid)) { + throw new Error('Parameter \'installedAddOnSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as InstalledAddOnExtensionListInstance; + + instance.get = function get(sid, ): InstalledAddOnExtensionContext { + return new InstalledAddOnExtensionContextImpl(version, installedAddOnSid, sid); + } + + instance._version = version; + instance._solution = { installedAddOnSid, }; + instance._uri = `/InstalledAddOns/${installedAddOnSid}/Extensions`; + + instance.page = function page(params?: InstalledAddOnExtensionListInstancePageOptions | ((error: Error | null, items: InstalledAddOnExtensionPage) => any), callback?: (error: Error | null, items: InstalledAddOnExtensionPage) => any): Promise<InstalledAddOnExtensionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InstalledAddOnExtensionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InstalledAddOnExtensionPage) => any): Promise<InstalledAddOnExtensionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InstalledAddOnExtensionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InstalledAddOnExtensionListInstancePageOptions | ((error: Error | null, items: ApiResponse<InstalledAddOnExtensionPage>) => any), callback?: (error: Error | null, items: ApiResponse<InstalledAddOnExtensionPage>) => any): Promise<ApiResponse<InstalledAddOnExtensionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<InstalledAddOnExtensionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InstalledAddOnExtensionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<InstalledAddOnExtensionPage>) => any): Promise<ApiResponse<InstalledAddOnExtensionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<InstalledAddOnExtensionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InstalledAddOnExtensionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InstalledAddOnExtensionPage extends Page<Marketplace, InstalledAddOnExtensionPayload, InstalledAddOnExtensionResource, InstalledAddOnExtensionInstance> { +/** +* Initialize the InstalledAddOnExtensionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Marketplace, response: Response<string>, solution: InstalledAddOnExtensionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InstalledAddOnExtensionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InstalledAddOnExtensionResource): InstalledAddOnExtensionInstance { + + return new InstalledAddOnExtensionInstance( + this._version, + payload, + this._solution.installedAddOnSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/preview/wireless/command.ts b/rest/preview/wireless/command.ts new file mode 100644 index 000000000..ddabe4d18 --- /dev/null +++ b/rest/preview/wireless/command.ts @@ -0,0 +1,728 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import Wireless from "../Wireless"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to create a CommandInstance + */ +export interface CommandListInstanceCreateOptions { + /** */ + "command": string; + /** */ + "device"?: string; + /** */ + "sim"?: string; + /** */ + "callbackMethod"?: string; + /** */ + "callbackUrl"?: string; + /** */ + "commandMode"?: string; + /** */ + "includeSid"?: string; +} + +/** + * Options to pass to each + */ +export interface CommandListInstanceEachOptions { + /** */ + "device"?: string; + /** */ + "sim"?: string; + /** */ + "status"?: string; + /** */ + "direction"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CommandInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CommandListInstanceOptions { + /** */ + "device"?: string; + /** */ + "sim"?: string; + /** */ + "status"?: string; + /** */ + "direction"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CommandListInstancePageOptions { + /** */ + "device"?: string; + /** */ + "sim"?: string; + /** */ + "status"?: string; + /** */ + "direction"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CommandContext { + + /** + * Fetch a CommandInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance + */ + fetch(callback?: (error: Error | null, item?: CommandInstance) => any): Promise<CommandInstance> + + /** + * Fetch a CommandInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CommandInstance>) => any): Promise<ApiResponse<CommandInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CommandContextSolution { + "sid": string; +} + +export class CommandContextImpl implements CommandContext { + protected _solution: CommandContextSolution; + protected _uri: string; + + + constructor(protected _version: Wireless, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Commands/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: CommandInstance) => any): Promise<CommandInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CommandInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CommandInstance>) => any): Promise<ApiResponse<CommandInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CommandResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CommandInstance> => ({ + ...response, + body: new CommandInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CommandPayload extends TwilioResponsePayload { + commands: CommandResource[]; +} + +interface CommandResource { + sid: string; + account_sid: string; + device_sid: string; + sim_sid: string; + command: string; + command_mode: string; + status: string; + direction: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CommandInstance { + protected _solution: CommandContextSolution; + protected _context?: CommandContext; + + constructor(protected _version: Wireless, payload: CommandResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.deviceSid = (payload.device_sid); + this.simSid = (payload.sim_sid); + this.command = (payload.command); + this.commandMode = (payload.command_mode); + this.status = (payload.status); + this.direction = (payload.direction); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + sid: string; + accountSid: string; + deviceSid: string; + simSid: string; + command: string; + commandMode: string; + status: string; + direction: string; + dateCreated: Date; + dateUpdated: Date; + url: string; + + private get _proxy(): CommandContext { + this._context = this._context || new CommandContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a CommandInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance + */ + fetch(callback?: (error: Error | null, item?: CommandInstance) => any): Promise<CommandInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CommandInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CommandInstance>) => any): Promise<ApiResponse<CommandInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + deviceSid: this.deviceSid, + simSid: this.simSid, + command: this.command, + commandMode: this.commandMode, + status: this.status, + direction: this.direction, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CommandSolution { +} + +export interface CommandListInstance { + _version: Wireless; + _solution: CommandSolution; + _uri: string; + + (sid: string, ): CommandContext; + get(sid: string, ): CommandContext; + + + + + /** + * Create a CommandInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance + */ + create(params: CommandListInstanceCreateOptions, callback?: (error: Error | null, item?: CommandInstance) => any): Promise<CommandInstance>; + + /** + * Create a CommandInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance with HTTP metadata + */ + createWithHttpInfo(params: CommandListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CommandInstance>) => any): Promise<ApiResponse<CommandInstance>>; + + + + + /** + * Streams CommandInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CommandInstance, done: (err?: Error) => void) => void): void; + each(params: CommandListInstanceEachOptions, callback?: (item: CommandInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CommandInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CommandInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CommandListInstanceEachOptions, callback?: (item: CommandInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CommandInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CommandPage) => any): Promise<CommandPage>; + /** + * Retrieve a single target page of CommandInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CommandPage>) => any): Promise<ApiResponse<CommandPage>>; + /** + * Lists CommandInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CommandInstance[]) => any): Promise<CommandInstance[]>; + list(params: CommandListInstanceOptions, callback?: (error: Error | null, items: CommandInstance[]) => any): Promise<CommandInstance[]>; + /** + * Lists CommandInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CommandInstance[]>) => any): Promise<ApiResponse<CommandInstance[]>>; + listWithHttpInfo(params: CommandListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CommandInstance[]>) => any): Promise<ApiResponse<CommandInstance[]>>; + /** + * Retrieve a single page of CommandInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CommandPage) => any): Promise<CommandPage>; + page(params: CommandListInstancePageOptions, callback?: (error: Error | null, items: CommandPage) => any): Promise<CommandPage>; + /** + * Retrieve a single page of CommandInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CommandPage>) => any): Promise<ApiResponse<CommandPage>>; + pageWithHttpInfo(params: CommandListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CommandPage>) => any): Promise<ApiResponse<CommandPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CommandListInstance(version: Wireless): CommandListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CommandListInstance; + + instance.get = function get(sid, ): CommandContext { + return new CommandContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Commands`; + + instance.create = function create(params: CommandListInstanceCreateOptions, callback?: (error: Error | null, items: CommandInstance) => any): Promise<CommandInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["command"] === null || params["command"] === undefined) { + throw new Error('Required parameter "params[\'command\']" missing.'); + } + + let data: any = {}; + + + + data["Command"] = params["command"]; + if (params["device"] !== undefined) + data["Device"] = params["device"]; + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["commandMode"] !== undefined) + data["CommandMode"] = params["commandMode"]; + if (params["includeSid"] !== undefined) + data["IncludeSid"] = params["includeSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CommandInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CommandListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<CommandInstance>) => any): Promise<ApiResponse<CommandInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["command"] === null || params["command"] === undefined) { + throw new Error('Required parameter "params[\'command\']" missing.'); + } + + let data: any = {}; + + + + data["Command"] = params["command"]; + if (params["device"] !== undefined) + data["Device"] = params["device"]; + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["commandMode"] !== undefined) + data["CommandMode"] = params["commandMode"]; + if (params["includeSid"] !== undefined) + data["IncludeSid"] = params["includeSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CommandResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CommandInstance> => ({ + ...response, + body: new CommandInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CommandListInstancePageOptions | ((error: Error | null, items: CommandPage) => any), callback?: (error: Error | null, items: CommandPage) => any): Promise<CommandPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["device"] !== undefined) + data["Device"] = params["device"]; + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CommandPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CommandPage) => any): Promise<CommandPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CommandPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CommandListInstancePageOptions | ((error: Error | null, items: ApiResponse<CommandPage>) => any), callback?: (error: Error | null, items: ApiResponse<CommandPage>) => any): Promise<ApiResponse<CommandPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["device"] !== undefined) + data["Device"] = params["device"]; + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CommandPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CommandPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CommandPage>) => any): Promise<ApiResponse<CommandPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CommandPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CommandPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CommandPage extends Page<Wireless, CommandPayload, CommandResource, CommandInstance> { +/** +* Initialize the CommandPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Wireless, response: Response<string>, solution: CommandSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CommandInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CommandResource): CommandInstance { + + return new CommandInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/preview/wireless/ratePlan.ts b/rest/preview/wireless/ratePlan.ts new file mode 100644 index 000000000..7e5254384 --- /dev/null +++ b/rest/preview/wireless/ratePlan.ts @@ -0,0 +1,977 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import Wireless from "../Wireless"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a RatePlanInstance + */ +export interface RatePlanContextUpdateOptions { + /** */ + "uniqueName"?: string; + /** */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a RatePlanInstance + */ +export interface RatePlanListInstanceCreateOptions { + /** */ + "uniqueName"?: string; + /** */ + "friendlyName"?: string; + /** */ + "dataEnabled"?: boolean; + /** */ + "dataLimit"?: number; + /** */ + "dataMetering"?: string; + /** */ + "messagingEnabled"?: boolean; + /** */ + "voiceEnabled"?: boolean; + /** */ + "commandsEnabled"?: boolean; + /** */ + "nationalRoamingEnabled"?: boolean; + /** */ + "internationalRoaming"?: Array<string>; +} + +/** + * Options to pass to each + */ +export interface RatePlanListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RatePlanInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RatePlanListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RatePlanListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RatePlanContext { + + /** + * Remove a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + fetch(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance> + + /** + * Fetch a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> + + /** + * Update a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + update(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + /** + * Update a RatePlanInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + update(params: RatePlanContextUpdateOptions, callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + + /** + * Update a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + /** + * Update a RatePlanInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + updateWithHttpInfo(params: RatePlanContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RatePlanContextSolution { + "sid": string; +} + +export class RatePlanContextImpl implements RatePlanContext { + protected _solution: RatePlanContextSolution; + protected _uri: string; + + + constructor(protected _version: Wireless, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/RatePlans/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RatePlanInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RatePlanResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<RatePlanInstance> => ({ + ...response, + body: new RatePlanInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: RatePlanContextUpdateOptions | ((error: Error | null, item?: RatePlanInstance) => any),callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RatePlanInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: RatePlanContextUpdateOptions | ((error: Error | null, item?: ApiResponse<RatePlanInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<RatePlanResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RatePlanInstance> => ({ + ...response, + body: new RatePlanInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RatePlanPayload extends TwilioResponsePayload { + rate_plans: RatePlanResource[]; +} + +interface RatePlanResource { + sid: string; + unique_name: string; + account_sid: string; + friendly_name: string; + data_enabled: boolean; + data_metering: string; + data_limit: number; + messaging_enabled: boolean; + voice_enabled: boolean; + national_roaming_enabled: boolean; + international_roaming: Array<string>; + date_created: Date; + date_updated: Date; + url: string; +} + +export class RatePlanInstance { + protected _solution: RatePlanContextSolution; + protected _context?: RatePlanContext; + + constructor(protected _version: Wireless, payload: RatePlanResource, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dataEnabled = (payload.data_enabled); + this.dataMetering = (payload.data_metering); + this.dataLimit = deserialize.integer(payload.data_limit); + this.messagingEnabled = (payload.messaging_enabled); + this.voiceEnabled = (payload.voice_enabled); + this.nationalRoamingEnabled = (payload.national_roaming_enabled); + this.internationalRoaming = (payload.international_roaming); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + sid: string; + uniqueName: string; + accountSid: string; + friendlyName: string; + dataEnabled: boolean; + dataMetering: string; + dataLimit: number; + messagingEnabled: boolean; + voiceEnabled: boolean; + nationalRoamingEnabled: boolean; + internationalRoaming: Array<string>; + dateCreated: Date; + dateUpdated: Date; + url: string; + + private get _proxy(): RatePlanContext { + this._context = this._context || new RatePlanContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + fetch(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + update(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + /** + * Update a RatePlanInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + update(params: RatePlanContextUpdateOptions, callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + + update(params?: any, callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + /** + * Update a RatePlanInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + updateWithHttpInfo(params: RatePlanContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dataEnabled: this.dataEnabled, + dataMetering: this.dataMetering, + dataLimit: this.dataLimit, + messagingEnabled: this.messagingEnabled, + voiceEnabled: this.voiceEnabled, + nationalRoamingEnabled: this.nationalRoamingEnabled, + internationalRoaming: this.internationalRoaming, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RatePlanSolution { +} + +export interface RatePlanListInstance { + _version: Wireless; + _solution: RatePlanSolution; + _uri: string; + + (sid: string, ): RatePlanContext; + get(sid: string, ): RatePlanContext; + + + + + + + + + /** + * Create a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + create(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + /** + * Create a RatePlanInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + create(params: RatePlanListInstanceCreateOptions, callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + + /** + * Create a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + /** + * Create a RatePlanInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + createWithHttpInfo(params: RatePlanListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + + + + + /** + * Streams RatePlanInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RatePlanInstance, done: (err?: Error) => void) => void): void; + each(params: RatePlanListInstanceEachOptions, callback?: (item: RatePlanInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RatePlanInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RatePlanInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RatePlanListInstanceEachOptions, callback?: (item: RatePlanInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RatePlanInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RatePlanPage) => any): Promise<RatePlanPage>; + /** + * Retrieve a single target page of RatePlanInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RatePlanPage>) => any): Promise<ApiResponse<RatePlanPage>>; + /** + * Lists RatePlanInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RatePlanInstance[]) => any): Promise<RatePlanInstance[]>; + list(params: RatePlanListInstanceOptions, callback?: (error: Error | null, items: RatePlanInstance[]) => any): Promise<RatePlanInstance[]>; + /** + * Lists RatePlanInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RatePlanInstance[]>) => any): Promise<ApiResponse<RatePlanInstance[]>>; + listWithHttpInfo(params: RatePlanListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RatePlanInstance[]>) => any): Promise<ApiResponse<RatePlanInstance[]>>; + /** + * Retrieve a single page of RatePlanInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RatePlanPage) => any): Promise<RatePlanPage>; + page(params: RatePlanListInstancePageOptions, callback?: (error: Error | null, items: RatePlanPage) => any): Promise<RatePlanPage>; + /** + * Retrieve a single page of RatePlanInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RatePlanPage>) => any): Promise<ApiResponse<RatePlanPage>>; + pageWithHttpInfo(params: RatePlanListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RatePlanPage>) => any): Promise<ApiResponse<RatePlanPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RatePlanListInstance(version: Wireless): RatePlanListInstance { + const instance = ((sid, ) => instance.get(sid, )) as RatePlanListInstance; + + instance.get = function get(sid, ): RatePlanContext { + return new RatePlanContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/RatePlans`; + + instance.create = function create(params?: RatePlanListInstanceCreateOptions | ((error: Error | null, items: RatePlanInstance) => any), callback?: (error: Error | null, items: RatePlanInstance) => any): Promise<RatePlanInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["dataEnabled"] !== undefined) + data["DataEnabled"] = serialize.bool(params["dataEnabled"]); + if (params["dataLimit"] !== undefined) + data["DataLimit"] = params["dataLimit"]; + if (params["dataMetering"] !== undefined) + data["DataMetering"] = params["dataMetering"]; + if (params["messagingEnabled"] !== undefined) + data["MessagingEnabled"] = serialize.bool(params["messagingEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["commandsEnabled"] !== undefined) + data["CommandsEnabled"] = serialize.bool(params["commandsEnabled"]); + if (params["nationalRoamingEnabled"] !== undefined) + data["NationalRoamingEnabled"] = serialize.bool(params["nationalRoamingEnabled"]); + if (params["internationalRoaming"] !== undefined) + data["InternationalRoaming"] = serialize.map(params["internationalRoaming"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RatePlanInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: RatePlanListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<RatePlanInstance>) => any), callback?: (error: Error | null, items: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["dataEnabled"] !== undefined) + data["DataEnabled"] = serialize.bool(params["dataEnabled"]); + if (params["dataLimit"] !== undefined) + data["DataLimit"] = params["dataLimit"]; + if (params["dataMetering"] !== undefined) + data["DataMetering"] = params["dataMetering"]; + if (params["messagingEnabled"] !== undefined) + data["MessagingEnabled"] = serialize.bool(params["messagingEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["commandsEnabled"] !== undefined) + data["CommandsEnabled"] = serialize.bool(params["commandsEnabled"]); + if (params["nationalRoamingEnabled"] !== undefined) + data["NationalRoamingEnabled"] = serialize.bool(params["nationalRoamingEnabled"]); + if (params["internationalRoaming"] !== undefined) + data["InternationalRoaming"] = serialize.map(params["internationalRoaming"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<RatePlanResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RatePlanInstance> => ({ + ...response, + body: new RatePlanInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RatePlanListInstancePageOptions | ((error: Error | null, items: RatePlanPage) => any), callback?: (error: Error | null, items: RatePlanPage) => any): Promise<RatePlanPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RatePlanPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RatePlanPage) => any): Promise<RatePlanPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RatePlanPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RatePlanListInstancePageOptions | ((error: Error | null, items: ApiResponse<RatePlanPage>) => any), callback?: (error: Error | null, items: ApiResponse<RatePlanPage>) => any): Promise<ApiResponse<RatePlanPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RatePlanPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RatePlanPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RatePlanPage>) => any): Promise<ApiResponse<RatePlanPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RatePlanPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RatePlanPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RatePlanPage extends Page<Wireless, RatePlanPayload, RatePlanResource, RatePlanInstance> { +/** +* Initialize the RatePlanPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Wireless, response: Response<string>, solution: RatePlanSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RatePlanInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RatePlanResource): RatePlanInstance { + + return new RatePlanInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/preview/wireless/sim.ts b/rest/preview/wireless/sim.ts new file mode 100644 index 000000000..19316e5ef --- /dev/null +++ b/rest/preview/wireless/sim.ts @@ -0,0 +1,913 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import Wireless from "../Wireless"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { UsageListInstance } from "./sim/usage"; + + + + +/** + * Options to pass to update a SimInstance + */ +export interface SimContextUpdateOptions { + /** */ + "uniqueName"?: string; + /** */ + "callbackMethod"?: string; + /** */ + "callbackUrl"?: string; + /** */ + "friendlyName"?: string; + /** */ + "ratePlan"?: string; + /** */ + "status"?: string; + /** */ + "commandsCallbackMethod"?: string; + /** */ + "commandsCallbackUrl"?: string; + /** */ + "smsFallbackMethod"?: string; + /** */ + "smsFallbackUrl"?: string; + /** */ + "smsMethod"?: string; + /** */ + "smsUrl"?: string; + /** */ + "voiceFallbackMethod"?: string; + /** */ + "voiceFallbackUrl"?: string; + /** */ + "voiceMethod"?: string; + /** */ + "voiceUrl"?: string; +} + +/** + * Options to pass to each + */ +export interface SimListInstanceEachOptions { + /** */ + "status"?: string; + /** */ + "iccid"?: string; + /** */ + "ratePlan"?: string; + /** */ + "eId"?: string; + /** */ + "simRegistrationCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SimInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SimListInstanceOptions { + /** */ + "status"?: string; + /** */ + "iccid"?: string; + /** */ + "ratePlan"?: string; + /** */ + "eId"?: string; + /** */ + "simRegistrationCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SimListInstancePageOptions { + /** */ + "status"?: string; + /** */ + "iccid"?: string; + /** */ + "ratePlan"?: string; + /** */ + "eId"?: string; + /** */ + "simRegistrationCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SimContext { + usage: UsageListInstance; + + /** + * Fetch a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + fetch(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> + + /** + * Fetch a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> + + /** + * Update a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + /** + * Update a SimInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + + /** + * Update a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + /** + * Update a SimInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SimContextSolution { + "sid": string; +} + +export class SimContextImpl implements SimContext { + protected _solution: SimContextSolution; + protected _uri: string; + + protected _usage?: UsageListInstance; + + constructor(protected _version: Wireless, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Sims/${sid}`; + } + + get usage(): UsageListInstance { + this._usage = this._usage || UsageListInstance(this._version, this._solution.sid); + return this._usage; + } + + fetch(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SimInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SimResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SimInstance> => ({ + ...response, + body: new SimInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SimContextUpdateOptions | ((error: Error | null, item?: SimInstance) => any),callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["ratePlan"] !== undefined) + data["RatePlan"] = params["ratePlan"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["commandsCallbackMethod"] !== undefined) + data["CommandsCallbackMethod"] = params["commandsCallbackMethod"]; + if (params["commandsCallbackUrl"] !== undefined) + data["CommandsCallbackUrl"] = params["commandsCallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SimInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SimContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SimInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["ratePlan"] !== undefined) + data["RatePlan"] = params["ratePlan"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["commandsCallbackMethod"] !== undefined) + data["CommandsCallbackMethod"] = params["commandsCallbackMethod"]; + if (params["commandsCallbackUrl"] !== undefined) + data["CommandsCallbackUrl"] = params["commandsCallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SimResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SimInstance> => ({ + ...response, + body: new SimInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SimPayload extends TwilioResponsePayload { + sims: SimResource[]; +} + +interface SimResource { + sid: string; + unique_name: string; + account_sid: string; + rate_plan_sid: string; + friendly_name: string; + iccid: string; + e_id: string; + status: string; + commands_callback_url: string; + commands_callback_method: string; + sms_fallback_method: string; + sms_fallback_url: string; + sms_method: string; + sms_url: string; + voice_fallback_method: string; + voice_fallback_url: string; + voice_method: string; + voice_url: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class SimInstance { + protected _solution: SimContextSolution; + protected _context?: SimContext; + + constructor(protected _version: Wireless, payload: SimResource, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.ratePlanSid = (payload.rate_plan_sid); + this.friendlyName = (payload.friendly_name); + this.iccid = (payload.iccid); + this.eId = (payload.e_id); + this.status = (payload.status); + this.commandsCallbackUrl = (payload.commands_callback_url); + this.commandsCallbackMethod = (payload.commands_callback_method); + this.smsFallbackMethod = (payload.sms_fallback_method); + this.smsFallbackUrl = (payload.sms_fallback_url); + this.smsMethod = (payload.sms_method); + this.smsUrl = (payload.sms_url); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceMethod = (payload.voice_method); + this.voiceUrl = (payload.voice_url); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + sid: string; + uniqueName: string; + accountSid: string; + ratePlanSid: string; + friendlyName: string; + iccid: string; + eId: string; + status: string; + commandsCallbackUrl: string; + commandsCallbackMethod: string; + smsFallbackMethod: string; + smsFallbackUrl: string; + smsMethod: string; + smsUrl: string; + voiceFallbackMethod: string; + voiceFallbackUrl: string; + voiceMethod: string; + voiceUrl: string; + dateCreated: Date; + dateUpdated: Date; + url: string; + links: Record<string, string>; + + private get _proxy(): SimContext { + this._context = this._context || new SimContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + fetch(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + /** + * Update a SimInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + /** + * Update a SimInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the usage. + */ + usage(): UsageListInstance { + return this._proxy.usage; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + ratePlanSid: this.ratePlanSid, + friendlyName: this.friendlyName, + iccid: this.iccid, + eId: this.eId, + status: this.status, + commandsCallbackUrl: this.commandsCallbackUrl, + commandsCallbackMethod: this.commandsCallbackMethod, + smsFallbackMethod: this.smsFallbackMethod, + smsFallbackUrl: this.smsFallbackUrl, + smsMethod: this.smsMethod, + smsUrl: this.smsUrl, + voiceFallbackMethod: this.voiceFallbackMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceMethod: this.voiceMethod, + voiceUrl: this.voiceUrl, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SimSolution { +} + +export interface SimListInstance { + _version: Wireless; + _solution: SimSolution; + _uri: string; + + (sid: string, ): SimContext; + get(sid: string, ): SimContext; + + + + + + + + /** + * Streams SimInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + each(params: SimListInstanceEachOptions, callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SimInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SimListInstanceEachOptions, callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SimInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage>; + /** + * Retrieve a single target page of SimInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>>; + /** + * Lists SimInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SimInstance[]) => any): Promise<SimInstance[]>; + list(params: SimListInstanceOptions, callback?: (error: Error | null, items: SimInstance[]) => any): Promise<SimInstance[]>; + /** + * Lists SimInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SimInstance[]>) => any): Promise<ApiResponse<SimInstance[]>>; + listWithHttpInfo(params: SimListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SimInstance[]>) => any): Promise<ApiResponse<SimInstance[]>>; + /** + * Retrieve a single page of SimInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage>; + page(params: SimListInstancePageOptions, callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage>; + /** + * Retrieve a single page of SimInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>>; + pageWithHttpInfo(params: SimListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SimListInstance(version: Wireless): SimListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SimListInstance; + + instance.get = function get(sid, ): SimContext { + return new SimContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Sims`; + + instance.page = function page(params?: SimListInstancePageOptions | ((error: Error | null, items: SimPage) => any), callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["iccid"] !== undefined) + data["Iccid"] = params["iccid"]; + if (params["ratePlan"] !== undefined) + data["RatePlan"] = params["ratePlan"]; + if (params["eId"] !== undefined) + data["EId"] = params["eId"]; + if (params["simRegistrationCode"] !== undefined) + data["SimRegistrationCode"] = params["simRegistrationCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SimPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SimPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SimListInstancePageOptions | ((error: Error | null, items: ApiResponse<SimPage>) => any), callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["iccid"] !== undefined) + data["Iccid"] = params["iccid"]; + if (params["ratePlan"] !== undefined) + data["RatePlan"] = params["ratePlan"]; + if (params["eId"] !== undefined) + data["EId"] = params["eId"]; + if (params["simRegistrationCode"] !== undefined) + data["SimRegistrationCode"] = params["simRegistrationCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SimPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SimPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SimPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SimPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SimPage extends Page<Wireless, SimPayload, SimResource, SimInstance> { +/** +* Initialize the SimPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Wireless, response: Response<string>, solution: SimSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SimInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SimResource): SimInstance { + + return new SimInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/preview/wireless/sim/usage.ts b/rest/preview/wireless/sim/usage.ts new file mode 100644 index 000000000..94c77bc10 --- /dev/null +++ b/rest/preview/wireless/sim/usage.ts @@ -0,0 +1,351 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Preview + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import Wireless from "../../Wireless"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a UsageInstance + */ +export interface UsageContextFetchOptions { + /** */ + "end"?: string; + /** */ + "start"?: string; +} + +export interface UsageContext { + + /** + * Fetch a UsageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsageInstance + */ + fetch(callback?: (error: Error | null, item?: UsageInstance) => any): Promise<UsageInstance>; + /** + * Fetch a UsageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsageInstance + */ + fetch(params: UsageContextFetchOptions, callback?: (error: Error | null, item?: UsageInstance) => any): Promise<UsageInstance>; + + /** + * Fetch a UsageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UsageInstance>) => any): Promise<ApiResponse<UsageInstance>>; + /** + * Fetch a UsageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsageInstance with HTTP metadata + */ + fetchWithHttpInfo(params: UsageContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<UsageInstance>) => any): Promise<ApiResponse<UsageInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UsageContextSolution { + "simSid": string; +} + +export class UsageContextImpl implements UsageContext { + protected _solution: UsageContextSolution; + protected _uri: string; + + + constructor(protected _version: Wireless, simSid: string) { + if (!isValidPathParam(simSid)) { + throw new Error('Parameter \'simSid\' is not valid.'); + } + + this._solution = { simSid, }; + this._uri = `/Sims/${simSid}/Usage`; + } + + fetch(params?: UsageContextFetchOptions | ((error: Error | null, item?: UsageInstance) => any),callback?: (error: Error | null, item?: UsageInstance) => any): Promise<UsageInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["end"] !== undefined) + data["End"] = params["end"]; + if (params["start"] !== undefined) + data["Start"] = params["start"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new UsageInstance(operationVersion, payload, instance._solution.simSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: UsageContextFetchOptions | ((error: Error | null, item?: ApiResponse<UsageInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<UsageInstance>) => any): Promise<ApiResponse<UsageInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["end"] !== undefined) + data["End"] = params["end"]; + if (params["start"] !== undefined) + data["Start"] = params["start"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<UsageResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<UsageInstance> => ({ + ...response, + body: new UsageInstance(operationVersion, response.body, instance._solution.simSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UsagePayload extends UsageResource {} + +interface UsageResource { + sim_sid: string; + sim_unique_name: string; + account_sid: string; + period: any; + commands_usage: any; + commands_costs: any; + data_usage: any; + data_costs: any; + url: string; +} + +export class UsageInstance { + protected _solution: UsageContextSolution; + protected _context?: UsageContext; + + constructor(protected _version: Wireless, payload: UsageResource, simSid: string) { + + this.simSid = (payload.sim_sid); + this.simUniqueName = (payload.sim_unique_name); + this.accountSid = (payload.account_sid); + this.period = (payload.period); + this.commandsUsage = (payload.commands_usage); + this.commandsCosts = (payload.commands_costs); + this.dataUsage = (payload.data_usage); + this.dataCosts = (payload.data_costs); + this.url = (payload.url); + + this._solution = { simSid, }; + } + + simSid: string; + simUniqueName: string; + accountSid: string; + period: any; + commandsUsage: any; + commandsCosts: any; + dataUsage: any; + dataCosts: any; + url: string; + + private get _proxy(): UsageContext { + this._context = this._context || new UsageContextImpl(this._version, this._solution.simSid); + return this._context; + } + + /** + * Fetch a UsageInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsageInstance + */ + fetch(callback?: (error: Error | null, item?: UsageInstance) => any): Promise<UsageInstance>; + /** + * Fetch a UsageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsageInstance + */ + fetch(params: UsageContextFetchOptions, callback?: (error: Error | null, item?: UsageInstance) => any): Promise<UsageInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: UsageInstance) => any): Promise<UsageInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a UsageInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsageInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UsageInstance>) => any): Promise<ApiResponse<UsageInstance>>; + /** + * Fetch a UsageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UsageInstance with HTTP metadata + */ + fetchWithHttpInfo(params: UsageContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<UsageInstance>) => any): Promise<ApiResponse<UsageInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<UsageInstance>) => any): Promise<ApiResponse<UsageInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + simSid: this.simSid, + simUniqueName: this.simUniqueName, + accountSid: this.accountSid, + period: this.period, + commandsUsage: this.commandsUsage, + commandsCosts: this.commandsCosts, + dataUsage: this.dataUsage, + dataCosts: this.dataCosts, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UsageSolution { + simSid: string; +} + +export interface UsageListInstance { + _version: Wireless; + _solution: UsageSolution; + _uri: string; + + (): UsageContext; + get(): UsageContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UsageListInstance(version: Wireless, simSid: string): UsageListInstance { + if (!isValidPathParam(simSid)) { + throw new Error('Parameter \'simSid\' is not valid.'); + } + + const instance = (() => instance.get()) as UsageListInstance; + + instance.get = function get(): UsageContext { + return new UsageContextImpl(version, simSid); + } + + instance._version = version; + instance._solution = { simSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/previewIam/Organizations.ts b/rest/previewIam/Organizations.ts new file mode 100644 index 000000000..17248f50d --- /dev/null +++ b/rest/previewIam/Organizations.ts @@ -0,0 +1,56 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import PreviewIamBase from "../PreviewIamBase"; +import Version from "../../base/Version"; +import { AccountListInstance } from "./organizations/account"; +import { RoleAssignmentListInstance } from "./organizations/roleAssignment"; +import { UserListInstance } from "./organizations/user"; + +export default class Organizations extends Version { + /** + * Initialize the Organizations version of PreviewIam + * + * @param domain - The Twilio (Twilio.PreviewIam) domain + */ + constructor(domain: PreviewIamBase) { + super(domain, "Organizations"); + } + + /** accounts - { Twilio.PreviewIam.Organizations.AccountListInstance } resource */ + protected _accounts?: AccountListInstance; + /** roleAssignments - { Twilio.PreviewIam.Organizations.RoleAssignmentListInstance } resource */ + protected _roleAssignments?: RoleAssignmentListInstance; + /** users - { Twilio.PreviewIam.Organizations.UserListInstance } resource */ + protected _users?: UserListInstance; + + /** Getter for accounts resource */ + get accounts(): AccountListInstance { + this._accounts = this._accounts || AccountListInstance(this); + return this._accounts; + } + + /** Getter for roleAssignments resource */ + get roleAssignments(): RoleAssignmentListInstance { + this._roleAssignments = this._roleAssignments || RoleAssignmentListInstance(this); + return this._roleAssignments; + } + + /** Getter for users resource */ + get users(): UserListInstance { + this._users = this._users || UserListInstance(this); + return this._users; + } + +} diff --git a/rest/previewIam/V1.ts b/rest/previewIam/V1.ts new file mode 100644 index 000000000..32cd1a520 --- /dev/null +++ b/rest/previewIam/V1.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import PreviewIamBase from "../PreviewIamBase"; +import Version from "../../base/Version"; +import { AuthorizeListInstance } from "./v1/authorize"; +import { TokenListInstance } from "./v1/token"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of PreviewIam + * + * @param domain - The Twilio (Twilio.PreviewIam) domain + */ + constructor(domain: PreviewIamBase) { + super(domain, "v1"); + } + + /** authorize - { Twilio.PreviewIam.V1.AuthorizeListInstance } resource */ + protected _authorize?: AuthorizeListInstance; + /** token - { Twilio.PreviewIam.V1.TokenListInstance } resource */ + protected _token?: TokenListInstance; + + /** Getter for authorize resource */ + get authorize(): AuthorizeListInstance { + this._authorize = this._authorize || AuthorizeListInstance(this); + return this._authorize; + } + + /** Getter for token resource */ + get token(): TokenListInstance { + this._token = this._token || TokenListInstance(this); + return this._token; + } + +} diff --git a/rest/previewIam/Versionless.ts b/rest/previewIam/Versionless.ts new file mode 100644 index 000000000..d137c4827 --- /dev/null +++ b/rest/previewIam/Versionless.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import PreviewIamBase from "../PreviewIamBase"; +import Version from "../../base/Version"; +import { OrganizationListInstance } from "./versionless/organization"; + +export default class Versionless extends Version { + /** + * Initialize the Versionless version of PreviewIam + * + * @param domain - The Twilio (Twilio.PreviewIam) domain + */ + constructor(domain: PreviewIamBase) { + super(domain, "Organizations"); + } + + /** organization - { Twilio.PreviewIam.Versionless.OrganizationListInstance } resource */ + protected _organization?: OrganizationListInstance; + + /** Getter for organization resource */ + get organization(): OrganizationListInstance { + this._organization = this._organization || OrganizationListInstance(this); + return this._organization; + } + +} diff --git a/rest/previewIam/organizations/account.ts b/rest/previewIam/organizations/account.ts new file mode 100644 index 000000000..96a2dabec --- /dev/null +++ b/rest/previewIam/organizations/account.ts @@ -0,0 +1,558 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import Organizations from "../Organizations"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface AccountListInstanceEachOptions { + /** */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AccountInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AccountListInstanceOptions { + /** */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AccountListInstancePageOptions { + /** */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AccountContext { + + /** + * Fetch a AccountInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + fetch(callback?: (error: Error | null, item?: AccountInstance) => any): Promise<AccountInstance> + + /** + * Fetch a AccountInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountInstance>) => any): Promise<ApiResponse<AccountInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AccountContextSolution { + "organizationSid": string; + "accountSid": string; +} + +export class AccountContextImpl implements AccountContext { + protected _solution: AccountContextSolution; + protected _uri: string; + + + constructor(protected _version: Organizations, organizationSid: string, accountSid: string) { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + this._solution = { organizationSid, accountSid, }; + this._uri = `/${organizationSid}/Accounts/${accountSid}`; + } + + fetch(callback?: (error: Error | null, item?: AccountInstance) => any): Promise<AccountInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AccountInstance(operationVersion, payload, instance._solution.organizationSid, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountInstance>) => any): Promise<ApiResponse<AccountInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AccountResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AccountInstance> => ({ + ...response, + body: new AccountInstance(operationVersion, response.body, instance._solution.organizationSid, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AccountPayload extends TwilioResponsePayload { + content: AccountResource[]; +} + +interface AccountResource { + account_sid: string; + friendly_name: string; + status: string; + owner_sid: string; + date_created: Date; +} + +/** + * Page content + */ +export class AccountInstance { + protected _solution: AccountContextSolution; + protected _context?: AccountContext; + + constructor(protected _version: Organizations, payload: AccountResource, organizationSid?: string, accountSid?: string) { + + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.status = (payload.status); + this.ownerSid = (payload.owner_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + + this._solution = { organizationSid: organizationSid, accountSid: accountSid, }; + } + + /** + * Twilio account sid + */ + accountSid: string; + /** + * Account friendly name + */ + friendlyName: string; + /** + * Account status + */ + status: string; + /** + * Twilio account sid + */ + ownerSid: string; + /** + * The date and time when the account was created in the system + */ + dateCreated: Date; + + private get _proxy(): AccountContext { + this._context = this._context || new AccountContextImpl(this._version, this._solution.organizationSid, this._solution.accountSid); + return this._context; + } + + /** + * Fetch a AccountInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + fetch(callback?: (error: Error | null, item?: AccountInstance) => any): Promise<AccountInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AccountInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountInstance>) => any): Promise<ApiResponse<AccountInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + friendlyName: this.friendlyName, + status: this.status, + ownerSid: this.ownerSid, + dateCreated: this.dateCreated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AccountSolution { + organizationSid: string; +} + +export interface AccountListInstance { + _version: Organizations; + _solution: AccountSolution; + _uri: string; + + (organizationSid: string, accountSid: string, ): AccountContext; + get(organizationSid: string, accountSid: string, ): AccountContext; + + + + + + /** + * Streams AccountInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + each(params: AccountListInstanceEachOptions, callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AccountInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AccountListInstanceEachOptions, callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AccountInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AccountPage) => any): Promise<AccountPage>; + /** + * Retrieve a single target page of AccountInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AccountPage>) => any): Promise<ApiResponse<AccountPage>>; + /** + * Lists AccountInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AccountInstance[]) => any): Promise<AccountInstance[]>; + list(params: AccountListInstanceOptions, callback?: (error: Error | null, items: AccountInstance[]) => any): Promise<AccountInstance[]>; + /** + * Lists AccountInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AccountInstance[]>) => any): Promise<ApiResponse<AccountInstance[]>>; + listWithHttpInfo(params: AccountListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AccountInstance[]>) => any): Promise<ApiResponse<AccountInstance[]>>; + /** + * Retrieve a single page of AccountInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AccountPage) => any): Promise<AccountPage>; + page(params: AccountListInstancePageOptions, callback?: (error: Error | null, items: AccountPage) => any): Promise<AccountPage>; + /** + * Retrieve a single page of AccountInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AccountPage>) => any): Promise<ApiResponse<AccountPage>>; + pageWithHttpInfo(params: AccountListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AccountPage>) => any): Promise<ApiResponse<AccountPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AccountListInstance(version: Organizations, organizationSid: string): AccountListInstance { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + const instance = ((organizationSid, accountSid, ) => instance.get(organizationSid, accountSid, )) as AccountListInstance; + + instance.get = function get(organizationSid, accountSid, ): AccountContext { + return new AccountContextImpl(version, organizationSid, accountSid); + } + + instance._version = version; + instance._solution = { organizationSid, }; + instance._uri = `/${organizationSid}/Accounts`; + + instance.page = function page(params?: AccountListInstancePageOptions | ((error: Error | null, items: AccountPage) => any), callback?: (error: Error | null, items: AccountPage) => any): Promise<AccountPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AccountPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AccountPage) => any): Promise<AccountPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AccountPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AccountListInstancePageOptions | ((error: Error | null, items: ApiResponse<AccountPage>) => any), callback?: (error: Error | null, items: ApiResponse<AccountPage>) => any): Promise<ApiResponse<AccountPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AccountPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AccountPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AccountPage>) => any): Promise<ApiResponse<AccountPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AccountPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AccountPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AccountPage extends Page<Organizations, AccountPayload, AccountResource, AccountInstance> { +/** +* Initialize the AccountPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Organizations, response: Response<string>, solution: AccountSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AccountInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AccountResource): AccountInstance { + + return new AccountInstance( + this._version, + payload, + this._solution.organizationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/previewIam/organizations/roleAssignment.ts b/rest/previewIam/organizations/roleAssignment.ts new file mode 100644 index 000000000..5df4131eb --- /dev/null +++ b/rest/previewIam/organizations/roleAssignment.ts @@ -0,0 +1,751 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import Organizations from "../Organizations"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class PublicApiCreateRoleAssignmentRequest { + /** + * Twilio Role Sid representing assigned role + */ + "roleSid": string; + /** + * Twilio Sid representing scope of this assignment + */ + "scope": string; + /** + * Twilio Sid representing identity of this assignment + */ + "identity": string; + /** + * The resource type for resource-level role assignments + */ + "resourceType"?: string | null; + /** + * The resource id for resource-level role assignments + */ + "resourceId"?: string | null; + + constructor(payload) { + this.roleSid = payload["role_sid"]; + this.scope = payload["scope"]; + this.identity = payload["identity"]; + this.resourceType = payload["resource_type"]; + this.resourceId = payload["resource_id"]; + } +} + + + + +/** + * Options to pass to create a RoleAssignmentInstance + */ +export interface RoleAssignmentListInstanceCreateOptions { + /** */ + "publicApiCreateRoleAssignmentRequest": PublicApiCreateRoleAssignmentRequest; +} + +/** + * Options to pass to each + */ +export interface RoleAssignmentListInstanceEachOptions { + /** */ + "pageSize"?: number; + /** */ + "identity"?: string; + /** */ + "scope"?: string; + /** Filter by resource type for resource-level role assignments */ + "resourceType"?: string; + /** Filter by resource id for resource-level role assignments */ + "resourceId"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoleAssignmentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoleAssignmentListInstanceOptions { + /** */ + "pageSize"?: number; + /** */ + "identity"?: string; + /** */ + "scope"?: string; + /** Filter by resource type for resource-level role assignments */ + "resourceType"?: string; + /** Filter by resource id for resource-level role assignments */ + "resourceId"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoleAssignmentListInstancePageOptions { + /** */ + "pageSize"?: number; + /** */ + "identity"?: string; + /** */ + "scope"?: string; + /** Filter by resource type for resource-level role assignments */ + "resourceType"?: string; + /** Filter by resource id for resource-level role assignments */ + "resourceId"?: string; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoleAssignmentContext { + + /** + * Remove a RoleAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a RoleAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoleAssignmentContextSolution { + "organizationSid": string; + "roleAssignmentSid": string; +} + +export class RoleAssignmentContextImpl implements RoleAssignmentContext { + protected _solution: RoleAssignmentContextSolution; + protected _uri: string; + + + constructor(protected _version: Organizations, organizationSid: string, roleAssignmentSid: string) { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + if (!isValidPathParam(roleAssignmentSid)) { + throw new Error('Parameter \'roleAssignmentSid\' is not valid.'); + } + + this._solution = { organizationSid, roleAssignmentSid, }; + this._uri = `/${organizationSid}/RoleAssignments/${roleAssignmentSid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RoleAssignmentPayload extends TwilioResponsePayload { + content: RoleAssignmentResource[]; +} + +interface RoleAssignmentResource { + sid: string; + role_sid: string; + scope: string; + identity: string; + resource_type: string; + resource_id: string; + code: number; + message: string; + moreInfo: string; + status: number; +} + +export class RoleAssignmentInstance { + protected _solution: RoleAssignmentContextSolution; + protected _context?: RoleAssignmentContext; + + constructor(protected _version: Organizations, payload: RoleAssignmentResource, organizationSid?: string, roleAssignmentSid?: string) { + + this.sid = (payload.sid); + this.roleSid = (payload.role_sid); + this.scope = (payload.scope); + this.identity = (payload.identity); + this.resourceType = (payload.resource_type); + this.resourceId = (payload.resource_id); + this.code = (payload.code); + this.message = (payload.message); + this.moreInfo = (payload.moreInfo); + this.status = (payload.status); + + this._solution = { organizationSid: organizationSid, roleAssignmentSid: roleAssignmentSid, }; + } + + /** + * Twilio Role Assignment Sid representing this role assignment + */ + sid: string; + /** + * Twilio Role Sid representing assigned role + */ + roleSid: string; + /** + * Twilio Sid representing identity of this assignment + */ + scope: string; + /** + * Twilio Sid representing scope of this assignment + */ + identity: string; + /** + * The resource type for resource-level role assignments + */ + resourceType: string; + /** + * The resource id for resource-level role assignments + */ + resourceId: string; + /** + * Twilio-specific error code + */ + code: number; + /** + * Error message + */ + message: string; + /** + * Link to Error Code References + */ + moreInfo: string; + /** + * HTTP response status code + */ + status: number; + + private get _proxy(): RoleAssignmentContext { + this._context = this._context || new RoleAssignmentContextImpl(this._version, this._solution.organizationSid, this._solution.roleAssignmentSid); + return this._context; + } + + /** + * Remove a RoleAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RoleAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + roleSid: this.roleSid, + scope: this.scope, + identity: this.identity, + resourceType: this.resourceType, + resourceId: this.resourceId, + code: this.code, + message: this.message, + moreInfo: this.moreInfo, + status: this.status, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoleAssignmentSolution { + organizationSid: string; +} + +export interface RoleAssignmentListInstance { + _version: Organizations; + _solution: RoleAssignmentSolution; + _uri: string; + + (organizationSid: string, roleAssignmentSid: string, ): RoleAssignmentContext; + get(organizationSid: string, roleAssignmentSid: string, ): RoleAssignmentContext; + + + + + /** + * Create a RoleAssignmentInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleAssignmentInstance + */ + create(params: PublicApiCreateRoleAssignmentRequest, headers?: any, callback?: (error: Error | null, item?: RoleAssignmentInstance) => any): Promise<RoleAssignmentInstance>; + + /** + * Create a RoleAssignmentInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleAssignmentInstance with HTTP metadata + */ + createWithHttpInfo(params: PublicApiCreateRoleAssignmentRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<RoleAssignmentInstance>) => any): Promise<ApiResponse<RoleAssignmentInstance>>; + + + + + /** + * Streams RoleAssignmentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoleAssignmentInstance, done: (err?: Error) => void) => void): void; + each(params: RoleAssignmentListInstanceEachOptions, callback?: (item: RoleAssignmentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoleAssignmentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoleAssignmentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoleAssignmentListInstanceEachOptions, callback?: (item: RoleAssignmentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoleAssignmentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RoleAssignmentPage) => any): Promise<RoleAssignmentPage>; + /** + * Retrieve a single target page of RoleAssignmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RoleAssignmentPage>) => any): Promise<ApiResponse<RoleAssignmentPage>>; + /** + * Lists RoleAssignmentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoleAssignmentInstance[]) => any): Promise<RoleAssignmentInstance[]>; + list(params: RoleAssignmentListInstanceOptions, callback?: (error: Error | null, items: RoleAssignmentInstance[]) => any): Promise<RoleAssignmentInstance[]>; + /** + * Lists RoleAssignmentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RoleAssignmentInstance[]>) => any): Promise<ApiResponse<RoleAssignmentInstance[]>>; + listWithHttpInfo(params: RoleAssignmentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RoleAssignmentInstance[]>) => any): Promise<ApiResponse<RoleAssignmentInstance[]>>; + /** + * Retrieve a single page of RoleAssignmentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RoleAssignmentPage) => any): Promise<RoleAssignmentPage>; + page(params: RoleAssignmentListInstancePageOptions, callback?: (error: Error | null, items: RoleAssignmentPage) => any): Promise<RoleAssignmentPage>; + /** + * Retrieve a single page of RoleAssignmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RoleAssignmentPage>) => any): Promise<ApiResponse<RoleAssignmentPage>>; + pageWithHttpInfo(params: RoleAssignmentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RoleAssignmentPage>) => any): Promise<ApiResponse<RoleAssignmentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoleAssignmentListInstance(version: Organizations, organizationSid: string): RoleAssignmentListInstance { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + const instance = ((organizationSid, roleAssignmentSid, ) => instance.get(organizationSid, roleAssignmentSid, )) as RoleAssignmentListInstance; + + instance.get = function get(organizationSid, roleAssignmentSid, ): RoleAssignmentContext { + return new RoleAssignmentContextImpl(version, organizationSid, roleAssignmentSid); + } + + instance._version = version; + instance._solution = { organizationSid, }; + instance._uri = `/${organizationSid}/RoleAssignments`; + + instance.create = function create(params: PublicApiCreateRoleAssignmentRequest, headers?: any, callback?: (error: Error | null, items: RoleAssignmentInstance) => any): Promise<RoleAssignmentInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleAssignmentInstance(operationVersion, payload, instance._solution.organizationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: PublicApiCreateRoleAssignmentRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<RoleAssignmentInstance>) => any): Promise<ApiResponse<RoleAssignmentInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<RoleAssignmentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RoleAssignmentInstance> => ({ + ...response, + body: new RoleAssignmentInstance(operationVersion, response.body, instance._solution.organizationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RoleAssignmentListInstancePageOptions | ((error: Error | null, items: RoleAssignmentPage) => any), callback?: (error: Error | null, items: RoleAssignmentPage) => any): Promise<RoleAssignmentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["scope"] !== undefined) + data["Scope"] = params["scope"]; + if (params["resourceType"] !== undefined) + data["ResourceType"] = params["resourceType"]; + if (params["resourceId"] !== undefined) + data["ResourceId"] = params["resourceId"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RoleAssignmentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RoleAssignmentPage) => any): Promise<RoleAssignmentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RoleAssignmentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoleAssignmentListInstancePageOptions | ((error: Error | null, items: ApiResponse<RoleAssignmentPage>) => any), callback?: (error: Error | null, items: ApiResponse<RoleAssignmentPage>) => any): Promise<ApiResponse<RoleAssignmentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["scope"] !== undefined) + data["Scope"] = params["scope"]; + if (params["resourceType"] !== undefined) + data["ResourceType"] = params["resourceType"]; + if (params["resourceId"] !== undefined) + data["ResourceId"] = params["resourceId"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RoleAssignmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RoleAssignmentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RoleAssignmentPage>) => any): Promise<ApiResponse<RoleAssignmentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RoleAssignmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RoleAssignmentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RoleAssignmentPage extends Page<Organizations, RoleAssignmentPayload, RoleAssignmentResource, RoleAssignmentInstance> { +/** +* Initialize the RoleAssignmentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Organizations, response: Response<string>, solution: RoleAssignmentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoleAssignmentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoleAssignmentResource): RoleAssignmentInstance { + + return new RoleAssignmentInstance( + this._version, + payload, + this._solution.organizationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/previewIam/organizations/user.ts b/rest/previewIam/organizations/user.ts new file mode 100644 index 000000000..7d0d0dc72 --- /dev/null +++ b/rest/previewIam/organizations/user.ts @@ -0,0 +1,1240 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import Organizations from "../Organizations"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + */ +export class ScimEmailAddress { + /** + * Indicates if this email address is the primary one + */ + "primary"?: boolean; + /** + * The actual email address value + */ + "value"?: string; + /** + * The type of email address (e.g., work, home, etc.) + */ + "type"?: string; + + constructor(payload) { + this.primary = payload["primary"]; + this.value = payload["value"]; + this.type = payload["type"]; + } +} + + +/** + * Meta + */ +export class ScimMeta { + /** + * Indicates the type of the resource + */ + "resourceType"?: string; + /** + * The date and time when the resource was created in the system + */ + "created"?: Date; + /** + * The date and time when the resource was last modified + */ + "lastModified"?: Date; + /** + * A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + */ + "version"?: string; + + constructor(payload) { + this.resourceType = payload["resourceType"]; + this.created = payload["created"]; + this.lastModified = payload["lastModified"]; + this.version = payload["version"]; + } +} + + +/** + * User\'s name + */ +export class ScimName { + /** + * The user\'s first or given name + */ + "givenName"?: string; + /** + * The user\'s last or family name + */ + "familyName"?: string; + + constructor(payload) { + this.givenName = payload["givenName"]; + this.familyName = payload["familyName"]; + } +} + + +export class ScimPatchOperation { + /** + * The operation to perform + */ + "op"?: string; + "path"?: string; + "value"?: Record<string, object>; + + constructor(payload) { + this.op = payload["op"]; + this.path = payload["path"]; + this.value = payload["value"]; + } +} + + +export class ScimPatchRequest { + "schemas"?: Array<string>; + "operations"?: Array<ScimPatchOperation>; + + constructor(payload) { + this.schemas = payload["schemas"]; + this.operations = payload["Operations"]; + } +} + + +export class ScimUser { + /** + * Unique Twilio user sid + */ + "id"?: string; + /** + * External unique resource id defined by provisioning client + */ + "externalId"?: string; + /** + * Unique username, MUST be same as primary email address + */ + "userName": string; + /** + * User friendly display name + */ + "displayName"?: string; + "name"?: ScimName; + /** + * Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + */ + "emails"?: Array<ScimEmailAddress>; + /** + * Indicates whether the user is active + */ + "active"?: boolean; + /** + * User\'s locale + */ + "locale"?: string; + /** + * User\'s time zone + */ + "timezone"?: string; + /** + * An array of URIs that indicate the schemas supported for this user resource + */ + "schemas"?: Array<string>; + "meta"?: ScimMeta; + /** + * A human-readable description of the error + */ + "detail"?: string; + /** + * A scimType error code as defined in RFC7644 + */ + "scimType"?: string; + /** + * Http status code + */ + "status"?: string; + /** + * Twilio-specific error code + */ + "code"?: number; + /** + * Link to Error Code References + */ + "moreInfo"?: string; + + constructor(payload) { + this.id = payload["id"]; + this.externalId = payload["externalId"]; + this.userName = payload["userName"]; + this.displayName = payload["displayName"]; + this.name = payload["name"]; + this.emails = payload["emails"]; + this.active = payload["active"]; + this.locale = payload["locale"]; + this.timezone = payload["timezone"]; + this.schemas = payload["schemas"]; + this.meta = payload["meta"]; + this.detail = payload["detail"]; + this.scimType = payload["scimType"]; + this.status = payload["status"]; + this.code = payload["code"]; + this.moreInfo = payload["moreInfo"]; + } +} + + + + + +/** + * Options to pass to patch a UserInstance + */ +export interface UserContextPatchOptions { + /** */ + "scimPatchRequest": ScimPatchRequest; + /** */ + "ifMatch"?: string; +} + +/** + * Options to pass to update a UserInstance + */ +export interface UserContextUpdateOptions { + /** */ + "scimUser": ScimUser; + /** */ + "ifMatch"?: string; +} + +/** + * Options to pass to create a UserInstance + */ +export interface UserListInstanceCreateOptions { + /** */ + "scimUser": ScimUser; +} + +/** + * Options to pass to each + */ +export interface UserListInstanceEachOptions { + /** */ + "filter"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserListInstanceOptions { + /** */ + "filter"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserListInstancePageOptions { + /** */ + "filter"?: string; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserContext { + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> + + /** + * Patch a UserInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + patch(params: ScimPatchRequest, headers?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance>; + + /** + * Patch a UserInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + patchWithHttpInfo(params: ScimPatchRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>>; + + /** + * Update a UserInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance>; + + /** + * Update a UserInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserContextSolution { + "organizationSid": string; + "userSid": string; +} + +export class UserContextImpl implements UserContext { + protected _solution: UserContextSolution; + protected _uri: string; + + + constructor(protected _version: Organizations, organizationSid: string, userSid: string) { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + if (!isValidPathParam(userSid)) { + throw new Error('Parameter \'userSid\' is not valid.'); + } + + this._solution = { organizationSid, userSid, }; + this._uri = `/${organizationSid}/scim/Users/${userSid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> { + const headers: any = {}; + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.organizationSid, instance._solution.userSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> { + const headers: any = {}; + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<UserResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<UserInstance> => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.organizationSid, instance._solution.userSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patch(params: ScimPatchRequest, headers?: any,callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.patch({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.organizationSid, instance._solution.userSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patchWithHttpInfo(params: ScimPatchRequest, headers?: any,callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.patchWithResponseInfo<UserResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<UserInstance> => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.organizationSid, instance._solution.userSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: ScimUser, headers?: any,callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.organizationSid, instance._solution.userSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: ScimUser, headers?: any,callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<UserResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<UserInstance> => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.organizationSid, instance._solution.userSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserPayload extends TwilioResponsePayload { + Resources: UserResource[]; +} + +interface UserResource { + id: string; + externalId: string; + userName: string; + displayName: string; + name: ScimName; + emails: Array<ScimEmailAddress>; + active: boolean; + locale: string; + timezone: string; + schemas: Array<string>; + meta: ScimMeta; + detail: string; + scimType: string; + status: string; + code: number; + moreInfo: string; +} + +export class UserInstance { + protected _solution: UserContextSolution; + protected _context?: UserContext; + + constructor(protected _version: Organizations, payload: UserResource, organizationSid?: string, userSid?: string) { + + this.id = (payload.id); + this.externalId = (payload.externalId); + this.userName = (payload.userName); + this.displayName = (payload.displayName); + this.name = payload.name !== null && payload.name !== undefined ? new ScimName(payload.name) : null; + this.emails = payload.emails !== null && payload.emails !== undefined ? payload.emails.map( + (payload: any) => new ScimEmailAddress(payload) + ) : null; + this.active = (payload.active); + this.locale = (payload.locale); + this.timezone = (payload.timezone); + this.schemas = (payload.schemas); + this.meta = payload.meta !== null && payload.meta !== undefined ? new ScimMeta(payload.meta) : null; + this.detail = (payload.detail); + this.scimType = (payload.scimType); + this.status = (payload.status); + this.code = (payload.code); + this.moreInfo = (payload.moreInfo); + + this._solution = { organizationSid: organizationSid, userSid: userSid, }; + } + + /** + * Unique Twilio user sid + */ + id: string; + /** + * External unique resource id defined by provisioning client + */ + externalId: string; + /** + * Unique username, MUST be same as primary email address + */ + userName: string; + /** + * User friendly display name + */ + displayName: string; + name: ScimName; + /** + * Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + */ + emails: Array<ScimEmailAddress>; + /** + * Indicates whether the user is active + */ + active: boolean; + /** + * User\'s locale + */ + locale: string; + /** + * User\'s time zone + */ + timezone: string; + /** + * An array of URIs that indicate the schemas supported for this user resource + */ + schemas: Array<string>; + meta: ScimMeta; + /** + * A human-readable description of the error + */ + detail: string; + /** + * A scimType error code as defined in RFC7644 + */ + scimType: string; + /** + * Http status code + */ + status: string; + /** + * Twilio-specific error code + */ + code: number; + /** + * Link to Error Code References + */ + moreInfo: string; + + private get _proxy(): UserContext { + this._context = this._context || new UserContextImpl(this._version, this._solution.organizationSid, this._solution.userSid); + return this._context; + } + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Patch a UserInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + patch(params: ScimPatchRequest, headers?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance>; + + patch(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> + { + return this._proxy.patch(params, callback); + } + + /** + * Patch a UserInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + patchWithHttpInfo(params: ScimPatchRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>>; + + patchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> + { + return this._proxy.patchWithHttpInfo(params, callback); + } + + /** + * Update a UserInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance>; + + update(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + externalId: this.externalId, + userName: this.userName, + displayName: this.displayName, + name: this.name, + emails: this.emails, + active: this.active, + locale: this.locale, + timezone: this.timezone, + schemas: this.schemas, + meta: this.meta, + detail: this.detail, + scimType: this.scimType, + status: this.status, + code: this.code, + moreInfo: this.moreInfo, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserSolution { + organizationSid: string; +} + +export interface UserListInstance { + _version: Organizations; + _solution: UserSolution; + _uri: string; + + (organizationSid: string, userSid: string, ): UserContext; + get(organizationSid: string, userSid: string, ): UserContext; + + + + + + + + + + + /** + * Create a UserInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + create(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance>; + + /** + * Create a UserInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + createWithHttpInfo(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>>; + + + + + /** + * Streams UserInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + each(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise<UserPage>; + /** + * Retrieve a single target page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<UserPage>) => any): Promise<ApiResponse<UserPage>>; + /** + * Lists UserInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserInstance[]) => any): Promise<UserInstance[]>; + list(params: UserListInstanceOptions, callback?: (error: Error | null, items: UserInstance[]) => any): Promise<UserInstance[]>; + /** + * Lists UserInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UserInstance[]>) => any): Promise<ApiResponse<UserInstance[]>>; + listWithHttpInfo(params: UserListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<UserInstance[]>) => any): Promise<ApiResponse<UserInstance[]>>; + /** + * Retrieve a single page of UserInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserPage) => any): Promise<UserPage>; + page(params: UserListInstancePageOptions, callback?: (error: Error | null, items: UserPage) => any): Promise<UserPage>; + /** + * Retrieve a single page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UserPage>) => any): Promise<ApiResponse<UserPage>>; + pageWithHttpInfo(params: UserListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<UserPage>) => any): Promise<ApiResponse<UserPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserListInstance(version: Organizations, organizationSid: string): UserListInstance { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + const instance = ((organizationSid, userSid, ) => instance.get(organizationSid, userSid, )) as UserListInstance; + + instance.get = function get(organizationSid, userSid, ): UserContext { + return new UserContextImpl(version, organizationSid, userSid); + } + + instance._version = version; + instance._solution = { organizationSid, }; + instance._uri = `/${organizationSid}/scim/Users`; + + instance.create = function create(params: ScimUser, headers?: any, callback?: (error: Error | null, items: UserInstance) => any): Promise<UserInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.organizationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ScimUser, headers?: any, callback?: (error: Error | null, items: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<UserResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<UserInstance> => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.organizationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: UserListInstancePageOptions | ((error: Error | null, items: UserPage) => any), callback?: (error: Error | null, items: UserPage) => any): Promise<UserPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["filter"] !== undefined) + data["filter"] = params["filter"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/scim+json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise<UserPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserListInstancePageOptions | ((error: Error | null, items: ApiResponse<UserPage>) => any), callback?: (error: Error | null, items: ApiResponse<UserPage>) => any): Promise<ApiResponse<UserPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["filter"] !== undefined) + data["filter"] = params["filter"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/scim+json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<UserPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<UserPage>) => any): Promise<ApiResponse<UserPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<UserPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserPage extends Page<Organizations, UserPayload, UserResource, UserInstance> { +/** +* Initialize the UserPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Organizations, response: Response<string>, solution: UserSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserResource): UserInstance { + + return new UserInstance( + this._version, + payload, + this._solution.organizationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/previewIam/v1/authorize.ts b/rest/previewIam/v1/authorize.ts new file mode 100644 index 000000000..cfc39281e --- /dev/null +++ b/rest/previewIam/v1/authorize.ts @@ -0,0 +1,231 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a AuthorizeInstance + */ +export interface AuthorizeListInstanceFetchOptions { + /** Response Type */ + "responseType"?: string; + /** The Client Identifier */ + "clientId"?: string; + /** The url to which response will be redirected to */ + "redirectUri"?: string; + /** The scope of the access request */ + "scope"?: string; + /** An opaque value which can be used to maintain state between the request and callback */ + "state"?: string; +} + + +export interface AuthorizeSolution { +} + +export interface AuthorizeListInstance { + _version: V1; + _solution: AuthorizeSolution; + _uri: string; + + + + /** + * Fetch a AuthorizeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance + */ + fetch(callback?: (error: Error | null, item?: AuthorizeInstance) => any): Promise<AuthorizeInstance>; + /** + * Fetch a AuthorizeInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance + */ + fetch(params: AuthorizeListInstanceFetchOptions, callback?: (error: Error | null, item?: AuthorizeInstance) => any): Promise<AuthorizeInstance>; + + /** + * Fetch a AuthorizeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AuthorizeInstance>) => any): Promise<ApiResponse<AuthorizeInstance>>; + /** + * Fetch a AuthorizeInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AuthorizeInstance with HTTP metadata + */ + fetchWithHttpInfo(params: AuthorizeListInstanceFetchOptions, callback?: (error: Error | null, item?: ApiResponse<AuthorizeInstance>) => any): Promise<ApiResponse<AuthorizeInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AuthorizeListInstance(version: V1): AuthorizeListInstance { + const instance = {} as AuthorizeListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/authorize`; + + instance.fetch = function fetch(params?: AuthorizeListInstanceFetchOptions | ((error: Error | null, items: AuthorizeInstance) => any), callback?: (error: Error | null, items: AuthorizeInstance) => any): Promise<AuthorizeInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["responseType"] !== undefined) + data["response_type"] = params["responseType"]; + if (params["clientId"] !== undefined) + data["client_id"] = params["clientId"]; + if (params["redirectUri"] !== undefined) + data["redirect_uri"] = params["redirectUri"]; + if (params["scope"] !== undefined) + data["scope"] = params["scope"]; + if (params["state"] !== undefined) + data["state"] = params["state"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new AuthorizeInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo(params?: AuthorizeListInstanceFetchOptions | ((error: Error | null, items: ApiResponse<AuthorizeInstance>) => any), callback?: (error: Error | null, items: ApiResponse<AuthorizeInstance>) => any): Promise<ApiResponse<AuthorizeInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["responseType"] !== undefined) + data["response_type"] = params["responseType"]; + if (params["clientId"] !== undefined) + data["client_id"] = params["clientId"]; + if (params["redirectUri"] !== undefined) + data["redirect_uri"] = params["redirectUri"]; + if (params["scope"] !== undefined) + data["scope"] = params["scope"]; + if (params["state"] !== undefined) + data["state"] = params["state"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AuthorizeResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AuthorizeInstance> => ({ + ...response, + body: new AuthorizeInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface AuthorizePayload extends AuthorizeResource {} + +interface AuthorizeResource { + redirect_to: string; +} + +export class AuthorizeInstance { + + constructor(protected _version: V1, payload: AuthorizeResource) { + + this.redirectTo = (payload.redirect_to); + + } + + /** + * The callback URL + */ + redirectTo: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + redirectTo: this.redirectTo, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/previewIam/v1/token.ts b/rest/previewIam/v1/token.ts new file mode 100644 index 000000000..1c9c628fb --- /dev/null +++ b/rest/previewIam/v1/token.ts @@ -0,0 +1,270 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a TokenInstance + */ +export interface TokenListInstanceCreateOptions { + /** Grant type is a credential representing resource owner\\\'s authorization which can be used by client to obtain access token. */ + "grantType": string; + /** A 34 character string that uniquely identifies this OAuth App. */ + "clientId": string; + /** The credential for confidential OAuth App. */ + "clientSecret"?: string; + /** JWT token related to the authorization code grant type. */ + "code"?: string; + /** The redirect uri */ + "redirectUri"?: string; + /** The targeted audience uri */ + "audience"?: string; + /** JWT token related to refresh access token. */ + "refreshToken"?: string; + /** The scope of token */ + "scope"?: string; +} + + +export interface TokenSolution { +} + +export interface TokenListInstance { + _version: V1; + _solution: TokenSolution; + _uri: string; + + + + /** + * Create a TokenInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance + */ + create(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, item?: TokenInstance) => any): Promise<TokenInstance>; + + /** + * Create a TokenInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TokenInstance with HTTP metadata + */ + createWithHttpInfo(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TokenInstance>) => any): Promise<ApiResponse<TokenInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TokenListInstance(version: V1): TokenListInstance { + const instance = {} as TokenListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/token`; + + instance.create = function create(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, items: TokenInstance) => any): Promise<TokenInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["grantType"] === null || params["grantType"] === undefined) { + throw new Error('Required parameter "params[\'grantType\']" missing.'); + } + + if (params["clientId"] === null || params["clientId"] === undefined) { + throw new Error('Required parameter "params[\'clientId\']" missing.'); + } + + let data: any = {}; + + + + data["grant_type"] = params["grantType"]; + + data["client_id"] = params["clientId"]; + if (params["clientSecret"] !== undefined) + data["client_secret"] = params["clientSecret"]; + if (params["code"] !== undefined) + data["code"] = params["code"]; + if (params["redirectUri"] !== undefined) + data["redirect_uri"] = params["redirectUri"]; + if (params["audience"] !== undefined) + data["audience"] = params["audience"]; + if (params["refreshToken"] !== undefined) + data["refresh_token"] = params["refreshToken"]; + if (params["scope"] !== undefined) + data["scope"] = params["scope"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TokenInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TokenListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<TokenInstance>) => any): Promise<ApiResponse<TokenInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["grantType"] === null || params["grantType"] === undefined) { + throw new Error('Required parameter "params[\'grantType\']" missing.'); + } + + if (params["clientId"] === null || params["clientId"] === undefined) { + throw new Error('Required parameter "params[\'clientId\']" missing.'); + } + + let data: any = {}; + + + + data["grant_type"] = params["grantType"]; + + data["client_id"] = params["clientId"]; + if (params["clientSecret"] !== undefined) + data["client_secret"] = params["clientSecret"]; + if (params["code"] !== undefined) + data["code"] = params["code"]; + if (params["redirectUri"] !== undefined) + data["redirect_uri"] = params["redirectUri"]; + if (params["audience"] !== undefined) + data["audience"] = params["audience"]; + if (params["refreshToken"] !== undefined) + data["refresh_token"] = params["refreshToken"]; + if (params["scope"] !== undefined) + data["scope"] = params["scope"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TokenResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TokenInstance> => ({ + ...response, + body: new TokenInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TokenPayload extends TokenResource {} + +interface TokenResource { + access_token: string; + refresh_token: string; + id_token: string; + token_type: string; + expires_in: number; +} + +export class TokenInstance { + + constructor(protected _version: V1, payload: TokenResource) { + + this.accessToken = (payload.access_token); + this.refreshToken = (payload.refresh_token); + this.idToken = (payload.id_token); + this.tokenType = (payload.token_type); + this.expiresIn = (payload.expires_in); + + } + + /** + * Token which carries the necessary information to access a Twilio resource directly. + */ + accessToken: string; + /** + * Token which carries the information necessary to get a new access token. + */ + refreshToken: string; + /** + * Token which carries the information necessary of user profile. + */ + idToken: string; + /** + * Token type + */ + tokenType: string; + expiresIn: number; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accessToken: this.accessToken, + refreshToken: this.refreshToken, + idToken: this.idToken, + tokenType: this.tokenType, + expiresIn: this.expiresIn, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/previewIam/versionless/organization.ts b/rest/previewIam/versionless/organization.ts new file mode 100644 index 000000000..a46125183 --- /dev/null +++ b/rest/previewIam/versionless/organization.ts @@ -0,0 +1,133 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import Versionless from "../Versionless"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { AccountListInstance } from "./organization/account"; +import { RoleAssignmentListInstance } from "./organization/roleAssignment"; +import { UserListInstance } from "./organization/user"; + + + +export interface OrganizationContext { + accounts: AccountListInstance; + roleAssignments: RoleAssignmentListInstance; + users: UserListInstance; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OrganizationContextSolution { + "organizationSid": string; +} + +export class OrganizationContextImpl implements OrganizationContext { + protected _solution: OrganizationContextSolution; + protected _uri: string; + + protected _accounts?: AccountListInstance; + protected _roleAssignments?: RoleAssignmentListInstance; + protected _users?: UserListInstance; + + constructor(protected _version: Versionless, organizationSid: string) { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + this._solution = { organizationSid, }; + this._uri = `/${organizationSid}`; + } + + get accounts(): AccountListInstance { + this._accounts = this._accounts || AccountListInstance(this._version, this._solution.organizationSid); + return this._accounts; + } + + get roleAssignments(): RoleAssignmentListInstance { + this._roleAssignments = this._roleAssignments || RoleAssignmentListInstance(this._version, this._solution.organizationSid); + return this._roleAssignments; + } + + get users(): UserListInstance { + this._users = this._users || UserListInstance(this._version, this._solution.organizationSid); + return this._users; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + +export interface OrganizationSolution { +} + +export interface OrganizationListInstance { + _version: Versionless; + _solution: OrganizationSolution; + _uri: string; + + (organizationSid: string, ): OrganizationContext; + get(organizationSid: string, ): OrganizationContext; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OrganizationListInstance(version: Versionless): OrganizationListInstance { + const instance = ((organizationSid, ) => instance.get(organizationSid, )) as OrganizationListInstance; + + instance.get = function get(organizationSid, ): OrganizationContext { + return new OrganizationContextImpl(version, organizationSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/previewIam/versionless/organization/account.ts b/rest/previewIam/versionless/organization/account.ts new file mode 100644 index 000000000..2cacb53aa --- /dev/null +++ b/rest/previewIam/versionless/organization/account.ts @@ -0,0 +1,558 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import Versionless from "../../Versionless"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface AccountListInstanceEachOptions { + /** */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AccountInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AccountListInstanceOptions { + /** */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AccountListInstancePageOptions { + /** */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AccountContext { + + /** + * Fetch a AccountInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + fetch(callback?: (error: Error | null, item?: AccountInstance) => any): Promise<AccountInstance> + + /** + * Fetch a AccountInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountInstance>) => any): Promise<ApiResponse<AccountInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AccountContextSolution { + "organizationSid": string; + "accountSid": string; +} + +export class AccountContextImpl implements AccountContext { + protected _solution: AccountContextSolution; + protected _uri: string; + + + constructor(protected _version: Versionless, organizationSid: string, accountSid: string) { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + if (!isValidPathParam(accountSid)) { + throw new Error('Parameter \'accountSid\' is not valid.'); + } + + this._solution = { organizationSid, accountSid, }; + this._uri = `/${organizationSid}/Accounts/${accountSid}`; + } + + fetch(callback?: (error: Error | null, item?: AccountInstance) => any): Promise<AccountInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AccountInstance(operationVersion, payload, instance._solution.organizationSid, instance._solution.accountSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountInstance>) => any): Promise<ApiResponse<AccountInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AccountResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AccountInstance> => ({ + ...response, + body: new AccountInstance(operationVersion, response.body, instance._solution.organizationSid, instance._solution.accountSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AccountPayload extends TwilioResponsePayload { + content: AccountResource[]; +} + +interface AccountResource { + account_sid: string; + friendly_name: string; + status: string; + owner_sid: string; + date_created: Date; +} + +/** + * Page content + */ +export class AccountInstance { + protected _solution: AccountContextSolution; + protected _context?: AccountContext; + + constructor(protected _version: Versionless, payload: AccountResource, organizationSid: string, accountSid?: string) { + + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.status = (payload.status); + this.ownerSid = (payload.owner_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + + this._solution = { organizationSid, accountSid: accountSid, }; + } + + /** + * Twilio account sid + */ + accountSid: string; + /** + * Account friendly name + */ + friendlyName: string; + /** + * Account status + */ + status: string; + /** + * Twilio account sid + */ + ownerSid: string; + /** + * The date and time when the account was created in the system + */ + dateCreated: Date; + + private get _proxy(): AccountContext { + this._context = this._context || new AccountContextImpl(this._version, this._solution.organizationSid, this._solution.accountSid); + return this._context; + } + + /** + * Fetch a AccountInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance + */ + fetch(callback?: (error: Error | null, item?: AccountInstance) => any): Promise<AccountInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AccountInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountInstance>) => any): Promise<ApiResponse<AccountInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + friendlyName: this.friendlyName, + status: this.status, + ownerSid: this.ownerSid, + dateCreated: this.dateCreated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AccountSolution { + organizationSid: string; +} + +export interface AccountListInstance { + _version: Versionless; + _solution: AccountSolution; + _uri: string; + + (accountSid: string, ): AccountContext; + get(accountSid: string, ): AccountContext; + + + + + + /** + * Streams AccountInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + each(params: AccountListInstanceEachOptions, callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AccountInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AccountListInstanceEachOptions, callback?: (item: AccountInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AccountInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AccountPage) => any): Promise<AccountPage>; + /** + * Retrieve a single target page of AccountInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AccountPage>) => any): Promise<ApiResponse<AccountPage>>; + /** + * Lists AccountInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AccountInstance[]) => any): Promise<AccountInstance[]>; + list(params: AccountListInstanceOptions, callback?: (error: Error | null, items: AccountInstance[]) => any): Promise<AccountInstance[]>; + /** + * Lists AccountInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AccountInstance[]>) => any): Promise<ApiResponse<AccountInstance[]>>; + listWithHttpInfo(params: AccountListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AccountInstance[]>) => any): Promise<ApiResponse<AccountInstance[]>>; + /** + * Retrieve a single page of AccountInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AccountPage) => any): Promise<AccountPage>; + page(params: AccountListInstancePageOptions, callback?: (error: Error | null, items: AccountPage) => any): Promise<AccountPage>; + /** + * Retrieve a single page of AccountInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AccountListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AccountPage>) => any): Promise<ApiResponse<AccountPage>>; + pageWithHttpInfo(params: AccountListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AccountPage>) => any): Promise<ApiResponse<AccountPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AccountListInstance(version: Versionless, organizationSid: string): AccountListInstance { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + const instance = ((accountSid, ) => instance.get(accountSid, )) as AccountListInstance; + + instance.get = function get(accountSid, ): AccountContext { + return new AccountContextImpl(version, organizationSid, accountSid); + } + + instance._version = version; + instance._solution = { organizationSid, }; + instance._uri = `/${organizationSid}/Accounts`; + + instance.page = function page(params?: AccountListInstancePageOptions | ((error: Error | null, items: AccountPage) => any), callback?: (error: Error | null, items: AccountPage) => any): Promise<AccountPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AccountPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AccountPage) => any): Promise<AccountPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AccountPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AccountListInstancePageOptions | ((error: Error | null, items: ApiResponse<AccountPage>) => any), callback?: (error: Error | null, items: ApiResponse<AccountPage>) => any): Promise<ApiResponse<AccountPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AccountPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AccountPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AccountPage>) => any): Promise<ApiResponse<AccountPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AccountPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AccountPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AccountPage extends Page<Versionless, AccountPayload, AccountResource, AccountInstance> { +/** +* Initialize the AccountPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Versionless, response: Response<string>, solution: AccountSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AccountInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AccountResource): AccountInstance { + + return new AccountInstance( + this._version, + payload, + this._solution.organizationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/previewIam/versionless/organization/roleAssignment.ts b/rest/previewIam/versionless/organization/roleAssignment.ts new file mode 100644 index 000000000..6f8d40f9b --- /dev/null +++ b/rest/previewIam/versionless/organization/roleAssignment.ts @@ -0,0 +1,751 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import Versionless from "../../Versionless"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class PublicApiCreateRoleAssignmentRequest { + /** + * Twilio Role Sid representing assigned role + */ + "roleSid": string; + /** + * Twilio Sid representing scope of this assignment + */ + "scope": string; + /** + * Twilio Sid representing identity of this assignment + */ + "identity": string; + /** + * The resource type for resource-level role assignments + */ + "resourceType"?: string | null; + /** + * The resource id for resource-level role assignments + */ + "resourceId"?: string | null; + + constructor(payload) { + this.roleSid = payload["role_sid"]; + this.scope = payload["scope"]; + this.identity = payload["identity"]; + this.resourceType = payload["resource_type"]; + this.resourceId = payload["resource_id"]; + } +} + + + + +/** + * Options to pass to create a RoleAssignmentInstance + */ +export interface RoleAssignmentListInstanceCreateOptions { + /** */ + "publicApiCreateRoleAssignmentRequest": PublicApiCreateRoleAssignmentRequest; +} + +/** + * Options to pass to each + */ +export interface RoleAssignmentListInstanceEachOptions { + /** */ + "pageSize"?: number; + /** */ + "identity"?: string; + /** */ + "scope"?: string; + /** Filter by resource type for resource-level role assignments */ + "resourceType"?: string; + /** Filter by resource id for resource-level role assignments */ + "resourceId"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoleAssignmentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoleAssignmentListInstanceOptions { + /** */ + "pageSize"?: number; + /** */ + "identity"?: string; + /** */ + "scope"?: string; + /** Filter by resource type for resource-level role assignments */ + "resourceType"?: string; + /** Filter by resource id for resource-level role assignments */ + "resourceId"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoleAssignmentListInstancePageOptions { + /** */ + "pageSize"?: number; + /** */ + "identity"?: string; + /** */ + "scope"?: string; + /** Filter by resource type for resource-level role assignments */ + "resourceType"?: string; + /** Filter by resource id for resource-level role assignments */ + "resourceId"?: string; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoleAssignmentContext { + + /** + * Remove a RoleAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a RoleAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoleAssignmentContextSolution { + "organizationSid": string; + "sid": string; +} + +export class RoleAssignmentContextImpl implements RoleAssignmentContext { + protected _solution: RoleAssignmentContextSolution; + protected _uri: string; + + + constructor(protected _version: Versionless, organizationSid: string, sid: string) { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { organizationSid, sid, }; + this._uri = `/${organizationSid}/RoleAssignments/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RoleAssignmentPayload extends TwilioResponsePayload { + content: RoleAssignmentResource[]; +} + +interface RoleAssignmentResource { + sid: string; + role_sid: string; + scope: string; + identity: string; + resource_type: string; + resource_id: string; + code: number; + message: string; + moreInfo: string; + status: number; +} + +export class RoleAssignmentInstance { + protected _solution: RoleAssignmentContextSolution; + protected _context?: RoleAssignmentContext; + + constructor(protected _version: Versionless, payload: RoleAssignmentResource, organizationSid: string, sid?: string) { + + this.sid = (payload.sid); + this.roleSid = (payload.role_sid); + this.scope = (payload.scope); + this.identity = (payload.identity); + this.resourceType = (payload.resource_type); + this.resourceId = (payload.resource_id); + this.code = (payload.code); + this.message = (payload.message); + this.moreInfo = (payload.moreInfo); + this.status = (payload.status); + + this._solution = { organizationSid, sid: sid, }; + } + + /** + * Twilio Role Assignment Sid representing this role assignment + */ + sid: string; + /** + * Twilio Role Sid representing assigned role + */ + roleSid: string; + /** + * Twilio Sid representing identity of this assignment + */ + scope: string; + /** + * Twilio Sid representing scope of this assignment + */ + identity: string; + /** + * The resource type for resource-level role assignments + */ + resourceType: string; + /** + * The resource id for resource-level role assignments + */ + resourceId: string; + /** + * Twilio-specific error code + */ + code: number; + /** + * Error message + */ + message: string; + /** + * Link to Error Code References + */ + moreInfo: string; + /** + * HTTP response status code + */ + status: number; + + private get _proxy(): RoleAssignmentContext { + this._context = this._context || new RoleAssignmentContextImpl(this._version, this._solution.organizationSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RoleAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RoleAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + roleSid: this.roleSid, + scope: this.scope, + identity: this.identity, + resourceType: this.resourceType, + resourceId: this.resourceId, + code: this.code, + message: this.message, + moreInfo: this.moreInfo, + status: this.status, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoleAssignmentSolution { + organizationSid: string; +} + +export interface RoleAssignmentListInstance { + _version: Versionless; + _solution: RoleAssignmentSolution; + _uri: string; + + (sid: string, ): RoleAssignmentContext; + get(sid: string, ): RoleAssignmentContext; + + + + + /** + * Create a RoleAssignmentInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleAssignmentInstance + */ + create(params: PublicApiCreateRoleAssignmentRequest, headers?: any, callback?: (error: Error | null, item?: RoleAssignmentInstance) => any): Promise<RoleAssignmentInstance>; + + /** + * Create a RoleAssignmentInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoleAssignmentInstance with HTTP metadata + */ + createWithHttpInfo(params: PublicApiCreateRoleAssignmentRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<RoleAssignmentInstance>) => any): Promise<ApiResponse<RoleAssignmentInstance>>; + + + + + /** + * Streams RoleAssignmentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoleAssignmentInstance, done: (err?: Error) => void) => void): void; + each(params: RoleAssignmentListInstanceEachOptions, callback?: (item: RoleAssignmentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoleAssignmentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoleAssignmentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoleAssignmentListInstanceEachOptions, callback?: (item: RoleAssignmentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoleAssignmentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RoleAssignmentPage) => any): Promise<RoleAssignmentPage>; + /** + * Retrieve a single target page of RoleAssignmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RoleAssignmentPage>) => any): Promise<ApiResponse<RoleAssignmentPage>>; + /** + * Lists RoleAssignmentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoleAssignmentInstance[]) => any): Promise<RoleAssignmentInstance[]>; + list(params: RoleAssignmentListInstanceOptions, callback?: (error: Error | null, items: RoleAssignmentInstance[]) => any): Promise<RoleAssignmentInstance[]>; + /** + * Lists RoleAssignmentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RoleAssignmentInstance[]>) => any): Promise<ApiResponse<RoleAssignmentInstance[]>>; + listWithHttpInfo(params: RoleAssignmentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RoleAssignmentInstance[]>) => any): Promise<ApiResponse<RoleAssignmentInstance[]>>; + /** + * Retrieve a single page of RoleAssignmentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RoleAssignmentPage) => any): Promise<RoleAssignmentPage>; + page(params: RoleAssignmentListInstancePageOptions, callback?: (error: Error | null, items: RoleAssignmentPage) => any): Promise<RoleAssignmentPage>; + /** + * Retrieve a single page of RoleAssignmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoleAssignmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RoleAssignmentPage>) => any): Promise<ApiResponse<RoleAssignmentPage>>; + pageWithHttpInfo(params: RoleAssignmentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RoleAssignmentPage>) => any): Promise<ApiResponse<RoleAssignmentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoleAssignmentListInstance(version: Versionless, organizationSid: string): RoleAssignmentListInstance { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RoleAssignmentListInstance; + + instance.get = function get(sid, ): RoleAssignmentContext { + return new RoleAssignmentContextImpl(version, organizationSid, sid); + } + + instance._version = version; + instance._solution = { organizationSid, }; + instance._uri = `/${organizationSid}/RoleAssignments`; + + instance.create = function create(params: PublicApiCreateRoleAssignmentRequest, headers?: any, callback?: (error: Error | null, items: RoleAssignmentInstance) => any): Promise<RoleAssignmentInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoleAssignmentInstance(operationVersion, payload, instance._solution.organizationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: PublicApiCreateRoleAssignmentRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<RoleAssignmentInstance>) => any): Promise<ApiResponse<RoleAssignmentInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<RoleAssignmentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RoleAssignmentInstance> => ({ + ...response, + body: new RoleAssignmentInstance(operationVersion, response.body, instance._solution.organizationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RoleAssignmentListInstancePageOptions | ((error: Error | null, items: RoleAssignmentPage) => any), callback?: (error: Error | null, items: RoleAssignmentPage) => any): Promise<RoleAssignmentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["scope"] !== undefined) + data["Scope"] = params["scope"]; + if (params["resourceType"] !== undefined) + data["ResourceType"] = params["resourceType"]; + if (params["resourceId"] !== undefined) + data["ResourceId"] = params["resourceId"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RoleAssignmentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RoleAssignmentPage) => any): Promise<RoleAssignmentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RoleAssignmentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoleAssignmentListInstancePageOptions | ((error: Error | null, items: ApiResponse<RoleAssignmentPage>) => any), callback?: (error: Error | null, items: ApiResponse<RoleAssignmentPage>) => any): Promise<ApiResponse<RoleAssignmentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["scope"] !== undefined) + data["Scope"] = params["scope"]; + if (params["resourceType"] !== undefined) + data["ResourceType"] = params["resourceType"]; + if (params["resourceId"] !== undefined) + data["ResourceId"] = params["resourceId"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RoleAssignmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RoleAssignmentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RoleAssignmentPage>) => any): Promise<ApiResponse<RoleAssignmentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RoleAssignmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RoleAssignmentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RoleAssignmentPage extends Page<Versionless, RoleAssignmentPayload, RoleAssignmentResource, RoleAssignmentInstance> { +/** +* Initialize the RoleAssignmentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Versionless, response: Response<string>, solution: RoleAssignmentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoleAssignmentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoleAssignmentResource): RoleAssignmentInstance { + + return new RoleAssignmentInstance( + this._version, + payload, + this._solution.organizationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/previewIam/versionless/organization/user.ts b/rest/previewIam/versionless/organization/user.ts new file mode 100644 index 000000000..872e88d35 --- /dev/null +++ b/rest/previewIam/versionless/organization/user.ts @@ -0,0 +1,1240 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import Versionless from "../../Versionless"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + */ +export class ScimEmailAddress { + /** + * Indicates if this email address is the primary one + */ + "primary"?: boolean; + /** + * The actual email address value + */ + "value"?: string; + /** + * The type of email address (e.g., work, home, etc.) + */ + "type"?: string; + + constructor(payload) { + this.primary = payload["primary"]; + this.value = payload["value"]; + this.type = payload["type"]; + } +} + + +/** + * Meta + */ +export class ScimMeta { + /** + * Indicates the type of the resource + */ + "resourceType"?: string; + /** + * The date and time when the resource was created in the system + */ + "created"?: Date; + /** + * The date and time when the resource was last modified + */ + "lastModified"?: Date; + /** + * A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + */ + "version"?: string; + + constructor(payload) { + this.resourceType = payload["resourceType"]; + this.created = payload["created"]; + this.lastModified = payload["lastModified"]; + this.version = payload["version"]; + } +} + + +/** + * User\'s name + */ +export class ScimName { + /** + * The user\'s first or given name + */ + "givenName"?: string; + /** + * The user\'s last or family name + */ + "familyName"?: string; + + constructor(payload) { + this.givenName = payload["givenName"]; + this.familyName = payload["familyName"]; + } +} + + +export class ScimPatchOperation { + /** + * The operation to perform + */ + "op"?: string; + "path"?: string; + "value"?: Record<string, object>; + + constructor(payload) { + this.op = payload["op"]; + this.path = payload["path"]; + this.value = payload["value"]; + } +} + + +export class ScimPatchRequest { + "schemas"?: Array<string>; + "operations"?: Array<ScimPatchOperation>; + + constructor(payload) { + this.schemas = payload["schemas"]; + this.operations = payload["Operations"]; + } +} + + +export class ScimUser { + /** + * Unique Twilio user sid + */ + "id"?: string; + /** + * External unique resource id defined by provisioning client + */ + "externalId"?: string; + /** + * Unique username, MUST be same as primary email address + */ + "userName": string; + /** + * User friendly display name + */ + "displayName"?: string; + "name"?: ScimName; + /** + * Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + */ + "emails"?: Array<ScimEmailAddress>; + /** + * Indicates whether the user is active + */ + "active"?: boolean; + /** + * User\'s locale + */ + "locale"?: string; + /** + * User\'s time zone + */ + "timezone"?: string; + /** + * An array of URIs that indicate the schemas supported for this user resource + */ + "schemas"?: Array<string>; + "meta"?: ScimMeta; + /** + * A human-readable description of the error + */ + "detail"?: string; + /** + * A scimType error code as defined in RFC7644 + */ + "scimType"?: string; + /** + * Http status code + */ + "status"?: string; + /** + * Twilio-specific error code + */ + "code"?: number; + /** + * Link to Error Code References + */ + "moreInfo"?: string; + + constructor(payload) { + this.id = payload["id"]; + this.externalId = payload["externalId"]; + this.userName = payload["userName"]; + this.displayName = payload["displayName"]; + this.name = payload["name"]; + this.emails = payload["emails"]; + this.active = payload["active"]; + this.locale = payload["locale"]; + this.timezone = payload["timezone"]; + this.schemas = payload["schemas"]; + this.meta = payload["meta"]; + this.detail = payload["detail"]; + this.scimType = payload["scimType"]; + this.status = payload["status"]; + this.code = payload["code"]; + this.moreInfo = payload["moreInfo"]; + } +} + + + + + +/** + * Options to pass to patch a UserInstance + */ +export interface UserContextPatchOptions { + /** */ + "scimPatchRequest": ScimPatchRequest; + /** */ + "ifMatch"?: string; +} + +/** + * Options to pass to update a UserInstance + */ +export interface UserContextUpdateOptions { + /** */ + "scimUser": ScimUser; + /** */ + "ifMatch"?: string; +} + +/** + * Options to pass to create a UserInstance + */ +export interface UserListInstanceCreateOptions { + /** */ + "scimUser": ScimUser; +} + +/** + * Options to pass to each + */ +export interface UserListInstanceEachOptions { + /** */ + "filter"?: string; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UserInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UserListInstanceOptions { + /** */ + "filter"?: string; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UserListInstancePageOptions { + /** */ + "filter"?: string; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface UserContext { + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> + + /** + * Patch a UserInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + patch(params: ScimPatchRequest, headers?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance>; + + /** + * Patch a UserInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + patchWithHttpInfo(params: ScimPatchRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>>; + + /** + * Update a UserInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance>; + + /** + * Update a UserInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface UserContextSolution { + "organizationSid": string; + "id": string; +} + +export class UserContextImpl implements UserContext { + protected _solution: UserContextSolution; + protected _uri: string; + + + constructor(protected _version: Versionless, organizationSid: string, id: string) { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + this._solution = { organizationSid, id, }; + this._uri = `/${organizationSid}/scim/Users/${id}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> { + const headers: any = {}; + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.organizationSid, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> { + const headers: any = {}; + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<UserResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<UserInstance> => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.organizationSid, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patch(params: ScimPatchRequest, headers?: any,callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.patch({ uri: instance._uri, method: "patch", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.organizationSid, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + patchWithHttpInfo(params: ScimPatchRequest, headers?: any,callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.patchWithResponseInfo<UserResource>({ uri: instance._uri, method: "patch", data, headers}).then((response) : ApiResponse<UserInstance> => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.organizationSid, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: ScimUser, headers?: any,callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.organizationSid, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: ScimUser, headers?: any,callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<UserResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<UserInstance> => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.organizationSid, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface UserPayload extends TwilioResponsePayload { + Resources: UserResource[]; +} + +interface UserResource { + id: string; + externalId: string; + userName: string; + displayName: string; + name: ScimName; + emails: Array<ScimEmailAddress>; + active: boolean; + locale: string; + timezone: string; + schemas: Array<string>; + meta: ScimMeta; + detail: string; + scimType: string; + status: string; + code: number; + moreInfo: string; +} + +export class UserInstance { + protected _solution: UserContextSolution; + protected _context?: UserContext; + + constructor(protected _version: Versionless, payload: UserResource, organizationSid: string, id?: string) { + + this.id = (payload.id); + this.externalId = (payload.externalId); + this.userName = (payload.userName); + this.displayName = (payload.displayName); + this.name = payload.name !== null && payload.name !== undefined ? new ScimName(payload.name) : null; + this.emails = payload.emails !== null && payload.emails !== undefined ? payload.emails.map( + (payload: any) => new ScimEmailAddress(payload) + ) : null; + this.active = (payload.active); + this.locale = (payload.locale); + this.timezone = (payload.timezone); + this.schemas = (payload.schemas); + this.meta = payload.meta !== null && payload.meta !== undefined ? new ScimMeta(payload.meta) : null; + this.detail = (payload.detail); + this.scimType = (payload.scimType); + this.status = (payload.status); + this.code = (payload.code); + this.moreInfo = (payload.moreInfo); + + this._solution = { organizationSid, id: id, }; + } + + /** + * Unique Twilio user sid + */ + id: string; + /** + * External unique resource id defined by provisioning client + */ + externalId: string; + /** + * Unique username, MUST be same as primary email address + */ + userName: string; + /** + * User friendly display name + */ + displayName: string; + name: ScimName; + /** + * Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + */ + emails: Array<ScimEmailAddress>; + /** + * Indicates whether the user is active + */ + active: boolean; + /** + * User\'s locale + */ + locale: string; + /** + * User\'s time zone + */ + timezone: string; + /** + * An array of URIs that indicate the schemas supported for this user resource + */ + schemas: Array<string>; + meta: ScimMeta; + /** + * A human-readable description of the error + */ + detail: string; + /** + * A scimType error code as defined in RFC7644 + */ + scimType: string; + /** + * Http status code + */ + status: string; + /** + * Twilio-specific error code + */ + code: number; + /** + * Link to Error Code References + */ + moreInfo: string; + + private get _proxy(): UserContext { + this._context = this._context || new UserContextImpl(this._version, this._solution.organizationSid, this._solution.id); + return this._context; + } + + /** + * Remove a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a UserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + fetch(callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a UserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Patch a UserInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + patch(params: ScimPatchRequest, headers?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance>; + + patch(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> + { + return this._proxy.patch(params, callback); + } + + /** + * Patch a UserInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + patchWithHttpInfo(params: ScimPatchRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>>; + + patchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> + { + return this._proxy.patchWithHttpInfo(params, callback); + } + + /** + * Update a UserInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + update(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance>; + + update(params?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a UserInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + updateWithHttpInfo(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + externalId: this.externalId, + userName: this.userName, + displayName: this.displayName, + name: this.name, + emails: this.emails, + active: this.active, + locale: this.locale, + timezone: this.timezone, + schemas: this.schemas, + meta: this.meta, + detail: this.detail, + scimType: this.scimType, + status: this.status, + code: this.code, + moreInfo: this.moreInfo, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface UserSolution { + organizationSid: string; +} + +export interface UserListInstance { + _version: Versionless; + _solution: UserSolution; + _uri: string; + + (id: string, ): UserContext; + get(id: string, ): UserContext; + + + + + + + + + + + /** + * Create a UserInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance + */ + create(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: UserInstance) => any): Promise<UserInstance>; + + /** + * Create a UserInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed UserInstance with HTTP metadata + */ + createWithHttpInfo(params: ScimUser, headers?: any, callback?: (error: Error | null, item?: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>>; + + + + + /** + * Streams UserInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + each(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UserInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UserListInstanceEachOptions, callback?: (item: UserInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UserInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise<UserPage>; + /** + * Retrieve a single target page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<UserPage>) => any): Promise<ApiResponse<UserPage>>; + /** + * Lists UserInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UserInstance[]) => any): Promise<UserInstance[]>; + list(params: UserListInstanceOptions, callback?: (error: Error | null, items: UserInstance[]) => any): Promise<UserInstance[]>; + /** + * Lists UserInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UserInstance[]>) => any): Promise<ApiResponse<UserInstance[]>>; + listWithHttpInfo(params: UserListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<UserInstance[]>) => any): Promise<ApiResponse<UserInstance[]>>; + /** + * Retrieve a single page of UserInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UserPage) => any): Promise<UserPage>; + page(params: UserListInstancePageOptions, callback?: (error: Error | null, items: UserPage) => any): Promise<UserPage>; + /** + * Retrieve a single page of UserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UserPage>) => any): Promise<ApiResponse<UserPage>>; + pageWithHttpInfo(params: UserListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<UserPage>) => any): Promise<ApiResponse<UserPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UserListInstance(version: Versionless, organizationSid: string): UserListInstance { + if (!isValidPathParam(organizationSid)) { + throw new Error('Parameter \'organizationSid\' is not valid.'); + } + + const instance = ((id, ) => instance.get(id, )) as UserListInstance; + + instance.get = function get(id, ): UserContext { + return new UserContextImpl(version, organizationSid, id); + } + + instance._version = version; + instance._solution = { organizationSid, }; + instance._uri = `/${organizationSid}/scim/Users`; + + instance.create = function create(params: ScimUser, headers?: any, callback?: (error: Error | null, items: UserInstance) => any): Promise<UserInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new UserInstance(operationVersion, payload, instance._solution.organizationSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ScimUser, headers?: any, callback?: (error: Error | null, items: ApiResponse<UserInstance>) => any): Promise<ApiResponse<UserInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/scim+json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<UserResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<UserInstance> => ({ + ...response, + body: new UserInstance(operationVersion, response.body, instance._solution.organizationSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: UserListInstancePageOptions | ((error: Error | null, items: UserPage) => any), callback?: (error: Error | null, items: UserPage) => any): Promise<UserPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["filter"] !== undefined) + data["filter"] = params["filter"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/scim+json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UserPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UserPage) => any): Promise<UserPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UserPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UserListInstancePageOptions | ((error: Error | null, items: ApiResponse<UserPage>) => any), callback?: (error: Error | null, items: ApiResponse<UserPage>) => any): Promise<ApiResponse<UserPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["filter"] !== undefined) + data["filter"] = params["filter"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/scim+json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<UserPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<UserPage>) => any): Promise<ApiResponse<UserPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<UserPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UserPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class UserPage extends Page<Versionless, UserPayload, UserResource, UserInstance> { +/** +* Initialize the UserPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: Versionless, response: Response<string>, solution: UserSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UserInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UserResource): UserInstance { + + return new UserInstance( + this._version, + payload, + this._solution.organizationSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/pricing/V1.ts b/rest/pricing/V1.ts new file mode 100644 index 000000000..857d78134 --- /dev/null +++ b/rest/pricing/V1.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Pricing + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import PricingBase from "../PricingBase"; +import Version from "../../base/Version"; +import { CountryListInstance } from "./v1/country"; +import { NumberListInstance } from "./v1/number"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Pricing + * + * @param domain - The Twilio (Twilio.Pricing) domain + */ + constructor(domain: PricingBase) { + super(domain, "v1"); + } + + /** countries - { Twilio.Pricing.V1.CountryListInstance } resource */ + protected _countries?: CountryListInstance; + /** numbers - { Twilio.Pricing.V1.NumberListInstance } resource */ + protected _numbers?: NumberListInstance; + + /** Getter for countries resource */ + get countries(): CountryListInstance { + this._countries = this._countries || CountryListInstance(this); + return this._countries; + } + + /** Getter for numbers resource */ + get numbers(): NumberListInstance { + this._numbers = this._numbers || NumberListInstance(this); + return this._numbers; + } + +} diff --git a/rest/pricing/V2.ts b/rest/pricing/V2.ts new file mode 100644 index 000000000..8d6da151c --- /dev/null +++ b/rest/pricing/V2.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Pricing + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import PricingBase from "../PricingBase"; +import Version from "../../base/Version"; +import { CountryListInstance } from "./v2/country"; +import { NumberListInstance } from "./v2/number"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Pricing + * + * @param domain - The Twilio (Twilio.Pricing) domain + */ + constructor(domain: PricingBase) { + super(domain, "v2"); + } + + /** countries - { Twilio.Pricing.V2.CountryListInstance } resource */ + protected _countries?: CountryListInstance; + /** numbers - { Twilio.Pricing.V2.NumberListInstance } resource */ + protected _numbers?: NumberListInstance; + + /** Getter for countries resource */ + get countries(): CountryListInstance { + this._countries = this._countries || CountryListInstance(this); + return this._countries; + } + + /** Getter for numbers resource */ + get numbers(): NumberListInstance { + this._numbers = this._numbers || NumberListInstance(this); + return this._numbers; + } + +} diff --git a/rest/pricing/v1/country.ts b/rest/pricing/v1/country.ts new file mode 100644 index 000000000..d886de4cc --- /dev/null +++ b/rest/pricing/v1/country.ts @@ -0,0 +1,1324 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Pricing + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class PricingV1MessagingMessagingCountryInstanceInboundSmsPrices { + "basePrice"?: number; + "currentPrice"?: number; + "numberType"?: string; + + constructor(payload) { + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.numberType = payload["number_type"]; + } +} + + +export class PricingV1MessagingMessagingCountryInstanceOutboundSmsPrices { + "carrier"?: string; + "mcc"?: string; + "mnc"?: string; + "prices"?: Array<PricingV1MessagingMessagingCountryInstanceOutboundSmsPricesPrices>; + + constructor(payload) { + this.carrier = payload["carrier"]; + this.mcc = payload["mcc"]; + this.mnc = payload["mnc"]; + this.prices = payload["prices"]; + } +} + + +export class PricingV1MessagingMessagingCountryInstanceOutboundSmsPricesPrices { + "basePrice"?: number; + "currentPrice"?: number; + "numberType"?: string; + + constructor(payload) { + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.numberType = payload["number_type"]; + } +} + + +export class PricingV1PhoneNumberPhoneNumberCountryInstancePhoneNumberPrices { + "basePrice"?: number; + "currentPrice"?: number; + "numberType"?: string; + + constructor(payload) { + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.numberType = payload["number_type"]; + } +} + + +export class PricingV1VoiceVoiceCountryInstanceInboundCallPrices { + "basePrice"?: number; + "currentPrice"?: number; + "numberType"?: string; + + constructor(payload) { + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.numberType = payload["number_type"]; + } +} + + +export class PricingV1VoiceVoiceCountryInstanceOutboundPrefixPrices { + "prefixes"?: Array<string>; + "basePrice"?: number; + "currentPrice"?: number; + "friendlyName"?: string; + + constructor(payload) { + this.prefixes = payload["prefixes"]; + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.friendlyName = payload["friendly_name"]; + } +} + + + + + + +/** + * Options to pass to each + */ +export interface CountryListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CountryInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CountryListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CountryListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +/** + * Options to pass to each + */ +export interface CountryListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CountryInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CountryListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CountryListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +/** + * Options to pass to each + */ +export interface CountryListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CountryInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CountryListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CountryListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CountryContext { + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CountryContextSolution { + "isoCountry": string; +} + +export class CountryContextImpl implements CountryContext { + protected _solution: CountryContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, isoCountry: string) { + if (!isValidPathParam(isoCountry)) { + throw new Error('Parameter \'isoCountry\' is not valid.'); + } + + this._solution = { isoCountry, }; + this._uri = `/Voice/Countries/${isoCountry}`; + } + + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CountryInstance(operationVersion, payload, instance._solution.isoCountry)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CountryResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CountryInstance> => ({ + ...response, + body: new CountryInstance(operationVersion, response.body, instance._solution.isoCountry) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CountryInstance(operationVersion, payload, instance._solution.isoCountry)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CountryResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CountryInstance> => ({ + ...response, + body: new CountryInstance(operationVersion, response.body, instance._solution.isoCountry) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CountryInstance(operationVersion, payload, instance._solution.isoCountry)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CountryResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CountryInstance> => ({ + ...response, + body: new CountryInstance(operationVersion, response.body, instance._solution.isoCountry) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CountryPayload extends TwilioResponsePayload { + countries: CountryResource[]; +} + +interface CountryResource { + country: string; + iso_country: string; + outbound_sms_prices: Array<PricingV1MessagingMessagingCountryInstanceOutboundSmsPrices>; + inbound_sms_prices: Array<PricingV1MessagingMessagingCountryInstanceInboundSmsPrices>; + price_unit: string; + url: string; + phone_number_prices: Array<PricingV1PhoneNumberPhoneNumberCountryInstancePhoneNumberPrices>; + outbound_prefix_prices: Array<PricingV1VoiceVoiceCountryInstanceOutboundPrefixPrices>; + inbound_call_prices: Array<PricingV1VoiceVoiceCountryInstanceInboundCallPrices>; +} + +export class CountryInstance { + protected _solution: CountryContextSolution; + protected _context?: CountryContext; + + constructor(protected _version: V1, payload: CountryResource, isoCountry?: string) { + + this.country = (payload.country); + this.isoCountry = (payload.iso_country); + this.outboundSmsPrices = payload.outbound_sms_prices !== null && payload.outbound_sms_prices !== undefined ? payload.outbound_sms_prices.map( + (payload: any) => new PricingV1MessagingMessagingCountryInstanceOutboundSmsPrices(payload) + ) : null; + this.inboundSmsPrices = payload.inbound_sms_prices !== null && payload.inbound_sms_prices !== undefined ? payload.inbound_sms_prices.map( + (payload: any) => new PricingV1MessagingMessagingCountryInstanceInboundSmsPrices(payload) + ) : null; + this.priceUnit = (payload.price_unit); + this.url = (payload.url); + this.phoneNumberPrices = payload.phone_number_prices !== null && payload.phone_number_prices !== undefined ? payload.phone_number_prices.map( + (payload: any) => new PricingV1PhoneNumberPhoneNumberCountryInstancePhoneNumberPrices(payload) + ) : null; + this.outboundPrefixPrices = payload.outbound_prefix_prices !== null && payload.outbound_prefix_prices !== undefined ? payload.outbound_prefix_prices.map( + (payload: any) => new PricingV1VoiceVoiceCountryInstanceOutboundPrefixPrices(payload) + ) : null; + this.inboundCallPrices = payload.inbound_call_prices !== null && payload.inbound_call_prices !== undefined ? payload.inbound_call_prices.map( + (payload: any) => new PricingV1VoiceVoiceCountryInstanceInboundCallPrices(payload) + ) : null; + + this._solution = { isoCountry: isoCountry, }; + } + + /** + * The name of the country. + */ + country: string; + /** + * The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + */ + isoCountry: string; + /** + * The list of [OutboundSMSPrice](https://www.twilio.com/docs/sms/api/pricing#outbound-sms-price) records that represent the price to send a message for each MCC/MNC applicable in this country. + */ + outboundSmsPrices: Array<PricingV1MessagingMessagingCountryInstanceOutboundSmsPrices>; + /** + * The list of [InboundPrice](https://www.twilio.com/docs/sms/api/pricing#inbound-price) records that describe the price to receive an inbound SMS to the different Twilio phone number types supported in this country + */ + inboundSmsPrices: Array<PricingV1MessagingMessagingCountryInstanceInboundSmsPrices>; + /** + * The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + */ + priceUnit: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The list of [PhoneNumberPrice](https://www.twilio.com/docs/phone-numbers/pricing#phone-number-price) records. + */ + phoneNumberPrices: Array<PricingV1PhoneNumberPhoneNumberCountryInstancePhoneNumberPrices>; + /** + * The list of OutboundPrefixPrice records, which include a list of the `prefixes`, the `friendly_name`, `base_price`, and the `current_price` for those prefixes. + */ + outboundPrefixPrices: Array<PricingV1VoiceVoiceCountryInstanceOutboundPrefixPrices>; + /** + * The list of [InboundCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) records. + */ + inboundCallPrices: Array<PricingV1VoiceVoiceCountryInstanceInboundCallPrices>; + + private get _proxy(): CountryContext { + this._context = this._context || new CountryContextImpl(this._version, this._solution.isoCountry); + return this._context; + } + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + country: this.country, + isoCountry: this.isoCountry, + outboundSmsPrices: this.outboundSmsPrices, + inboundSmsPrices: this.inboundSmsPrices, + priceUnit: this.priceUnit, + url: this.url, + phoneNumberPrices: this.phoneNumberPrices, + outboundPrefixPrices: this.outboundPrefixPrices, + inboundCallPrices: this.inboundCallPrices, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CountrySolution { +} + +export interface CountryListInstance { + _version: V1; + _solution: CountrySolution; + _uri: string; + + (isoCountry: string, ): CountryContext; + get(isoCountry: string, ): CountryContext; + + + + + + + + + + /** + * Streams CountryInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + each(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CountryInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single target page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + /** + * Lists CountryInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + list(params: CountryListInstanceOptions, callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + /** + * Lists CountryInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + listWithHttpInfo(params: CountryListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + /** + * Retrieve a single page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + page(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + pageWithHttpInfo(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + + + + /** + * Streams CountryInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + each(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CountryInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single target page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + /** + * Lists CountryInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + list(params: CountryListInstanceOptions, callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + /** + * Lists CountryInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + listWithHttpInfo(params: CountryListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + /** + * Retrieve a single page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + page(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + pageWithHttpInfo(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + + + + /** + * Streams CountryInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + each(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CountryInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single target page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + /** + * Lists CountryInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + list(params: CountryListInstanceOptions, callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + /** + * Lists CountryInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + listWithHttpInfo(params: CountryListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + /** + * Retrieve a single page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + page(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + pageWithHttpInfo(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CountryListInstance(version: V1): CountryListInstance { + const instance = ((isoCountry, ) => instance.get(isoCountry, )) as CountryListInstance; + + instance.get = function get(isoCountry, ): CountryContext { + return new CountryContextImpl(version, isoCountry); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Voice/Countries`; + + instance.page = function page(params?: CountryListInstancePageOptions | ((error: Error | null, items: CountryPage) => any), callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CountryPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CountryPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CountryListInstancePageOptions | ((error: Error | null, items: ApiResponse<CountryPage>) => any), callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.page = function page(params?: CountryListInstancePageOptions | ((error: Error | null, items: CountryPage) => any), callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CountryPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CountryPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CountryListInstancePageOptions | ((error: Error | null, items: ApiResponse<CountryPage>) => any), callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.page = function page(params?: CountryListInstancePageOptions | ((error: Error | null, items: CountryPage) => any), callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CountryPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CountryPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CountryListInstancePageOptions | ((error: Error | null, items: ApiResponse<CountryPage>) => any), callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CountryPage extends Page<V1, CountryPayload, CountryResource, CountryInstance> { +/** +* Initialize the CountryPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CountrySolution) { + super(version, response, solution); + } + + /** + * Build an instance of CountryInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CountryResource): CountryInstance { + + return new CountryInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/pricing/v1/number.ts b/rest/pricing/v1/number.ts new file mode 100644 index 000000000..ce0c51ff6 --- /dev/null +++ b/rest/pricing/v1/number.ts @@ -0,0 +1,300 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Pricing + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The [InboundCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) record. If `null`, the Phone Number is not a Twilio number owned by this account. + */ +export class PricingV1VoiceVoiceNumberInboundCallPrice { + "basePrice"?: number; + "currentPrice"?: number; + "numberType"?: string; + + constructor(payload) { + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.numberType = payload["number_type"]; + } +} + + +/** + * The OutboundCallPrice record, which includes a list of `origination_prefixes` and the `base_price` and `current_price` for those prefixes. + */ +export class PricingV1VoiceVoiceNumberOutboundCallPrice { + "basePrice"?: number; + "currentPrice"?: number; + + constructor(payload) { + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + } +} + + + + +export interface NumberContext { + + /** + * Fetch a NumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance + */ + fetch(callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance> + + /** + * Fetch a NumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface NumberContextSolution { + "number": string; +} + +export class NumberContextImpl implements NumberContext { + protected _solution: NumberContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, number: string) { + if (!isValidPathParam(number)) { + throw new Error('Parameter \'number\' is not valid.'); + } + + this._solution = { number, }; + this._uri = `/Voice/Numbers/${number}`; + } + + fetch(callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new NumberInstance(operationVersion, payload, instance._solution.number)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<NumberResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<NumberInstance> => ({ + ...response, + body: new NumberInstance(operationVersion, response.body, instance._solution.number) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface NumberPayload extends NumberResource {} + +interface NumberResource { + number: string; + country: string; + iso_country: string; + outbound_call_price: PricingV1VoiceVoiceNumberOutboundCallPrice; + inbound_call_price: PricingV1VoiceVoiceNumberInboundCallPrice; + price_unit: string; + url: string; +} + +export class NumberInstance { + protected _solution: NumberContextSolution; + protected _context?: NumberContext; + + constructor(protected _version: V1, payload: NumberResource, number?: string) { + + this.number = (payload.number); + this.country = (payload.country); + this.isoCountry = (payload.iso_country); + this.outboundCallPrice = payload.outbound_call_price !== null && payload.outbound_call_price !== undefined ? new PricingV1VoiceVoiceNumberOutboundCallPrice(payload.outbound_call_price) : null; + this.inboundCallPrice = payload.inbound_call_price !== null && payload.inbound_call_price !== undefined ? new PricingV1VoiceVoiceNumberInboundCallPrice(payload.inbound_call_price) : null; + this.priceUnit = (payload.price_unit); + this.url = (payload.url); + + this._solution = { number: number, }; + } + + /** + * The phone number. + */ + number: string; + /** + * The name of the country. + */ + country: string; + /** + * The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + */ + isoCountry: string; + outboundCallPrice: PricingV1VoiceVoiceNumberOutboundCallPrice; + inboundCallPrice: PricingV1VoiceVoiceNumberInboundCallPrice; + /** + * The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + */ + priceUnit: string; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): NumberContext { + this._context = this._context || new NumberContextImpl(this._version, this._solution.number); + return this._context; + } + + /** + * Fetch a NumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance + */ + fetch(callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a NumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + number: this.number, + country: this.country, + isoCountry: this.isoCountry, + outboundCallPrice: this.outboundCallPrice, + inboundCallPrice: this.inboundCallPrice, + priceUnit: this.priceUnit, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface NumberSolution { +} + +export interface NumberListInstance { + _version: V1; + _solution: NumberSolution; + _uri: string; + + (number: string, ): NumberContext; + get(number: string, ): NumberContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NumberListInstance(version: V1): NumberListInstance { + const instance = ((number, ) => instance.get(number, )) as NumberListInstance; + + instance.get = function get(number, ): NumberContext { + return new NumberContextImpl(version, number); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/pricing/v2/country.ts b/rest/pricing/v2/country.ts new file mode 100644 index 000000000..20bcbd621 --- /dev/null +++ b/rest/pricing/v2/country.ts @@ -0,0 +1,933 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Pricing + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class PricingV2TrunkingCountryInstanceOriginatingCallPrices { + "basePrice"?: number; + "currentPrice"?: number; + "numberType"?: string; + + constructor(payload) { + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.numberType = payload["number_type"]; + } +} + + +export class PricingV2TrunkingCountryInstanceTerminatingPrefixPrices { + "originationPrefixes"?: Array<string>; + "destinationPrefixes"?: Array<string>; + "basePrice"?: number; + "currentPrice"?: number; + "friendlyName"?: string; + + constructor(payload) { + this.originationPrefixes = payload["origination_prefixes"]; + this.destinationPrefixes = payload["destination_prefixes"]; + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.friendlyName = payload["friendly_name"]; + } +} + + + + + +/** + * Options to pass to each + */ +export interface CountryListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CountryInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CountryListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CountryListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +/** + * Options to pass to each + */ +export interface CountryListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CountryInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CountryListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CountryListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CountryContext { + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CountryContextSolution { + "isoCountry": string; +} + +export class CountryContextImpl implements CountryContext { + protected _solution: CountryContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, isoCountry: string) { + if (!isValidPathParam(isoCountry)) { + throw new Error('Parameter \'isoCountry\' is not valid.'); + } + + this._solution = { isoCountry, }; + this._uri = `/Voice/Countries/${isoCountry}`; + } + + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CountryInstance(operationVersion, payload, instance._solution.isoCountry)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CountryResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CountryInstance> => ({ + ...response, + body: new CountryInstance(operationVersion, response.body, instance._solution.isoCountry) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CountryInstance(operationVersion, payload, instance._solution.isoCountry)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CountryResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CountryInstance> => ({ + ...response, + body: new CountryInstance(operationVersion, response.body, instance._solution.isoCountry) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CountryPayload extends TwilioResponsePayload { + countries: CountryResource[]; +} + +interface CountryResource { + country: string; + iso_country: string; + terminating_prefix_prices: Array<PricingV2TrunkingCountryInstanceTerminatingPrefixPrices>; + originating_call_prices: Array<PricingV2TrunkingCountryInstanceOriginatingCallPrices>; + price_unit: string; + url: string; + outbound_prefix_prices: Array<PricingV2TrunkingCountryInstanceTerminatingPrefixPrices>; + inbound_call_prices: Array<PricingV2TrunkingCountryInstanceOriginatingCallPrices>; +} + +export class CountryInstance { + protected _solution: CountryContextSolution; + protected _context?: CountryContext; + + constructor(protected _version: V2, payload: CountryResource, isoCountry?: string) { + + this.country = (payload.country); + this.isoCountry = (payload.iso_country); + this.terminatingPrefixPrices = payload.terminating_prefix_prices !== null && payload.terminating_prefix_prices !== undefined ? payload.terminating_prefix_prices.map( + (payload: any) => new PricingV2TrunkingCountryInstanceTerminatingPrefixPrices(payload) + ) : null; + this.originatingCallPrices = payload.originating_call_prices !== null && payload.originating_call_prices !== undefined ? payload.originating_call_prices.map( + (payload: any) => new PricingV2TrunkingCountryInstanceOriginatingCallPrices(payload) + ) : null; + this.priceUnit = (payload.price_unit); + this.url = (payload.url); + this.outboundPrefixPrices = payload.outbound_prefix_prices !== null && payload.outbound_prefix_prices !== undefined ? payload.outbound_prefix_prices.map( + (payload: any) => new PricingV2TrunkingCountryInstanceTerminatingPrefixPrices(payload) + ) : null; + this.inboundCallPrices = payload.inbound_call_prices !== null && payload.inbound_call_prices !== undefined ? payload.inbound_call_prices.map( + (payload: any) => new PricingV2TrunkingCountryInstanceOriginatingCallPrices(payload) + ) : null; + + this._solution = { isoCountry: isoCountry, }; + } + + /** + * The name of the country. + */ + country: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + */ + isoCountry: string; + /** + * The list of [TerminatingPrefixPrice](https://www.twilio.com/docs/voice/pricing#outbound-prefix-price-with-origin) records. + */ + terminatingPrefixPrices: Array<PricingV2TrunkingCountryInstanceTerminatingPrefixPrices>; + /** + * The list of [OriginatingCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) records. + */ + originatingCallPrices: Array<PricingV2TrunkingCountryInstanceOriginatingCallPrices>; + /** + * The currency in which prices are measured, specified in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + */ + priceUnit: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The list of [OutboundPrefixPriceWithOrigin](https://www.twilio.com/docs/voice/pricing#outbound-prefix-price-with-origin) records. + */ + outboundPrefixPrices: Array<PricingV2TrunkingCountryInstanceTerminatingPrefixPrices>; + /** + * The list of [InboundCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) records. + */ + inboundCallPrices: Array<PricingV2TrunkingCountryInstanceOriginatingCallPrices>; + + private get _proxy(): CountryContext { + this._context = this._context || new CountryContextImpl(this._version, this._solution.isoCountry); + return this._context; + } + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + country: this.country, + isoCountry: this.isoCountry, + terminatingPrefixPrices: this.terminatingPrefixPrices, + originatingCallPrices: this.originatingCallPrices, + priceUnit: this.priceUnit, + url: this.url, + outboundPrefixPrices: this.outboundPrefixPrices, + inboundCallPrices: this.inboundCallPrices, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CountrySolution { +} + +export interface CountryListInstance { + _version: V2; + _solution: CountrySolution; + _uri: string; + + (isoCountry: string, ): CountryContext; + get(isoCountry: string, ): CountryContext; + + + + + + + + /** + * Streams CountryInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + each(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CountryInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single target page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + /** + * Lists CountryInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + list(params: CountryListInstanceOptions, callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + /** + * Lists CountryInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + listWithHttpInfo(params: CountryListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + /** + * Retrieve a single page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + page(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + pageWithHttpInfo(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + + + + /** + * Streams CountryInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + each(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CountryInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single target page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + /** + * Lists CountryInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + list(params: CountryListInstanceOptions, callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + /** + * Lists CountryInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + listWithHttpInfo(params: CountryListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + /** + * Retrieve a single page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + page(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + pageWithHttpInfo(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CountryListInstance(version: V2): CountryListInstance { + const instance = ((isoCountry, ) => instance.get(isoCountry, )) as CountryListInstance; + + instance.get = function get(isoCountry, ): CountryContext { + return new CountryContextImpl(version, isoCountry); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Voice/Countries`; + + instance.page = function page(params?: CountryListInstancePageOptions | ((error: Error | null, items: CountryPage) => any), callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CountryPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CountryPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CountryListInstancePageOptions | ((error: Error | null, items: ApiResponse<CountryPage>) => any), callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.page = function page(params?: CountryListInstancePageOptions | ((error: Error | null, items: CountryPage) => any), callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CountryPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CountryPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CountryListInstancePageOptions | ((error: Error | null, items: ApiResponse<CountryPage>) => any), callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CountryPage extends Page<V2, CountryPayload, CountryResource, CountryInstance> { +/** +* Initialize the CountryPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: CountrySolution) { + super(version, response, solution); + } + + /** + * Build an instance of CountryInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CountryResource): CountryInstance { + + return new CountryInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/pricing/v2/number.ts b/rest/pricing/v2/number.ts new file mode 100644 index 000000000..fd578b49c --- /dev/null +++ b/rest/pricing/v2/number.ts @@ -0,0 +1,590 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Pricing + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class PricingV2TrunkingCountryInstanceTerminatingPrefixPrices { + "originationPrefixes"?: Array<string>; + "destinationPrefixes"?: Array<string>; + "basePrice"?: number; + "currentPrice"?: number; + "friendlyName"?: string; + + constructor(payload) { + this.originationPrefixes = payload["origination_prefixes"]; + this.destinationPrefixes = payload["destination_prefixes"]; + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.friendlyName = payload["friendly_name"]; + } +} + + +/** + * The [OriginatingCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) record. + */ +export class PricingV2TrunkingNumberOriginatingCallPrice { + "basePrice"?: number; + "currentPrice"?: number; + "numberType"?: string; + + constructor(payload) { + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.numberType = payload["number_type"]; + } +} + + +/** + * The [InboundCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) record. + */ +export class PricingV2VoiceVoiceNumberInboundCallPrice { + "basePrice"?: number; + "currentPrice"?: number; + "numberType"?: string; + + constructor(payload) { + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.numberType = payload["number_type"]; + } +} + + +export class PricingV2VoiceVoiceNumberOutboundCallPrices { + "basePrice"?: number; + "currentPrice"?: number; + "originationPrefixes"?: Array<string>; + + constructor(payload) { + this.basePrice = payload["base_price"]; + this.currentPrice = payload["current_price"]; + this.originationPrefixes = payload["origination_prefixes"]; + } +} + + + +/** + * Options to pass to fetch a NumberInstance + */ +export interface NumberContextFetchOptions { + /** The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. */ + "originationNumber"?: string; +} + +/** + * Options to pass to fetch a NumberInstance + */ +export interface NumberContextFetchOptions { + /** The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. */ + "originationNumber"?: string; +} + +export interface NumberContext { + + /** + * Fetch a NumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance + */ + fetch(callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance>; + /** + * Fetch a NumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance + */ + fetch(params: NumberContextFetchOptions, callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance>; + + /** + * Fetch a NumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>>; + /** + * Fetch a NumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance with HTTP metadata + */ + fetchWithHttpInfo(params: NumberContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>>; + + /** + * Fetch a NumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance + */ + fetch(callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance>; + /** + * Fetch a NumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance + */ + fetch(params: NumberContextFetchOptions, callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance>; + + /** + * Fetch a NumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>>; + /** + * Fetch a NumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance with HTTP metadata + */ + fetchWithHttpInfo(params: NumberContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface NumberContextSolution { + "destinationNumber": string; +} + +export class NumberContextImpl implements NumberContext { + protected _solution: NumberContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, destinationNumber: string) { + if (!isValidPathParam(destinationNumber)) { + throw new Error('Parameter \'destinationNumber\' is not valid.'); + } + + this._solution = { destinationNumber, }; + this._uri = `/Voice/Numbers/${destinationNumber}`; + } + + fetch(params?: NumberContextFetchOptions | ((error: Error | null, item?: NumberInstance) => any),callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["originationNumber"] !== undefined) + data["OriginationNumber"] = params["originationNumber"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new NumberInstance(operationVersion, payload, instance._solution.destinationNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: NumberContextFetchOptions | ((error: Error | null, item?: ApiResponse<NumberInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["originationNumber"] !== undefined) + data["OriginationNumber"] = params["originationNumber"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<NumberResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<NumberInstance> => ({ + ...response, + body: new NumberInstance(operationVersion, response.body, instance._solution.destinationNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(params?: NumberContextFetchOptions | ((error: Error | null, item?: NumberInstance) => any),callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["originationNumber"] !== undefined) + data["OriginationNumber"] = params["originationNumber"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new NumberInstance(operationVersion, payload, instance._solution.destinationNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: NumberContextFetchOptions | ((error: Error | null, item?: ApiResponse<NumberInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["originationNumber"] !== undefined) + data["OriginationNumber"] = params["originationNumber"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<NumberResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<NumberInstance> => ({ + ...response, + body: new NumberInstance(operationVersion, response.body, instance._solution.destinationNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface NumberPayload extends NumberResource {} + +interface NumberResource { + destination_number: string; + origination_number: string; + country: string; + iso_country: string; + terminating_prefix_prices: Array<PricingV2TrunkingCountryInstanceTerminatingPrefixPrices>; + originating_call_price: PricingV2TrunkingNumberOriginatingCallPrice; + price_unit: string; + url: string; + outbound_call_prices: Array<PricingV2VoiceVoiceNumberOutboundCallPrices>; + inbound_call_price: PricingV2VoiceVoiceNumberInboundCallPrice; +} + +export class NumberInstance { + protected _solution: NumberContextSolution; + protected _context?: NumberContext; + + constructor(protected _version: V2, payload: NumberResource, destinationNumber?: string) { + + this.destinationNumber = (payload.destination_number); + this.originationNumber = (payload.origination_number); + this.country = (payload.country); + this.isoCountry = (payload.iso_country); + this.terminatingPrefixPrices = payload.terminating_prefix_prices !== null && payload.terminating_prefix_prices !== undefined ? payload.terminating_prefix_prices.map( + (payload: any) => new PricingV2TrunkingCountryInstanceTerminatingPrefixPrices(payload) + ) : null; + this.originatingCallPrice = payload.originating_call_price !== null && payload.originating_call_price !== undefined ? new PricingV2TrunkingNumberOriginatingCallPrice(payload.originating_call_price) : null; + this.priceUnit = (payload.price_unit); + this.url = (payload.url); + this.outboundCallPrices = payload.outbound_call_prices !== null && payload.outbound_call_prices !== undefined ? payload.outbound_call_prices.map( + (payload: any) => new PricingV2VoiceVoiceNumberOutboundCallPrices(payload) + ) : null; + this.inboundCallPrice = payload.inbound_call_price !== null && payload.inbound_call_price !== undefined ? new PricingV2VoiceVoiceNumberInboundCallPrice(payload.inbound_call_price) : null; + + this._solution = { destinationNumber: destinationNumber, }; + } + + /** + * The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + destinationNumber: string; + /** + * The origination phone number in [[E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + originationNumber: string; + /** + * The name of the country. + */ + country: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + */ + isoCountry: string; + terminatingPrefixPrices: Array<PricingV2TrunkingCountryInstanceTerminatingPrefixPrices>; + originatingCallPrice: PricingV2TrunkingNumberOriginatingCallPrice; + /** + * The currency in which prices are measured, specified in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + */ + priceUnit: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The list of [OutboundCallPriceWithOrigin](https://www.twilio.com/docs/voice/pricing#outbound-call-price-with-origin) records. + */ + outboundCallPrices: Array<PricingV2VoiceVoiceNumberOutboundCallPrices>; + inboundCallPrice: PricingV2VoiceVoiceNumberInboundCallPrice; + + private get _proxy(): NumberContext { + this._context = this._context || new NumberContextImpl(this._version, this._solution.destinationNumber); + return this._context; + } + + /** + * Fetch a NumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance + */ + fetch(callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance>; + /** + * Fetch a NumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance + */ + fetch(params: NumberContextFetchOptions, callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a NumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>>; + /** + * Fetch a NumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance with HTTP metadata + */ + fetchWithHttpInfo(params: NumberContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Fetch a NumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance + */ + fetch(callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance>; + /** + * Fetch a NumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance + */ + fetch(params: NumberContextFetchOptions, callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: NumberInstance) => any): Promise<NumberInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a NumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>>; + /** + * Fetch a NumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NumberInstance with HTTP metadata + */ + fetchWithHttpInfo(params: NumberContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<NumberInstance>) => any): Promise<ApiResponse<NumberInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + destinationNumber: this.destinationNumber, + originationNumber: this.originationNumber, + country: this.country, + isoCountry: this.isoCountry, + terminatingPrefixPrices: this.terminatingPrefixPrices, + originatingCallPrice: this.originatingCallPrice, + priceUnit: this.priceUnit, + url: this.url, + outboundCallPrices: this.outboundCallPrices, + inboundCallPrice: this.inboundCallPrice, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface NumberSolution { +} + +export interface NumberListInstance { + _version: V2; + _solution: NumberSolution; + _uri: string; + + (destinationNumber: string, ): NumberContext; + get(destinationNumber: string, ): NumberContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NumberListInstance(version: V2): NumberListInstance { + const instance = ((destinationNumber, ) => instance.get(destinationNumber, )) as NumberListInstance; + + instance.get = function get(destinationNumber, ): NumberContext { + return new NumberContextImpl(version, destinationNumber); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/proxy/V1.ts b/rest/proxy/V1.ts new file mode 100644 index 000000000..3654cdbfc --- /dev/null +++ b/rest/proxy/V1.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Proxy + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import ProxyBase from "../ProxyBase"; +import Version from "../../base/Version"; +import { ServiceListInstance } from "./v1/service"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Proxy + * + * @param domain - The Twilio (Twilio.Proxy) domain + */ + constructor(domain: ProxyBase) { + super(domain, "v1"); + } + + /** services - { Twilio.Proxy.V1.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + +} diff --git a/rest/proxy/v1/service.ts b/rest/proxy/v1/service.ts new file mode 100644 index 000000000..21e4c4157 --- /dev/null +++ b/rest/proxy/v1/service.ts @@ -0,0 +1,1063 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Proxy + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { PhoneNumberListInstance } from "./service/phoneNumber"; +import { SessionListInstance } from "./service/session"; + + +/** + * Where a proxy number must be located relative to the participant identifier. Can be: `country`, `area-code`, or `extended-area-code`. The default value is `country` and more specific areas than `country` are only available in North America. + */ +export type ServiceGeoMatchLevel = 'area-code'|'overlay'|'radius'|'country'; + +/** + * The preference for Proxy Number selection in the Service instance. Can be: `prefer-sticky` or `avoid-sticky`. `prefer-sticky` means that we will try and select the same Proxy Number for a given participant if they have previous [Sessions](https://www.twilio.com/docs/proxy/api/session), but we will not fail if that Proxy Number cannot be used. `avoid-sticky` means that we will try to use different Proxy Numbers as long as that is possible within a given pool rather than try and use a previously assigned number. + */ +export type ServiceNumberSelectionBehavior = 'avoid-sticky'|'prefer-sticky'; + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** */ + "uniqueName"?: string; + /** The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session\\\'s last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session\\\'s default TTL value by setting its `ttl` value. */ + "defaultTtl"?: number; + /** The URL we should call when the interaction status changes. */ + "callbackUrl"?: string; + /** */ + "geoMatchLevel"?: ServiceGeoMatchLevel; + /** */ + "numberSelectionBehavior"?: ServiceNumberSelectionBehavior; + /** The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. */ + "interceptCallbackUrl"?: string; + /** The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. */ + "outOfSessionCallbackUrl"?: string; + /** The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. */ + "chatInstanceSid"?: string; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** */ + "uniqueName": string; + /** The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session\\\'s last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session\\\'s default TTL value by setting its `ttl` value. */ + "defaultTtl"?: number; + /** The URL we should call when the interaction status changes. */ + "callbackUrl"?: string; + /** */ + "geoMatchLevel"?: ServiceGeoMatchLevel; + /** */ + "numberSelectionBehavior"?: ServiceNumberSelectionBehavior; + /** The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. */ + "interceptCallbackUrl"?: string; + /** The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. */ + "outOfSessionCallbackUrl"?: string; + /** The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. */ + "chatInstanceSid"?: string; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + phoneNumbers: PhoneNumberListInstance; + sessions: SessionListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _phoneNumbers?: PhoneNumberListInstance; + protected _sessions?: SessionListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get phoneNumbers(): PhoneNumberListInstance { + this._phoneNumbers = this._phoneNumbers || PhoneNumberListInstance(this._version, this._solution.sid); + return this._phoneNumbers; + } + + get sessions(): SessionListInstance { + this._sessions = this._sessions || SessionListInstance(this._version, this._solution.sid); + return this._sessions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["defaultTtl"] !== undefined) + data["DefaultTtl"] = params["defaultTtl"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["geoMatchLevel"] !== undefined) + data["GeoMatchLevel"] = params["geoMatchLevel"]; + if (params["numberSelectionBehavior"] !== undefined) + data["NumberSelectionBehavior"] = params["numberSelectionBehavior"]; + if (params["interceptCallbackUrl"] !== undefined) + data["InterceptCallbackUrl"] = params["interceptCallbackUrl"]; + if (params["outOfSessionCallbackUrl"] !== undefined) + data["OutOfSessionCallbackUrl"] = params["outOfSessionCallbackUrl"]; + if (params["chatInstanceSid"] !== undefined) + data["ChatInstanceSid"] = params["chatInstanceSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ServiceInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["defaultTtl"] !== undefined) + data["DefaultTtl"] = params["defaultTtl"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["geoMatchLevel"] !== undefined) + data["GeoMatchLevel"] = params["geoMatchLevel"]; + if (params["numberSelectionBehavior"] !== undefined) + data["NumberSelectionBehavior"] = params["numberSelectionBehavior"]; + if (params["interceptCallbackUrl"] !== undefined) + data["InterceptCallbackUrl"] = params["interceptCallbackUrl"]; + if (params["outOfSessionCallbackUrl"] !== undefined) + data["OutOfSessionCallbackUrl"] = params["outOfSessionCallbackUrl"]; + if (params["chatInstanceSid"] !== undefined) + data["ChatInstanceSid"] = params["chatInstanceSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + sid: string; + unique_name: string; + account_sid: string; + chat_instance_sid: string; + callback_url: string; + default_ttl: number; + number_selection_behavior: ServiceNumberSelectionBehavior; + geo_match_level: ServiceGeoMatchLevel; + intercept_callback_url: string; + out_of_session_callback_url: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V1, payload: ServiceResource, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.chatInstanceSid = (payload.chat_instance_sid); + this.callbackUrl = (payload.callback_url); + this.defaultTtl = deserialize.integer(payload.default_ttl); + this.numberSelectionBehavior = payload.number_selection_behavior; + this.geoMatchLevel = payload.geo_match_level; + this.interceptCallbackUrl = (payload.intercept_callback_url); + this.outOfSessionCallbackUrl = (payload.out_of_session_callback_url); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Service resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. Supports UTF-8 characters. **This value should not have PII.** + */ + uniqueName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + */ + accountSid: string; + /** + * The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + */ + chatInstanceSid: string; + /** + * The URL we call when the interaction status changes. + */ + callbackUrl: string; + /** + * The default `ttl` value for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session\'s last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session\'s default TTL value by setting its `ttl` value. + */ + defaultTtl: number; + numberSelectionBehavior: ServiceNumberSelectionBehavior; + geoMatchLevel: ServiceGeoMatchLevel; + /** + * The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + */ + interceptCallbackUrl: string; + /** + * The URL we call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + */ + outOfSessionCallbackUrl: string; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + */ + dateCreated: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + */ + dateUpdated: Date; + /** + * The absolute URL of the Service resource. + */ + url: string; + /** + * The URLs of resources related to the Service. + */ + links: Record<string, string>; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the phoneNumbers. + */ + phoneNumbers(): PhoneNumberListInstance { + return this._proxy.phoneNumbers; + } + + /** + * Access the sessions. + */ + sessions(): SessionListInstance { + return this._proxy.sessions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + chatInstanceSid: this.chatInstanceSid, + callbackUrl: this.callbackUrl, + defaultTtl: this.defaultTtl, + numberSelectionBehavior: this.numberSelectionBehavior, + geoMatchLevel: this.geoMatchLevel, + interceptCallbackUrl: this.interceptCallbackUrl, + outOfSessionCallbackUrl: this.outOfSessionCallbackUrl, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V1; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V1): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ServiceInstance) => any): Promise<ServiceInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + if (params["defaultTtl"] !== undefined) + data["DefaultTtl"] = params["defaultTtl"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["geoMatchLevel"] !== undefined) + data["GeoMatchLevel"] = params["geoMatchLevel"]; + if (params["numberSelectionBehavior"] !== undefined) + data["NumberSelectionBehavior"] = params["numberSelectionBehavior"]; + if (params["interceptCallbackUrl"] !== undefined) + data["InterceptCallbackUrl"] = params["interceptCallbackUrl"]; + if (params["outOfSessionCallbackUrl"] !== undefined) + data["OutOfSessionCallbackUrl"] = params["outOfSessionCallbackUrl"]; + if (params["chatInstanceSid"] !== undefined) + data["ChatInstanceSid"] = params["chatInstanceSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + if (params["defaultTtl"] !== undefined) + data["DefaultTtl"] = params["defaultTtl"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["geoMatchLevel"] !== undefined) + data["GeoMatchLevel"] = params["geoMatchLevel"]; + if (params["numberSelectionBehavior"] !== undefined) + data["NumberSelectionBehavior"] = params["numberSelectionBehavior"]; + if (params["interceptCallbackUrl"] !== undefined) + data["InterceptCallbackUrl"] = params["interceptCallbackUrl"]; + if (params["outOfSessionCallbackUrl"] !== undefined) + data["OutOfSessionCallbackUrl"] = params["outOfSessionCallbackUrl"]; + if (params["chatInstanceSid"] !== undefined) + data["ChatInstanceSid"] = params["chatInstanceSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse<ServicePage>) => any), callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page<V1, ServicePayload, ServiceResource, ServiceInstance> { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/proxy/v1/service/phoneNumber.ts b/rest/proxy/v1/service/phoneNumber.ts new file mode 100644 index 000000000..78a1e6b0c --- /dev/null +++ b/rest/proxy/v1/service/phoneNumber.ts @@ -0,0 +1,966 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Proxy + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../interfaces"; + + + + + +/** + * Options to pass to update a PhoneNumberInstance + */ +export interface PhoneNumberContextUpdateOptions { + /** Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. */ + "isReserved"?: boolean; +} + +/** + * Options to pass to create a PhoneNumberInstance + */ +export interface PhoneNumberListInstanceCreateOptions { + /** The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. */ + "sid"?: string; + /** The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. */ + "phoneNumber"?: string; + /** Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. */ + "isReserved"?: boolean; +} + +/** + * Options to pass to each + */ +export interface PhoneNumberListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PhoneNumberListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PhoneNumberListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PhoneNumberContext { + + /** + * Remove a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + + /** + * Update a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Update a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PhoneNumberContextSolution { + "serviceSid": string; + "sid": string; +} + +export class PhoneNumberContextImpl implements PhoneNumberContext { + protected _solution: PhoneNumberContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/PhoneNumbers/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: PhoneNumberContextUpdateOptions | ((error: Error | null, item?: PhoneNumberInstance) => any),callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["isReserved"] !== undefined) + data["IsReserved"] = serialize.bool(params["isReserved"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: PhoneNumberContextUpdateOptions | ((error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["isReserved"] !== undefined) + data["IsReserved"] = serialize.bool(params["isReserved"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PhoneNumberPayload extends TwilioResponsePayload { + phone_numbers: PhoneNumberResource[]; +} + +interface PhoneNumberResource { + sid: string; + account_sid: string; + service_sid: string; + date_created: Date; + date_updated: Date; + phone_number: string; + friendly_name: string; + iso_country: string; + capabilities: PhoneNumberCapabilities; + url: string; + is_reserved: boolean; + in_use: number; +} + +export class PhoneNumberInstance { + protected _solution: PhoneNumberContextSolution; + protected _context?: PhoneNumberContext; + + constructor(protected _version: V1, payload: PhoneNumberResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.phoneNumber = (payload.phone_number); + this.friendlyName = (payload.friendly_name); + this.isoCountry = (payload.iso_country); + this.capabilities = (payload.capabilities); + this.url = (payload.url); + this.isReserved = (payload.is_reserved); + this.inUse = deserialize.integer(payload.in_use); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the PhoneNumber resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. + */ + accountSid: string; + /** + * The SID of the PhoneNumber resource\'s parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + */ + serviceSid: string; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + */ + dateCreated: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + */ + dateUpdated: Date; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The ISO Country Code for the phone number. + */ + isoCountry: string; + capabilities: PhoneNumberCapabilities; + /** + * The absolute URL of the PhoneNumber resource. + */ + url: string; + /** + * Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + */ + isReserved: boolean; + /** + * The number of open session assigned to the number. See the [How many Phone Numbers do I need?](https://www.twilio.com/docs/proxy/phone-numbers-needed) guide for more information. + */ + inUse: number; + + private get _proxy(): PhoneNumberContext { + this._context = this._context || new PhoneNumberContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Update a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + update(params?: any, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + phoneNumber: this.phoneNumber, + friendlyName: this.friendlyName, + isoCountry: this.isoCountry, + capabilities: this.capabilities, + url: this.url, + isReserved: this.isReserved, + inUse: this.inUse, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PhoneNumberSolution { + serviceSid: string; +} + +export interface PhoneNumberListInstance { + _version: V1; + _solution: PhoneNumberSolution; + _uri: string; + + (sid: string, ): PhoneNumberContext; + get(sid: string, ): PhoneNumberContext; + + + + + + + + + /** + * Create a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + create(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Create a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + create(params: PhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + /** + * Create a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Create a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + createWithHttpInfo(params: PhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + + + + /** + * Streams PhoneNumberInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + each(params: PhoneNumberListInstanceEachOptions, callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PhoneNumberInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PhoneNumberListInstanceEachOptions, callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PhoneNumberInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage>; + /** + * Retrieve a single target page of PhoneNumberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>>; + /** + * Lists PhoneNumberInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PhoneNumberInstance[]) => any): Promise<PhoneNumberInstance[]>; + list(params: PhoneNumberListInstanceOptions, callback?: (error: Error | null, items: PhoneNumberInstance[]) => any): Promise<PhoneNumberInstance[]>; + /** + * Lists PhoneNumberInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PhoneNumberInstance[]>) => any): Promise<ApiResponse<PhoneNumberInstance[]>>; + listWithHttpInfo(params: PhoneNumberListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<PhoneNumberInstance[]>) => any): Promise<ApiResponse<PhoneNumberInstance[]>>; + /** + * Retrieve a single page of PhoneNumberInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage>; + page(params: PhoneNumberListInstancePageOptions, callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage>; + /** + * Retrieve a single page of PhoneNumberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>>; + pageWithHttpInfo(params: PhoneNumberListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PhoneNumberListInstance(version: V1, serviceSid: string): PhoneNumberListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as PhoneNumberListInstance; + + instance.get = function get(sid, ): PhoneNumberContext { + return new PhoneNumberContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/PhoneNumbers`; + + instance.create = function create(params?: PhoneNumberListInstanceCreateOptions | ((error: Error | null, items: PhoneNumberInstance) => any), callback?: (error: Error | null, items: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["sid"] !== undefined) + data["Sid"] = params["sid"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["isReserved"] !== undefined) + data["IsReserved"] = serialize.bool(params["isReserved"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: PhoneNumberListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<PhoneNumberInstance>) => any), callback?: (error: Error | null, items: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["sid"] !== undefined) + data["Sid"] = params["sid"]; + if (params["phoneNumber"] !== undefined) + data["PhoneNumber"] = params["phoneNumber"]; + if (params["isReserved"] !== undefined) + data["IsReserved"] = serialize.bool(params["isReserved"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: PhoneNumberListInstancePageOptions | ((error: Error | null, items: PhoneNumberPage) => any), callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PhoneNumberPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PhoneNumberPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PhoneNumberListInstancePageOptions | ((error: Error | null, items: ApiResponse<PhoneNumberPage>) => any), callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<PhoneNumberPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PhoneNumberPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<PhoneNumberPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PhoneNumberPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PhoneNumberPage extends Page<V1, PhoneNumberPayload, PhoneNumberResource, PhoneNumberInstance> { +/** +* Initialize the PhoneNumberPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: PhoneNumberSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PhoneNumberInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PhoneNumberResource): PhoneNumberInstance { + + return new PhoneNumberInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/proxy/v1/service/session.ts b/rest/proxy/v1/service/session.ts new file mode 100644 index 000000000..0cde54189 --- /dev/null +++ b/rest/proxy/v1/service/session.ts @@ -0,0 +1,1060 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Proxy + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { InteractionListInstance } from "./session/interaction"; +import { ParticipantListInstance } from "./session/participant"; + + +/** + * The Mode of the Session. Can be: `message-only`, `voice-only`, or `voice-and-message`. + */ +export type SessionMode = 'message-only'|'voice-only'|'voice-and-message'; + +/** + * The status of the Session. Can be: `open`, `in-progress`, `closed`, `failed`, or `unknown`. + */ +export type SessionStatus = 'open'|'in-progress'|'closed'|'failed'|'unknown'; + + + + +/** + * Options to pass to update a SessionInstance + */ +export interface SessionContextUpdateOptions { + /** The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. */ + "dateExpiry"?: Date; + /** The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session\\\'s last Interaction. */ + "ttl"?: number; + /** */ + "status"?: SessionStatus; +} + +/** + * Options to pass to create a SessionInstance + */ +export interface SessionListInstanceCreateOptions { + /** An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** */ + "uniqueName"?: string; + /** The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. */ + "dateExpiry"?: Date; + /** The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session\\\'s last Interaction. */ + "ttl"?: number; + /** */ + "mode"?: SessionMode; + /** */ + "status"?: SessionStatus; + /** The Participant objects to include in the new session. */ + "participants"?: Array<any>; +} + +/** + * Options to pass to each + */ +export interface SessionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SessionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SessionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SessionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SessionContext { + interactions: InteractionListInstance; + participants: ParticipantListInstance; + + /** + * Remove a SessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance + */ + fetch(callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance> + + /** + * Fetch a SessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>> + + /** + * Update a SessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance + */ + update(callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance>; + /** + * Update a SessionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance + */ + update(params: SessionContextUpdateOptions, callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance>; + + /** + * Update a SessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>>; + /** + * Update a SessionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance with HTTP metadata + */ + updateWithHttpInfo(params: SessionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SessionContextSolution { + "serviceSid": string; + "sid": string; +} + +export class SessionContextImpl implements SessionContext { + protected _solution: SessionContextSolution; + protected _uri: string; + + protected _interactions?: InteractionListInstance; + protected _participants?: ParticipantListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Sessions/${sid}`; + } + + get interactions(): InteractionListInstance { + this._interactions = this._interactions || InteractionListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._interactions; + } + + get participants(): ParticipantListInstance { + this._participants = this._participants || ParticipantListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._participants; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SessionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SessionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SessionInstance> => ({ + ...response, + body: new SessionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SessionContextUpdateOptions | ((error: Error | null, item?: SessionInstance) => any),callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["dateExpiry"] !== undefined) + data["DateExpiry"] = serialize.iso8601DateTime(params["dateExpiry"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SessionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SessionContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SessionInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["dateExpiry"] !== undefined) + data["DateExpiry"] = serialize.iso8601DateTime(params["dateExpiry"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SessionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SessionInstance> => ({ + ...response, + body: new SessionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SessionPayload extends TwilioResponsePayload { + sessions: SessionResource[]; +} + +interface SessionResource { + sid: string; + service_sid: string; + account_sid: string; + date_started: Date; + date_ended: Date; + date_last_interaction: Date; + date_expiry: Date; + unique_name: string; + status: SessionStatus; + closed_reason: string; + ttl: number; + mode: SessionMode; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class SessionInstance { + protected _solution: SessionContextSolution; + protected _context?: SessionContext; + + constructor(protected _version: V1, payload: SessionResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.serviceSid = (payload.service_sid); + this.accountSid = (payload.account_sid); + this.dateStarted = deserialize.iso8601DateTime(payload.date_started); + this.dateEnded = deserialize.iso8601DateTime(payload.date_ended); + this.dateLastInteraction = deserialize.iso8601DateTime(payload.date_last_interaction); + this.dateExpiry = deserialize.iso8601DateTime(payload.date_expiry); + this.uniqueName = (payload.unique_name); + this.status = payload.status; + this.closedReason = (payload.closed_reason); + this.ttl = deserialize.integer(payload.ttl); + this.mode = payload.mode; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Session resource. + */ + sid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/proxy/api/service) the session is associated with. + */ + serviceSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Session resource. + */ + accountSid: string; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session started. + */ + dateStarted: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session ended. + */ + dateEnded: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session last had an interaction. + */ + dateLastInteraction: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + */ + dateExpiry: Date; + /** + * An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. Supports UTF-8 characters. **This value should not have PII.** + */ + uniqueName: string; + status: SessionStatus; + /** + * The reason the Session ended. + */ + closedReason: string; + /** + * The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session\'s last Interaction. + */ + ttl: number; + mode: SessionMode; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + */ + dateCreated: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + */ + dateUpdated: Date; + /** + * The absolute URL of the Session resource. + */ + url: string; + /** + * The URLs of resources related to the Session. + */ + links: Record<string, string>; + + private get _proxy(): SessionContext { + this._context = this._context || new SessionContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a SessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance + */ + fetch(callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance + */ + update(callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance>; + /** + * Update a SessionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance + */ + update(params: SessionContextUpdateOptions, callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>>; + /** + * Update a SessionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance with HTTP metadata + */ + updateWithHttpInfo(params: SessionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the interactions. + */ + interactions(): InteractionListInstance { + return this._proxy.interactions; + } + + /** + * Access the participants. + */ + participants(): ParticipantListInstance { + return this._proxy.participants; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + serviceSid: this.serviceSid, + accountSid: this.accountSid, + dateStarted: this.dateStarted, + dateEnded: this.dateEnded, + dateLastInteraction: this.dateLastInteraction, + dateExpiry: this.dateExpiry, + uniqueName: this.uniqueName, + status: this.status, + closedReason: this.closedReason, + ttl: this.ttl, + mode: this.mode, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SessionSolution { + serviceSid: string; +} + +export interface SessionListInstance { + _version: V1; + _solution: SessionSolution; + _uri: string; + + (sid: string, ): SessionContext; + get(sid: string, ): SessionContext; + + + + + + + + + /** + * Create a SessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance + */ + create(callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance>; + /** + * Create a SessionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance + */ + create(params: SessionListInstanceCreateOptions, callback?: (error: Error | null, item?: SessionInstance) => any): Promise<SessionInstance>; + + /** + * Create a SessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>>; + /** + * Create a SessionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SessionInstance with HTTP metadata + */ + createWithHttpInfo(params: SessionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>>; + + + + + /** + * Streams SessionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SessionInstance, done: (err?: Error) => void) => void): void; + each(params: SessionListInstanceEachOptions, callback?: (item: SessionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SessionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SessionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SessionListInstanceEachOptions, callback?: (item: SessionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SessionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SessionPage) => any): Promise<SessionPage>; + /** + * Retrieve a single target page of SessionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SessionPage>) => any): Promise<ApiResponse<SessionPage>>; + /** + * Lists SessionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SessionInstance[]) => any): Promise<SessionInstance[]>; + list(params: SessionListInstanceOptions, callback?: (error: Error | null, items: SessionInstance[]) => any): Promise<SessionInstance[]>; + /** + * Lists SessionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SessionInstance[]>) => any): Promise<ApiResponse<SessionInstance[]>>; + listWithHttpInfo(params: SessionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SessionInstance[]>) => any): Promise<ApiResponse<SessionInstance[]>>; + /** + * Retrieve a single page of SessionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SessionPage) => any): Promise<SessionPage>; + page(params: SessionListInstancePageOptions, callback?: (error: Error | null, items: SessionPage) => any): Promise<SessionPage>; + /** + * Retrieve a single page of SessionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SessionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SessionPage>) => any): Promise<ApiResponse<SessionPage>>; + pageWithHttpInfo(params: SessionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SessionPage>) => any): Promise<ApiResponse<SessionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SessionListInstance(version: V1, serviceSid: string): SessionListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as SessionListInstance; + + instance.get = function get(sid, ): SessionContext { + return new SessionContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Sessions`; + + instance.create = function create(params?: SessionListInstanceCreateOptions | ((error: Error | null, items: SessionInstance) => any), callback?: (error: Error | null, items: SessionInstance) => any): Promise<SessionInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dateExpiry"] !== undefined) + data["DateExpiry"] = serialize.iso8601DateTime(params["dateExpiry"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["mode"] !== undefined) + data["Mode"] = params["mode"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["participants"] !== undefined) + data["Participants"] = serialize.map(params["participants"], (e: any) => serialize.object(e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SessionInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: SessionListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<SessionInstance>) => any), callback?: (error: Error | null, items: ApiResponse<SessionInstance>) => any): Promise<ApiResponse<SessionInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dateExpiry"] !== undefined) + data["DateExpiry"] = serialize.iso8601DateTime(params["dateExpiry"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["mode"] !== undefined) + data["Mode"] = params["mode"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["participants"] !== undefined) + data["Participants"] = serialize.map(params["participants"], (e: any) => serialize.object(e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SessionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SessionInstance> => ({ + ...response, + body: new SessionInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SessionListInstancePageOptions | ((error: Error | null, items: SessionPage) => any), callback?: (error: Error | null, items: SessionPage) => any): Promise<SessionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SessionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SessionPage) => any): Promise<SessionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SessionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SessionListInstancePageOptions | ((error: Error | null, items: ApiResponse<SessionPage>) => any), callback?: (error: Error | null, items: ApiResponse<SessionPage>) => any): Promise<ApiResponse<SessionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SessionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SessionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SessionPage>) => any): Promise<ApiResponse<SessionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SessionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SessionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SessionPage extends Page<V1, SessionPayload, SessionResource, SessionInstance> { +/** +* Initialize the SessionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SessionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SessionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SessionResource): SessionInstance { + + return new SessionInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/proxy/v1/service/session/interaction.ts b/rest/proxy/v1/service/session/interaction.ts new file mode 100644 index 000000000..45f93f324 --- /dev/null +++ b/rest/proxy/v1/service/session/interaction.ts @@ -0,0 +1,743 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Proxy + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The inbound resource status of the Interaction. Will always be `delivered` for messages and `in-progress` for calls. + */ +export type InteractionResourceStatus = 'accepted'|'answered'|'busy'|'canceled'|'completed'|'deleted'|'delivered'|'delivery-unknown'|'failed'|'in-progress'|'initiated'|'no-answer'|'queued'|'received'|'receiving'|'ringing'|'scheduled'|'sending'|'sent'|'undelivered'|'unknown'; + +/** + * The Type of the Interaction. Can be: `message`, `voice` or `unknown`. + */ +export type InteractionType = 'message'|'voice'|'unknown'; + + + + +/** + * Options to pass to each + */ +export interface InteractionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: InteractionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface InteractionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface InteractionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface InteractionContext { + + /** + * Remove a InteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a InteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a InteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance + */ + fetch(callback?: (error: Error | null, item?: InteractionInstance) => any): Promise<InteractionInstance> + + /** + * Fetch a InteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InteractionInstance>) => any): Promise<ApiResponse<InteractionInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface InteractionContextSolution { + "serviceSid": string; + "sessionSid": string; + "sid": string; +} + +export class InteractionContextImpl implements InteractionContext { + protected _solution: InteractionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sessionSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sessionSid)) { + throw new Error('Parameter \'sessionSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sessionSid, sid, }; + this._uri = `/Services/${serviceSid}/Sessions/${sessionSid}/Interactions/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: InteractionInstance) => any): Promise<InteractionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new InteractionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sessionSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InteractionInstance>) => any): Promise<ApiResponse<InteractionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<InteractionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<InteractionInstance> => ({ + ...response, + body: new InteractionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sessionSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface InteractionPayload extends TwilioResponsePayload { + interactions: InteractionResource[]; +} + +interface InteractionResource { + sid: string; + session_sid: string; + service_sid: string; + account_sid: string; + data: string; + type: InteractionType; + inbound_participant_sid: string; + inbound_resource_sid: string; + inbound_resource_status: InteractionResourceStatus; + inbound_resource_type: string; + inbound_resource_url: string; + outbound_participant_sid: string; + outbound_resource_sid: string; + outbound_resource_status: InteractionResourceStatus; + outbound_resource_type: string; + outbound_resource_url: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class InteractionInstance { + protected _solution: InteractionContextSolution; + protected _context?: InteractionContext; + + constructor(protected _version: V1, payload: InteractionResource, serviceSid: string, sessionSid: string, sid?: string) { + + this.sid = (payload.sid); + this.sessionSid = (payload.session_sid); + this.serviceSid = (payload.service_sid); + this.accountSid = (payload.account_sid); + this.data = (payload.data); + this.type = payload.type; + this.inboundParticipantSid = (payload.inbound_participant_sid); + this.inboundResourceSid = (payload.inbound_resource_sid); + this.inboundResourceStatus = payload.inbound_resource_status; + this.inboundResourceType = (payload.inbound_resource_type); + this.inboundResourceUrl = (payload.inbound_resource_url); + this.outboundParticipantSid = (payload.outbound_participant_sid); + this.outboundResourceSid = (payload.outbound_resource_sid); + this.outboundResourceStatus = payload.outbound_resource_status; + this.outboundResourceType = (payload.outbound_resource_type); + this.outboundResourceUrl = (payload.outbound_resource_url); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, sessionSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Interaction resource. + */ + sid: string; + /** + * The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. + */ + sessionSid: string; + /** + * The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + */ + serviceSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Interaction resource. + */ + accountSid: string; + /** + * A JSON string that includes the message body of message interactions (e.g. `{\"body\": \"hello\"}`) or the call duration (when available) of a call (e.g. `{\"duration\": \"5\"}`). + */ + data: string; + type: InteractionType; + /** + * The SID of the inbound [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + */ + inboundParticipantSid: string; + /** + * The SID of the inbound resource; either the [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + */ + inboundResourceSid: string; + inboundResourceStatus: InteractionResourceStatus; + /** + * The inbound resource type. Can be [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + */ + inboundResourceType: string; + /** + * The URL of the Twilio inbound resource + */ + inboundResourceUrl: string; + /** + * The SID of the outbound [Participant](https://www.twilio.com/docs/proxy/api/participant)). + */ + outboundParticipantSid: string; + /** + * The SID of the outbound resource; either the [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + */ + outboundResourceSid: string; + outboundResourceStatus: InteractionResourceStatus; + /** + * The outbound resource type. Can be: [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + */ + outboundResourceType: string; + /** + * The URL of the Twilio outbound resource. + */ + outboundResourceUrl: string; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the Interaction was created. + */ + dateCreated: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + */ + dateUpdated: Date; + /** + * The absolute URL of the Interaction resource. + */ + url: string; + + private get _proxy(): InteractionContext { + this._context = this._context || new InteractionContextImpl(this._version, this._solution.serviceSid, this._solution.sessionSid, this._solution.sid); + return this._context; + } + + /** + * Remove a InteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a InteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a InteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance + */ + fetch(callback?: (error: Error | null, item?: InteractionInstance) => any): Promise<InteractionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a InteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed InteractionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<InteractionInstance>) => any): Promise<ApiResponse<InteractionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + sessionSid: this.sessionSid, + serviceSid: this.serviceSid, + accountSid: this.accountSid, + data: this.data, + type: this.type, + inboundParticipantSid: this.inboundParticipantSid, + inboundResourceSid: this.inboundResourceSid, + inboundResourceStatus: this.inboundResourceStatus, + inboundResourceType: this.inboundResourceType, + inboundResourceUrl: this.inboundResourceUrl, + outboundParticipantSid: this.outboundParticipantSid, + outboundResourceSid: this.outboundResourceSid, + outboundResourceStatus: this.outboundResourceStatus, + outboundResourceType: this.outboundResourceType, + outboundResourceUrl: this.outboundResourceUrl, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface InteractionSolution { + serviceSid: string; + sessionSid: string; +} + +export interface InteractionListInstance { + _version: V1; + _solution: InteractionSolution; + _uri: string; + + (sid: string, ): InteractionContext; + get(sid: string, ): InteractionContext; + + + + + + + + /** + * Streams InteractionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: InteractionInstance, done: (err?: Error) => void) => void): void; + each(params: InteractionListInstanceEachOptions, callback?: (item: InteractionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams InteractionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: InteractionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: InteractionListInstanceEachOptions, callback?: (item: InteractionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of InteractionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: InteractionPage) => any): Promise<InteractionPage>; + /** + * Retrieve a single target page of InteractionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<InteractionPage>) => any): Promise<ApiResponse<InteractionPage>>; + /** + * Lists InteractionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: InteractionInstance[]) => any): Promise<InteractionInstance[]>; + list(params: InteractionListInstanceOptions, callback?: (error: Error | null, items: InteractionInstance[]) => any): Promise<InteractionInstance[]>; + /** + * Lists InteractionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<InteractionInstance[]>) => any): Promise<ApiResponse<InteractionInstance[]>>; + listWithHttpInfo(params: InteractionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<InteractionInstance[]>) => any): Promise<ApiResponse<InteractionInstance[]>>; + /** + * Retrieve a single page of InteractionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: InteractionPage) => any): Promise<InteractionPage>; + page(params: InteractionListInstancePageOptions, callback?: (error: Error | null, items: InteractionPage) => any): Promise<InteractionPage>; + /** + * Retrieve a single page of InteractionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { InteractionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<InteractionPage>) => any): Promise<ApiResponse<InteractionPage>>; + pageWithHttpInfo(params: InteractionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<InteractionPage>) => any): Promise<ApiResponse<InteractionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function InteractionListInstance(version: V1, serviceSid: string, sessionSid: string): InteractionListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sessionSid)) { + throw new Error('Parameter \'sessionSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as InteractionListInstance; + + instance.get = function get(sid, ): InteractionContext { + return new InteractionContextImpl(version, serviceSid, sessionSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, sessionSid, }; + instance._uri = `/Services/${serviceSid}/Sessions/${sessionSid}/Interactions`; + + instance.page = function page(params?: InteractionListInstancePageOptions | ((error: Error | null, items: InteractionPage) => any), callback?: (error: Error | null, items: InteractionPage) => any): Promise<InteractionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new InteractionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: InteractionPage) => any): Promise<InteractionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new InteractionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: InteractionListInstancePageOptions | ((error: Error | null, items: ApiResponse<InteractionPage>) => any), callback?: (error: Error | null, items: ApiResponse<InteractionPage>) => any): Promise<ApiResponse<InteractionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<InteractionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InteractionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<InteractionPage>) => any): Promise<ApiResponse<InteractionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<InteractionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new InteractionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class InteractionPage extends Page<V1, InteractionPayload, InteractionResource, InteractionInstance> { +/** +* Initialize the InteractionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: InteractionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of InteractionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: InteractionResource): InteractionInstance { + + return new InteractionInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.sessionSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/proxy/v1/service/session/participant.ts b/rest/proxy/v1/service/session/participant.ts new file mode 100644 index 000000000..c31d45329 --- /dev/null +++ b/rest/proxy/v1/service/session/participant.ts @@ -0,0 +1,832 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Proxy + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { MessageInteractionListInstance } from "./participant/messageInteraction"; + + + + + +/** + * Options to pass to create a ParticipantInstance + */ +export interface ParticipantListInstanceCreateOptions { + /** The phone number of the Participant. */ + "identifier": string; + /** The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** */ + "friendlyName"?: string; + /** The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. */ + "proxyIdentifier"?: string; + /** The SID of the Proxy Identifier to assign to the Participant. */ + "proxyIdentifierSid"?: string; +} + +/** + * Options to pass to each + */ +export interface ParticipantListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ParticipantListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ParticipantListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ParticipantContext { + messageInteractions: MessageInteractionListInstance; + + /** + * Remove a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance> + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ParticipantContextSolution { + "serviceSid": string; + "sessionSid": string; + "sid": string; +} + +export class ParticipantContextImpl implements ParticipantContext { + protected _solution: ParticipantContextSolution; + protected _uri: string; + + protected _messageInteractions?: MessageInteractionListInstance; + + constructor(protected _version: V1, serviceSid: string, sessionSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sessionSid)) { + throw new Error('Parameter \'sessionSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sessionSid, sid, }; + this._uri = `/Services/${serviceSid}/Sessions/${sessionSid}/Participants/${sid}`; + } + + get messageInteractions(): MessageInteractionListInstance { + this._messageInteractions = this._messageInteractions || MessageInteractionListInstance(this._version, this._solution.serviceSid, this._solution.sessionSid, this._solution.sid); + return this._messageInteractions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sessionSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ParticipantResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ParticipantInstance> => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sessionSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ParticipantPayload extends TwilioResponsePayload { + participants: ParticipantResource[]; +} + +interface ParticipantResource { + sid: string; + session_sid: string; + service_sid: string; + account_sid: string; + friendly_name: string; + identifier: string; + proxy_identifier: string; + proxy_identifier_sid: string; + date_deleted: Date; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class ParticipantInstance { + protected _solution: ParticipantContextSolution; + protected _context?: ParticipantContext; + + constructor(protected _version: V1, payload: ParticipantResource, serviceSid: string, sessionSid: string, sid?: string) { + + this.sid = (payload.sid); + this.sessionSid = (payload.session_sid); + this.serviceSid = (payload.service_sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.identifier = (payload.identifier); + this.proxyIdentifier = (payload.proxy_identifier); + this.proxyIdentifierSid = (payload.proxy_identifier_sid); + this.dateDeleted = deserialize.iso8601DateTime(payload.date_deleted); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sessionSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Participant resource. + */ + sid: string; + /** + * The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. + */ + sessionSid: string; + /** + * The SID of the resource\'s parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + */ + serviceSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the participant. This value must be 255 characters or fewer. Supports UTF-8 characters. **This value should not have PII.** + */ + friendlyName: string; + /** + * The phone number or channel identifier of the Participant. This value must be 191 characters or fewer. Supports UTF-8 characters. + */ + identifier: string; + /** + * The phone number or short code (masked number) of the participant\'s partner. The participant will call or message the partner participant at this number. + */ + proxyIdentifier: string; + /** + * The SID of the Proxy Identifier assigned to the Participant. + */ + proxyIdentifierSid: string; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Participant was removed from the session. + */ + dateDeleted: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + */ + dateCreated: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + */ + dateUpdated: Date; + /** + * The absolute URL of the Participant resource. + */ + url: string; + /** + * The URLs to resources related the participant. + */ + links: Record<string, string>; + + private get _proxy(): ParticipantContext { + this._context = this._context || new ParticipantContextImpl(this._version, this._solution.serviceSid, this._solution.sessionSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the messageInteractions. + */ + messageInteractions(): MessageInteractionListInstance { + return this._proxy.messageInteractions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + sessionSid: this.sessionSid, + serviceSid: this.serviceSid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + identifier: this.identifier, + proxyIdentifier: this.proxyIdentifier, + proxyIdentifierSid: this.proxyIdentifierSid, + dateDeleted: this.dateDeleted, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ParticipantSolution { + serviceSid: string; + sessionSid: string; +} + +export interface ParticipantListInstance { + _version: V1; + _solution: ParticipantSolution; + _uri: string; + + (sid: string, ): ParticipantContext; + get(sid: string, ): ParticipantContext; + + + + + + + /** + * Create a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + create(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance>; + + /** + * Create a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + createWithHttpInfo(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>>; + + + + + /** + * Streams ParticipantInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + each(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ParticipantInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise<ParticipantPage>; + /** + * Retrieve a single target page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ParticipantPage>) => any): Promise<ApiResponse<ParticipantPage>>; + /** + * Lists ParticipantInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise<ParticipantInstance[]>; + list(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise<ParticipantInstance[]>; + /** + * Lists ParticipantInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ParticipantInstance[]>) => any): Promise<ApiResponse<ParticipantInstance[]>>; + listWithHttpInfo(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ParticipantInstance[]>) => any): Promise<ApiResponse<ParticipantInstance[]>>; + /** + * Retrieve a single page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ParticipantPage) => any): Promise<ParticipantPage>; + page(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ParticipantPage) => any): Promise<ParticipantPage>; + /** + * Retrieve a single page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ParticipantPage>) => any): Promise<ApiResponse<ParticipantPage>>; + pageWithHttpInfo(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ParticipantPage>) => any): Promise<ApiResponse<ParticipantPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ParticipantListInstance(version: V1, serviceSid: string, sessionSid: string): ParticipantListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sessionSid)) { + throw new Error('Parameter \'sessionSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ParticipantListInstance; + + instance.get = function get(sid, ): ParticipantContext { + return new ParticipantContextImpl(version, serviceSid, sessionSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, sessionSid, }; + instance._uri = `/Services/${serviceSid}/Sessions/${sessionSid}/Participants`; + + instance.create = function create(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, items: ParticipantInstance) => any): Promise<ParticipantInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identifier"] === null || params["identifier"] === undefined) { + throw new Error('Required parameter "params[\'identifier\']" missing.'); + } + + let data: any = {}; + + + + data["Identifier"] = params["identifier"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["proxyIdentifier"] !== undefined) + data["ProxyIdentifier"] = params["proxyIdentifier"]; + if (params["proxyIdentifierSid"] !== undefined) + data["ProxyIdentifierSid"] = params["proxyIdentifierSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sessionSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ParticipantListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identifier"] === null || params["identifier"] === undefined) { + throw new Error('Required parameter "params[\'identifier\']" missing.'); + } + + let data: any = {}; + + + + data["Identifier"] = params["identifier"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["proxyIdentifier"] !== undefined) + data["ProxyIdentifier"] = params["proxyIdentifier"]; + if (params["proxyIdentifierSid"] !== undefined) + data["ProxyIdentifierSid"] = params["proxyIdentifierSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ParticipantResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ParticipantInstance> => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sessionSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ParticipantPage) => any), callback?: (error: Error | null, items: ParticipantPage) => any): Promise<ParticipantPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ParticipantPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise<ParticipantPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ParticipantPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ApiResponse<ParticipantPage>) => any), callback?: (error: Error | null, items: ApiResponse<ParticipantPage>) => any): Promise<ApiResponse<ParticipantPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ParticipantPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ParticipantPage>) => any): Promise<ApiResponse<ParticipantPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ParticipantPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ParticipantPage extends Page<V1, ParticipantPayload, ParticipantResource, ParticipantInstance> { +/** +* Initialize the ParticipantPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ParticipantSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ParticipantInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ParticipantResource): ParticipantInstance { + + return new ParticipantInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.sessionSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/proxy/v1/service/session/participant/messageInteraction.ts b/rest/proxy/v1/service/session/participant/messageInteraction.ts new file mode 100644 index 000000000..fce9b419c --- /dev/null +++ b/rest/proxy/v1/service/session/participant/messageInteraction.ts @@ -0,0 +1,802 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Proxy + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../../base/Page"; +import Response from "../../../../../../http/response"; +import V1 from "../../../../V1"; +const deserialize = require("../../../../../../base/deserialize"); +const serialize = require("../../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../../base/utility"; +import { ApiResponse } from "../../../../../../base/ApiResponse"; + + +/** + * Always empty for created Message Interactions. + */ +export type MessageInteractionResourceStatus = 'accepted'|'answered'|'busy'|'canceled'|'completed'|'deleted'|'delivered'|'delivery-unknown'|'failed'|'in-progress'|'initiated'|'no-answer'|'queued'|'received'|'receiving'|'ringing'|'scheduled'|'sending'|'sent'|'undelivered'|'unknown'; + +/** + * The Type of Message Interaction. This value is always `message`. + */ +export type MessageInteractionType = 'message'|'voice'|'unknown'; + + + +/** + * Options to pass to create a MessageInteractionInstance + */ +export interface MessageInteractionListInstanceCreateOptions { + /** The message to send to the participant */ + "body"?: string; + /** Reserved. Not currently supported. */ + "mediaUrl"?: Array<string>; +} + +/** + * Options to pass to each + */ +export interface MessageInteractionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MessageInteractionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MessageInteractionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MessageInteractionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MessageInteractionContext { + + /** + * Fetch a MessageInteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInteractionInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInteractionInstance) => any): Promise<MessageInteractionInstance> + + /** + * Fetch a MessageInteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInteractionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<MessageInteractionInstance>) => any): Promise<ApiResponse<MessageInteractionInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MessageInteractionContextSolution { + "serviceSid": string; + "sessionSid": string; + "participantSid": string; + "sid": string; +} + +export class MessageInteractionContextImpl implements MessageInteractionContext { + protected _solution: MessageInteractionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sessionSid: string, participantSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sessionSid)) { + throw new Error('Parameter \'sessionSid\' is not valid.'); + } + + if (!isValidPathParam(participantSid)) { + throw new Error('Parameter \'participantSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sessionSid, participantSid, sid, }; + this._uri = `/Services/${serviceSid}/Sessions/${sessionSid}/Participants/${participantSid}/MessageInteractions/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: MessageInteractionInstance) => any): Promise<MessageInteractionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MessageInteractionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sessionSid, instance._solution.participantSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<MessageInteractionInstance>) => any): Promise<ApiResponse<MessageInteractionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<MessageInteractionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<MessageInteractionInstance> => ({ + ...response, + body: new MessageInteractionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sessionSid, instance._solution.participantSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MessageInteractionPayload extends TwilioResponsePayload { + interactions: MessageInteractionResource[]; +} + +interface MessageInteractionResource { + sid: string; + session_sid: string; + service_sid: string; + account_sid: string; + data: string; + type: MessageInteractionType; + participant_sid: string; + inbound_participant_sid: string; + inbound_resource_sid: string; + inbound_resource_status: MessageInteractionResourceStatus; + inbound_resource_type: string; + inbound_resource_url: string; + outbound_participant_sid: string; + outbound_resource_sid: string; + outbound_resource_status: MessageInteractionResourceStatus; + outbound_resource_type: string; + outbound_resource_url: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class MessageInteractionInstance { + protected _solution: MessageInteractionContextSolution; + protected _context?: MessageInteractionContext; + + constructor(protected _version: V1, payload: MessageInteractionResource, serviceSid: string, sessionSid: string, participantSid: string, sid?: string) { + + this.sid = (payload.sid); + this.sessionSid = (payload.session_sid); + this.serviceSid = (payload.service_sid); + this.accountSid = (payload.account_sid); + this.data = (payload.data); + this.type = payload.type; + this.participantSid = (payload.participant_sid); + this.inboundParticipantSid = (payload.inbound_participant_sid); + this.inboundResourceSid = (payload.inbound_resource_sid); + this.inboundResourceStatus = payload.inbound_resource_status; + this.inboundResourceType = (payload.inbound_resource_type); + this.inboundResourceUrl = (payload.inbound_resource_url); + this.outboundParticipantSid = (payload.outbound_participant_sid); + this.outboundResourceSid = (payload.outbound_resource_sid); + this.outboundResourceStatus = payload.outbound_resource_status; + this.outboundResourceType = (payload.outbound_resource_type); + this.outboundResourceUrl = (payload.outbound_resource_url); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, sessionSid, participantSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the MessageInteraction resource. + */ + sid: string; + /** + * The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. + */ + sessionSid: string; + /** + * The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + */ + serviceSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the MessageInteraction resource. + */ + accountSid: string; + /** + * A JSON string that includes the message body sent to the participant. (e.g. `{\"body\": \"hello\"}`) + */ + data: string; + type: MessageInteractionType; + /** + * The SID of the [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + */ + participantSid: string; + /** + * Always empty for created Message Interactions. + */ + inboundParticipantSid: string; + /** + * Always empty for created Message Interactions. + */ + inboundResourceSid: string; + inboundResourceStatus: MessageInteractionResourceStatus; + /** + * Always empty for created Message Interactions. + */ + inboundResourceType: string; + /** + * Always empty for created Message Interactions. + */ + inboundResourceUrl: string; + /** + * The SID of the outbound [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + */ + outboundParticipantSid: string; + /** + * The SID of the outbound [Message](https://www.twilio.com/docs/sms/api/message-resource) resource. + */ + outboundResourceSid: string; + outboundResourceStatus: MessageInteractionResourceStatus; + /** + * The outbound resource type. This value is always `Message`. + */ + outboundResourceType: string; + /** + * The URL of the Twilio message resource. + */ + outboundResourceUrl: string; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + */ + dateCreated: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + */ + dateUpdated: Date; + /** + * The absolute URL of the MessageInteraction resource. + */ + url: string; + + private get _proxy(): MessageInteractionContext { + this._context = this._context || new MessageInteractionContextImpl(this._version, this._solution.serviceSid, this._solution.sessionSid, this._solution.participantSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a MessageInteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInteractionInstance + */ + fetch(callback?: (error: Error | null, item?: MessageInteractionInstance) => any): Promise<MessageInteractionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MessageInteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInteractionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<MessageInteractionInstance>) => any): Promise<ApiResponse<MessageInteractionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + sessionSid: this.sessionSid, + serviceSid: this.serviceSid, + accountSid: this.accountSid, + data: this.data, + type: this.type, + participantSid: this.participantSid, + inboundParticipantSid: this.inboundParticipantSid, + inboundResourceSid: this.inboundResourceSid, + inboundResourceStatus: this.inboundResourceStatus, + inboundResourceType: this.inboundResourceType, + inboundResourceUrl: this.inboundResourceUrl, + outboundParticipantSid: this.outboundParticipantSid, + outboundResourceSid: this.outboundResourceSid, + outboundResourceStatus: this.outboundResourceStatus, + outboundResourceType: this.outboundResourceType, + outboundResourceUrl: this.outboundResourceUrl, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MessageInteractionSolution { + serviceSid: string; + sessionSid: string; + participantSid: string; +} + +export interface MessageInteractionListInstance { + _version: V1; + _solution: MessageInteractionSolution; + _uri: string; + + (sid: string, ): MessageInteractionContext; + get(sid: string, ): MessageInteractionContext; + + + + + /** + * Create a MessageInteractionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInteractionInstance + */ + create(callback?: (error: Error | null, item?: MessageInteractionInstance) => any): Promise<MessageInteractionInstance>; + /** + * Create a MessageInteractionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInteractionInstance + */ + create(params: MessageInteractionListInstanceCreateOptions, callback?: (error: Error | null, item?: MessageInteractionInstance) => any): Promise<MessageInteractionInstance>; + + /** + * Create a MessageInteractionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInteractionInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<MessageInteractionInstance>) => any): Promise<ApiResponse<MessageInteractionInstance>>; + /** + * Create a MessageInteractionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessageInteractionInstance with HTTP metadata + */ + createWithHttpInfo(params: MessageInteractionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<MessageInteractionInstance>) => any): Promise<ApiResponse<MessageInteractionInstance>>; + + + + + /** + * Streams MessageInteractionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageInteractionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MessageInteractionInstance, done: (err?: Error) => void) => void): void; + each(params: MessageInteractionListInstanceEachOptions, callback?: (item: MessageInteractionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MessageInteractionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageInteractionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MessageInteractionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MessageInteractionListInstanceEachOptions, callback?: (item: MessageInteractionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MessageInteractionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MessageInteractionPage) => any): Promise<MessageInteractionPage>; + /** + * Retrieve a single target page of MessageInteractionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<MessageInteractionPage>) => any): Promise<ApiResponse<MessageInteractionPage>>; + /** + * Lists MessageInteractionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageInteractionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MessageInteractionInstance[]) => any): Promise<MessageInteractionInstance[]>; + list(params: MessageInteractionListInstanceOptions, callback?: (error: Error | null, items: MessageInteractionInstance[]) => any): Promise<MessageInteractionInstance[]>; + /** + * Lists MessageInteractionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageInteractionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<MessageInteractionInstance[]>) => any): Promise<ApiResponse<MessageInteractionInstance[]>>; + listWithHttpInfo(params: MessageInteractionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<MessageInteractionInstance[]>) => any): Promise<ApiResponse<MessageInteractionInstance[]>>; + /** + * Retrieve a single page of MessageInteractionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageInteractionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MessageInteractionPage) => any): Promise<MessageInteractionPage>; + page(params: MessageInteractionListInstancePageOptions, callback?: (error: Error | null, items: MessageInteractionPage) => any): Promise<MessageInteractionPage>; + /** + * Retrieve a single page of MessageInteractionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessageInteractionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<MessageInteractionPage>) => any): Promise<ApiResponse<MessageInteractionPage>>; + pageWithHttpInfo(params: MessageInteractionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<MessageInteractionPage>) => any): Promise<ApiResponse<MessageInteractionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessageInteractionListInstance(version: V1, serviceSid: string, sessionSid: string, participantSid: string): MessageInteractionListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sessionSid)) { + throw new Error('Parameter \'sessionSid\' is not valid.'); + } + + if (!isValidPathParam(participantSid)) { + throw new Error('Parameter \'participantSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as MessageInteractionListInstance; + + instance.get = function get(sid, ): MessageInteractionContext { + return new MessageInteractionContextImpl(version, serviceSid, sessionSid, participantSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, sessionSid, participantSid, }; + instance._uri = `/Services/${serviceSid}/Sessions/${sessionSid}/Participants/${participantSid}/MessageInteractions`; + + instance.create = function create(params?: MessageInteractionListInstanceCreateOptions | ((error: Error | null, items: MessageInteractionInstance) => any), callback?: (error: Error | null, items: MessageInteractionInstance) => any): Promise<MessageInteractionInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["mediaUrl"] !== undefined) + data["MediaUrl"] = serialize.map(params["mediaUrl"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessageInteractionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sessionSid, instance._solution.participantSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: MessageInteractionListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<MessageInteractionInstance>) => any), callback?: (error: Error | null, items: ApiResponse<MessageInteractionInstance>) => any): Promise<ApiResponse<MessageInteractionInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["body"] !== undefined) + data["Body"] = params["body"]; + if (params["mediaUrl"] !== undefined) + data["MediaUrl"] = serialize.map(params["mediaUrl"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<MessageInteractionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<MessageInteractionInstance> => ({ + ...response, + body: new MessageInteractionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sessionSid, instance._solution.participantSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MessageInteractionListInstancePageOptions | ((error: Error | null, items: MessageInteractionPage) => any), callback?: (error: Error | null, items: MessageInteractionPage) => any): Promise<MessageInteractionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MessageInteractionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MessageInteractionPage) => any): Promise<MessageInteractionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MessageInteractionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MessageInteractionListInstancePageOptions | ((error: Error | null, items: ApiResponse<MessageInteractionPage>) => any), callback?: (error: Error | null, items: ApiResponse<MessageInteractionPage>) => any): Promise<ApiResponse<MessageInteractionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<MessageInteractionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessageInteractionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<MessageInteractionPage>) => any): Promise<ApiResponse<MessageInteractionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<MessageInteractionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessageInteractionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MessageInteractionPage extends Page<V1, MessageInteractionPayload, MessageInteractionResource, MessageInteractionInstance> { +/** +* Initialize the MessageInteractionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: MessageInteractionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MessageInteractionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MessageInteractionResource): MessageInteractionInstance { + + return new MessageInteractionInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.sessionSid, + this._solution.participantSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/routes/V2.ts b/rest/routes/V2.ts new file mode 100644 index 000000000..915a43147 --- /dev/null +++ b/rest/routes/V2.ts @@ -0,0 +1,56 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Routes + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import RoutesBase from "../RoutesBase"; +import Version from "../../base/Version"; +import { PhoneNumberListInstance } from "./v2/phoneNumber"; +import { SipDomainListInstance } from "./v2/sipDomain"; +import { TrunkListInstance } from "./v2/trunk"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Routes + * + * @param domain - The Twilio (Twilio.Routes) domain + */ + constructor(domain: RoutesBase) { + super(domain, "v2"); + } + + /** phoneNumbers - { Twilio.Routes.V2.PhoneNumberListInstance } resource */ + protected _phoneNumbers?: PhoneNumberListInstance; + /** sipDomains - { Twilio.Routes.V2.SipDomainListInstance } resource */ + protected _sipDomains?: SipDomainListInstance; + /** trunks - { Twilio.Routes.V2.TrunkListInstance } resource */ + protected _trunks?: TrunkListInstance; + + /** Getter for phoneNumbers resource */ + get phoneNumbers(): PhoneNumberListInstance { + this._phoneNumbers = this._phoneNumbers || PhoneNumberListInstance(this); + return this._phoneNumbers; + } + + /** Getter for sipDomains resource */ + get sipDomains(): SipDomainListInstance { + this._sipDomains = this._sipDomains || SipDomainListInstance(this); + return this._sipDomains; + } + + /** Getter for trunks resource */ + get trunks(): TrunkListInstance { + this._trunks = this._trunks || TrunkListInstance(this); + return this._trunks; + } + +} diff --git a/rest/routes/V3.ts b/rest/routes/V3.ts new file mode 100644 index 000000000..ddf2b91ce --- /dev/null +++ b/rest/routes/V3.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Routes + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import RoutesBase from "../RoutesBase"; +import Version from "../../base/Version"; +import { PhoneNumberListInstance } from "./v3/phoneNumber"; + +export default class V3 extends Version { + /** + * Initialize the V3 version of Routes + * + * @param domain - The Twilio (Twilio.Routes) domain + */ + constructor(domain: RoutesBase) { + super(domain, "v3"); + } + + /** phoneNumbers - { Twilio.Routes.V3.PhoneNumberListInstance } resource */ + protected _phoneNumbers?: PhoneNumberListInstance; + + /** Getter for phoneNumbers resource */ + get phoneNumbers(): PhoneNumberListInstance { + this._phoneNumbers = this._phoneNumbers || PhoneNumberListInstance(this); + return this._phoneNumbers; + } + +} diff --git a/rest/routes/v2/phoneNumber.ts b/rest/routes/v2/phoneNumber.ts new file mode 100644 index 000000000..5ffcffc95 --- /dev/null +++ b/rest/routes/v2/phoneNumber.ts @@ -0,0 +1,450 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Routes + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a PhoneNumberInstance + */ +export interface PhoneNumberContextUpdateOptions { + /** The Inbound Processing Region used for this phone number for voice */ + "voiceRegion"?: string; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; +} + +export interface PhoneNumberContext { + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + + /** + * Update a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Update a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PhoneNumberContextSolution { + "phoneNumber": string; +} + +export class PhoneNumberContextImpl implements PhoneNumberContext { + protected _solution: PhoneNumberContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, phoneNumber: string) { + if (!isValidPathParam(phoneNumber)) { + throw new Error('Parameter \'phoneNumber\' is not valid.'); + } + + this._solution = { phoneNumber, }; + this._uri = `/PhoneNumbers/${phoneNumber}`; + } + + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: PhoneNumberContextUpdateOptions | ((error: Error | null, item?: PhoneNumberInstance) => any),callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["voiceRegion"] !== undefined) + data["VoiceRegion"] = params["voiceRegion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: PhoneNumberContextUpdateOptions | ((error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["voiceRegion"] !== undefined) + data["VoiceRegion"] = params["voiceRegion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PhoneNumberPayload extends PhoneNumberResource {} + +interface PhoneNumberResource { + phone_number: string; + url: string; + sid: string; + account_sid: string; + friendly_name: string; + voice_region: string; + date_created: Date; + date_updated: Date; +} + +export class PhoneNumberInstance { + protected _solution: PhoneNumberContextSolution; + protected _context?: PhoneNumberContext; + + constructor(protected _version: V2, payload: PhoneNumberResource, phoneNumber?: string) { + + this.phoneNumber = (payload.phone_number); + this.url = (payload.url); + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.voiceRegion = (payload.voice_region); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { phoneNumber: phoneNumber, }; + } + + /** + * The phone number in E.164 format + */ + phoneNumber: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * A 34 character string that uniquely identifies the Inbound Processing Region assignments for this phone number. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * A human readable description of the Inbound Processing Region assignments for this phone number, up to 64 characters. + */ + friendlyName: string; + /** + * The Inbound Processing Region used for this phone number for voice. + */ + voiceRegion: string; + /** + * The date that this phone number was assigned an Inbound Processing Region, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that the Inbound Processing Region was updated for this phone number, given in ISO 8601 format. + */ + dateUpdated: Date; + + private get _proxy(): PhoneNumberContext { + this._context = this._context || new PhoneNumberContextImpl(this._version, this._solution.phoneNumber); + return this._context; + } + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Update a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + update(params?: any, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + phoneNumber: this.phoneNumber, + url: this.url, + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + voiceRegion: this.voiceRegion, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PhoneNumberSolution { +} + +export interface PhoneNumberListInstance { + _version: V2; + _solution: PhoneNumberSolution; + _uri: string; + + (phoneNumber: string, ): PhoneNumberContext; + get(phoneNumber: string, ): PhoneNumberContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PhoneNumberListInstance(version: V2): PhoneNumberListInstance { + const instance = ((phoneNumber, ) => instance.get(phoneNumber, )) as PhoneNumberListInstance; + + instance.get = function get(phoneNumber, ): PhoneNumberContext { + return new PhoneNumberContextImpl(version, phoneNumber); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/routes/v2/sipDomain.ts b/rest/routes/v2/sipDomain.ts new file mode 100644 index 000000000..1bb3c5f5e --- /dev/null +++ b/rest/routes/v2/sipDomain.ts @@ -0,0 +1,426 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Routes + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a SipDomainInstance + */ +export interface SipDomainContextUpdateOptions { + /** */ + "voiceRegion"?: string; + /** */ + "friendlyName"?: string; +} + +export interface SipDomainContext { + + /** + * Fetch a SipDomainInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance + */ + fetch(callback?: (error: Error | null, item?: SipDomainInstance) => any): Promise<SipDomainInstance> + + /** + * Fetch a SipDomainInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SipDomainInstance>) => any): Promise<ApiResponse<SipDomainInstance>> + + /** + * Update a SipDomainInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance + */ + update(callback?: (error: Error | null, item?: SipDomainInstance) => any): Promise<SipDomainInstance>; + /** + * Update a SipDomainInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance + */ + update(params: SipDomainContextUpdateOptions, callback?: (error: Error | null, item?: SipDomainInstance) => any): Promise<SipDomainInstance>; + + /** + * Update a SipDomainInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SipDomainInstance>) => any): Promise<ApiResponse<SipDomainInstance>>; + /** + * Update a SipDomainInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance with HTTP metadata + */ + updateWithHttpInfo(params: SipDomainContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SipDomainInstance>) => any): Promise<ApiResponse<SipDomainInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SipDomainContextSolution { + "sipDomain": string; +} + +export class SipDomainContextImpl implements SipDomainContext { + protected _solution: SipDomainContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sipDomain: string) { + if (!isValidPathParam(sipDomain)) { + throw new Error('Parameter \'sipDomain\' is not valid.'); + } + + this._solution = { sipDomain, }; + this._uri = `/SipDomains/${sipDomain}`; + } + + fetch(callback?: (error: Error | null, item?: SipDomainInstance) => any): Promise<SipDomainInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SipDomainInstance(operationVersion, payload, instance._solution.sipDomain)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SipDomainInstance>) => any): Promise<ApiResponse<SipDomainInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SipDomainResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SipDomainInstance> => ({ + ...response, + body: new SipDomainInstance(operationVersion, response.body, instance._solution.sipDomain) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SipDomainContextUpdateOptions | ((error: Error | null, item?: SipDomainInstance) => any),callback?: (error: Error | null, item?: SipDomainInstance) => any): Promise<SipDomainInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["voiceRegion"] !== undefined) + data["VoiceRegion"] = params["voiceRegion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SipDomainInstance(operationVersion, payload, instance._solution.sipDomain)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SipDomainContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SipDomainInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SipDomainInstance>) => any): Promise<ApiResponse<SipDomainInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["voiceRegion"] !== undefined) + data["VoiceRegion"] = params["voiceRegion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SipDomainResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SipDomainInstance> => ({ + ...response, + body: new SipDomainInstance(operationVersion, response.body, instance._solution.sipDomain) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SipDomainPayload extends SipDomainResource {} + +interface SipDomainResource { + sip_domain: string; + url: string; + sid: string; + account_sid: string; + friendly_name: string; + voice_region: string; + date_created: Date; + date_updated: Date; +} + +export class SipDomainInstance { + protected _solution: SipDomainContextSolution; + protected _context?: SipDomainContext; + + constructor(protected _version: V2, payload: SipDomainResource, sipDomain?: string) { + + this.sipDomain = (payload.sip_domain); + this.url = (payload.url); + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.voiceRegion = (payload.voice_region); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { sipDomain: sipDomain, }; + } + + sipDomain: string; + url: string; + sid: string; + accountSid: string; + friendlyName: string; + voiceRegion: string; + dateCreated: Date; + dateUpdated: Date; + + private get _proxy(): SipDomainContext { + this._context = this._context || new SipDomainContextImpl(this._version, this._solution.sipDomain); + return this._context; + } + + /** + * Fetch a SipDomainInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance + */ + fetch(callback?: (error: Error | null, item?: SipDomainInstance) => any): Promise<SipDomainInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SipDomainInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SipDomainInstance>) => any): Promise<ApiResponse<SipDomainInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SipDomainInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance + */ + update(callback?: (error: Error | null, item?: SipDomainInstance) => any): Promise<SipDomainInstance>; + /** + * Update a SipDomainInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance + */ + update(params: SipDomainContextUpdateOptions, callback?: (error: Error | null, item?: SipDomainInstance) => any): Promise<SipDomainInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SipDomainInstance) => any): Promise<SipDomainInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SipDomainInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SipDomainInstance>) => any): Promise<ApiResponse<SipDomainInstance>>; + /** + * Update a SipDomainInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SipDomainInstance with HTTP metadata + */ + updateWithHttpInfo(params: SipDomainContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SipDomainInstance>) => any): Promise<ApiResponse<SipDomainInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SipDomainInstance>) => any): Promise<ApiResponse<SipDomainInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sipDomain: this.sipDomain, + url: this.url, + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + voiceRegion: this.voiceRegion, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SipDomainSolution { +} + +export interface SipDomainListInstance { + _version: V2; + _solution: SipDomainSolution; + _uri: string; + + (sipDomain: string, ): SipDomainContext; + get(sipDomain: string, ): SipDomainContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SipDomainListInstance(version: V2): SipDomainListInstance { + const instance = ((sipDomain, ) => instance.get(sipDomain, )) as SipDomainListInstance; + + instance.get = function get(sipDomain, ): SipDomainContext { + return new SipDomainContextImpl(version, sipDomain); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/routes/v2/trunk.ts b/rest/routes/v2/trunk.ts new file mode 100644 index 000000000..2b245ff1b --- /dev/null +++ b/rest/routes/v2/trunk.ts @@ -0,0 +1,450 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Routes + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a TrunkInstance + */ +export interface TrunkContextUpdateOptions { + /** The Inbound Processing Region used for this SIP Trunk for voice */ + "voiceRegion"?: string; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; +} + +export interface TrunkContext { + + /** + * Fetch a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + fetch(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance> + + /** + * Fetch a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> + + /** + * Update a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + update(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance>; + /** + * Update a TrunkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + update(params: TrunkContextUpdateOptions, callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance>; + + /** + * Update a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>>; + /** + * Update a TrunkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + updateWithHttpInfo(params: TrunkContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TrunkContextSolution { + "sipTrunkDomain": string; +} + +export class TrunkContextImpl implements TrunkContext { + protected _solution: TrunkContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sipTrunkDomain: string) { + if (!isValidPathParam(sipTrunkDomain)) { + throw new Error('Parameter \'sipTrunkDomain\' is not valid.'); + } + + this._solution = { sipTrunkDomain, }; + this._uri = `/Trunks/${sipTrunkDomain}`; + } + + fetch(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TrunkInstance(operationVersion, payload, instance._solution.sipTrunkDomain)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TrunkResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TrunkInstance> => ({ + ...response, + body: new TrunkInstance(operationVersion, response.body, instance._solution.sipTrunkDomain) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: TrunkContextUpdateOptions | ((error: Error | null, item?: TrunkInstance) => any),callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["voiceRegion"] !== undefined) + data["VoiceRegion"] = params["voiceRegion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TrunkInstance(operationVersion, payload, instance._solution.sipTrunkDomain)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: TrunkContextUpdateOptions | ((error: Error | null, item?: ApiResponse<TrunkInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["voiceRegion"] !== undefined) + data["VoiceRegion"] = params["voiceRegion"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<TrunkResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TrunkInstance> => ({ + ...response, + body: new TrunkInstance(operationVersion, response.body, instance._solution.sipTrunkDomain) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TrunkPayload extends TrunkResource {} + +interface TrunkResource { + sip_trunk_domain: string; + url: string; + sid: string; + account_sid: string; + friendly_name: string; + voice_region: string; + date_created: Date; + date_updated: Date; +} + +export class TrunkInstance { + protected _solution: TrunkContextSolution; + protected _context?: TrunkContext; + + constructor(protected _version: V2, payload: TrunkResource, sipTrunkDomain?: string) { + + this.sipTrunkDomain = (payload.sip_trunk_domain); + this.url = (payload.url); + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.voiceRegion = (payload.voice_region); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + this._solution = { sipTrunkDomain: sipTrunkDomain, }; + } + + /** + * The absolute URL of the SIP Trunk + */ + sipTrunkDomain: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * A 34 character string that uniquely identifies the Inbound Processing Region assignments for this SIP Trunk. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * A human readable description of the Inbound Processing Region assignments for this SIP Trunk, up to 64 characters. + */ + friendlyName: string; + /** + * The Inbound Processing Region used for this SIP Trunk for voice. + */ + voiceRegion: string; + /** + * The date that this SIP Trunk was assigned an Inbound Processing Region, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that the Inbound Processing Region was updated for this SIP Trunk, given in ISO 8601 format. + */ + dateUpdated: Date; + + private get _proxy(): TrunkContext { + this._context = this._context || new TrunkContextImpl(this._version, this._solution.sipTrunkDomain); + return this._context; + } + + /** + * Fetch a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + fetch(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + update(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance>; + /** + * Update a TrunkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + update(params: TrunkContextUpdateOptions, callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance>; + + update(params?: any, callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>>; + /** + * Update a TrunkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + updateWithHttpInfo(params: TrunkContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sipTrunkDomain: this.sipTrunkDomain, + url: this.url, + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + voiceRegion: this.voiceRegion, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TrunkSolution { +} + +export interface TrunkListInstance { + _version: V2; + _solution: TrunkSolution; + _uri: string; + + (sipTrunkDomain: string, ): TrunkContext; + get(sipTrunkDomain: string, ): TrunkContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TrunkListInstance(version: V2): TrunkListInstance { + const instance = ((sipTrunkDomain, ) => instance.get(sipTrunkDomain, )) as TrunkListInstance; + + instance.get = function get(sipTrunkDomain, ): TrunkContext { + return new TrunkContextImpl(version, sipTrunkDomain); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/routes/v3/phoneNumber.ts b/rest/routes/v3/phoneNumber.ts new file mode 100644 index 000000000..bafff9fa8 --- /dev/null +++ b/rest/routes/v3/phoneNumber.ts @@ -0,0 +1,456 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Routes + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a PhoneNumberInstance + */ +export interface PhoneNumberContextUpdateOptions { + /** The Inbound Processing Region used for this phone number for voice */ + "voiceRegion"?: string; + /** The Inbound Processing Region used for this phone number for messaging */ + "messagingRegion"?: string; + /** A human readable description of this resource, up to 64 characters. */ + "friendlyName"?: string; +} + +export interface PhoneNumberContext { + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + + /** + * Update a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Update a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PhoneNumberContextSolution { + "phoneNumber": string; +} + +export class PhoneNumberContextImpl implements PhoneNumberContext { + protected _solution: PhoneNumberContextSolution; + protected _uri: string; + + + constructor(protected _version: V3, phoneNumber: string) { + if (!isValidPathParam(phoneNumber)) { + throw new Error('Parameter \'phoneNumber\' is not valid.'); + } + + this._solution = { phoneNumber, }; + this._uri = `/PhoneNumbers/${phoneNumber}`; + } + + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: PhoneNumberContextUpdateOptions | ((error: Error | null, item?: PhoneNumberInstance) => any),callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["voiceRegion"] !== undefined) + data["voiceRegion"] = params["voiceRegion"]; + if (params["messagingRegion"] !== undefined) + data["messagingRegion"] = params["messagingRegion"]; + if (params["friendlyName"] !== undefined) + data["friendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: PhoneNumberContextUpdateOptions | ((error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["voiceRegion"] !== undefined) + data["voiceRegion"] = params["voiceRegion"]; + if (params["messagingRegion"] !== undefined) + data["messagingRegion"] = params["messagingRegion"]; + if (params["friendlyName"] !== undefined) + data["friendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + + +interface PhoneNumberResource { + phoneNumber: string; + url: string; + accountSid: string; + friendlyName: string; + voiceRegion: string; + messagingRegion: string; + dateCreated: Date; + dateUpdated: Date; +} + +export class PhoneNumberInstance { + protected _solution: PhoneNumberContextSolution; + protected _context?: PhoneNumberContext; + + constructor(protected _version: V3, _payload: PhoneNumberResource, phoneNumber?: string) { + const payload = _payload; + this.phoneNumber = (payload.phoneNumber); + this.url = (payload.url); + this.accountSid = (payload.accountSid); + this.friendlyName = (payload.friendlyName); + this.voiceRegion = (payload.voiceRegion); + this.messagingRegion = (payload.messagingRegion); + this.dateCreated = deserialize.iso8601DateTime(payload.dateCreated); + this.dateUpdated = deserialize.iso8601DateTime(payload.dateUpdated); + + this._solution = { phoneNumber: phoneNumber, }; + } + + /** + * The phone number in E.164 format + */ + phoneNumber: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * A human readable description of the Inbound Processing Region assignments for this phone number, up to 64 characters. + */ + friendlyName: string; + /** + * The Inbound Processing Region used for this phone number for voice. + */ + voiceRegion: string; + /** + * The Inbound Processing Region used for this phone number for messaging. + */ + messagingRegion: string; + /** + * The date that this phone number was assigned an Inbound Processing Region, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that the Inbound Processing Region was updated for this phone number, given in ISO 8601 format. + */ + dateUpdated: Date; + + private get _proxy(): PhoneNumberContext { + this._context = this._context || new PhoneNumberContextImpl(this._version, this._solution.phoneNumber); + return this._context; + } + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + /** + * Update a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + update(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + update(params?: any, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + /** + * Update a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + updateWithHttpInfo(params: PhoneNumberContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + phoneNumber: this.phoneNumber, + url: this.url, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + voiceRegion: this.voiceRegion, + messagingRegion: this.messagingRegion, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PhoneNumberSolution { +} + +export interface PhoneNumberListInstance { + _version: V3; + _solution: PhoneNumberSolution; + _uri: string; + + (phoneNumber: string, ): PhoneNumberContext; + get(phoneNumber: string, ): PhoneNumberContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PhoneNumberListInstance(version: V3): PhoneNumberListInstance { + const instance = ((phoneNumber, ) => instance.get(phoneNumber, )) as PhoneNumberListInstance; + + instance.get = function get(phoneNumber, ): PhoneNumberContext { + return new PhoneNumberContextImpl(version, phoneNumber); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/serverless/V1.ts b/rest/serverless/V1.ts new file mode 100644 index 000000000..042f46408 --- /dev/null +++ b/rest/serverless/V1.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import ServerlessBase from "../ServerlessBase"; +import Version from "../../base/Version"; +import { ServiceListInstance } from "./v1/service"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Serverless + * + * @param domain - The Twilio (Twilio.Serverless) domain + */ + constructor(domain: ServerlessBase) { + super(domain, "v1"); + } + + /** services - { Twilio.Serverless.V1.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + +} diff --git a/rest/serverless/v1/service.ts b/rest/serverless/v1/service.ts new file mode 100644 index 000000000..25b546299 --- /dev/null +++ b/rest/serverless/v1/service.ts @@ -0,0 +1,1022 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { AssetListInstance } from "./service/asset"; +import { BuildListInstance } from "./service/build"; +import { EnvironmentListInstance } from "./service/environment"; +import { FunctionListInstance } from "./service/function"; + + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** Whether to inject Account credentials into a function invocation context. */ + "includeCredentials"?: boolean; + /** A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. */ + "friendlyName"?: string; + /** Whether the Service resource\\\'s properties and subresources can be edited via the UI. The default value is `false`. */ + "uiEditable"?: boolean; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. */ + "uniqueName": string; + /** A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. */ + "friendlyName": string; + /** Whether to inject Account credentials into a function invocation context. The default value is `true`. */ + "includeCredentials"?: boolean; + /** Whether the Service\\\'s properties and subresources can be edited via the UI. The default value is `false`. */ + "uiEditable"?: boolean; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + assets: AssetListInstance; + builds: BuildListInstance; + environments: EnvironmentListInstance; + functions: FunctionListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _assets?: AssetListInstance; + protected _builds?: BuildListInstance; + protected _environments?: EnvironmentListInstance; + protected _functions?: FunctionListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get assets(): AssetListInstance { + this._assets = this._assets || AssetListInstance(this._version, this._solution.sid); + return this._assets; + } + + get builds(): BuildListInstance { + this._builds = this._builds || BuildListInstance(this._version, this._solution.sid); + return this._builds; + } + + get environments(): EnvironmentListInstance { + this._environments = this._environments || EnvironmentListInstance(this._version, this._solution.sid); + return this._environments; + } + + get functions(): FunctionListInstance { + this._functions = this._functions || FunctionListInstance(this._version, this._solution.sid); + return this._functions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["includeCredentials"] !== undefined) + data["IncludeCredentials"] = serialize.bool(params["includeCredentials"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uiEditable"] !== undefined) + data["UiEditable"] = serialize.bool(params["uiEditable"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ServiceInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["includeCredentials"] !== undefined) + data["IncludeCredentials"] = serialize.bool(params["includeCredentials"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["uiEditable"] !== undefined) + data["UiEditable"] = serialize.bool(params["uiEditable"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + sid: string; + account_sid: string; + friendly_name: string; + unique_name: string; + include_credentials: boolean; + ui_editable: boolean; + domain_base: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V1, payload: ServiceResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.uniqueName = (payload.unique_name); + this.includeCredentials = (payload.include_credentials); + this.uiEditable = (payload.ui_editable); + this.domainBase = (payload.domain_base); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Service resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the Service resource. + */ + friendlyName: string; + /** + * A user-defined string that uniquely identifies the Service resource. It can be used in place of the Service resource\'s `sid` in the URL to address the Service resource. + */ + uniqueName: string; + /** + * Whether to inject Account credentials into a function invocation context. + */ + includeCredentials: boolean; + /** + * Whether the Service resource\'s properties and subresources can be edited via the UI. + */ + uiEditable: boolean; + /** + * The base domain name for this Service, which is a combination of the unique name and a randomly generated string. + */ + domainBase: string; + /** + * The date and time in GMT when the Service resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Service resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Service resource. + */ + url: string; + /** + * The URLs of the Service\'s nested resources. + */ + links: Record<string, string>; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the assets. + */ + assets(): AssetListInstance { + return this._proxy.assets; + } + + /** + * Access the builds. + */ + builds(): BuildListInstance { + return this._proxy.builds; + } + + /** + * Access the environments. + */ + environments(): EnvironmentListInstance { + return this._proxy.environments; + } + + /** + * Access the functions. + */ + functions(): FunctionListInstance { + return this._proxy.functions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + uniqueName: this.uniqueName, + includeCredentials: this.includeCredentials, + uiEditable: this.uiEditable, + domainBase: this.domainBase, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V1; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V1): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ServiceInstance) => any): Promise<ServiceInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + + data["FriendlyName"] = params["friendlyName"]; + if (params["includeCredentials"] !== undefined) + data["IncludeCredentials"] = serialize.bool(params["includeCredentials"]); + if (params["uiEditable"] !== undefined) + data["UiEditable"] = serialize.bool(params["uiEditable"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + + data["FriendlyName"] = params["friendlyName"]; + if (params["includeCredentials"] !== undefined) + data["IncludeCredentials"] = serialize.bool(params["includeCredentials"]); + if (params["uiEditable"] !== undefined) + data["UiEditable"] = serialize.bool(params["uiEditable"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse<ServicePage>) => any), callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page<V1, ServicePayload, ServiceResource, ServiceInstance> { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/serverless/v1/service/asset.ts b/rest/serverless/v1/service/asset.ts new file mode 100644 index 000000000..5f9c14b5b --- /dev/null +++ b/rest/serverless/v1/service/asset.ts @@ -0,0 +1,899 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { AssetVersionListInstance } from "./asset/assetVersion"; + + + + + +/** + * Options to pass to update a AssetInstance + */ +export interface AssetContextUpdateOptions { + /** A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. */ + "friendlyName": string; +} + +/** + * Options to pass to create a AssetInstance + */ +export interface AssetListInstanceCreateOptions { + /** A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. */ + "friendlyName": string; +} + +/** + * Options to pass to each + */ +export interface AssetListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AssetInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AssetListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AssetListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AssetContext { + assetVersions: AssetVersionListInstance; + + /** + * Remove a AssetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a AssetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a AssetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetInstance + */ + fetch(callback?: (error: Error | null, item?: AssetInstance) => any): Promise<AssetInstance> + + /** + * Fetch a AssetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AssetInstance>) => any): Promise<ApiResponse<AssetInstance>> + + /** + * Update a AssetInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetInstance + */ + update(params: AssetContextUpdateOptions, callback?: (error: Error | null, item?: AssetInstance) => any): Promise<AssetInstance>; + + /** + * Update a AssetInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetInstance with HTTP metadata + */ + updateWithHttpInfo(params: AssetContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<AssetInstance>) => any): Promise<ApiResponse<AssetInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AssetContextSolution { + "serviceSid": string; + "sid": string; +} + +export class AssetContextImpl implements AssetContext { + protected _solution: AssetContextSolution; + protected _uri: string; + + protected _assetVersions?: AssetVersionListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Assets/${sid}`; + } + + get assetVersions(): AssetVersionListInstance { + this._assetVersions = this._assetVersions || AssetVersionListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._assetVersions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AssetInstance) => any): Promise<AssetInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AssetInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AssetInstance>) => any): Promise<ApiResponse<AssetInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AssetResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AssetInstance> => ({ + ...response, + body: new AssetInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: AssetContextUpdateOptions,callback?: (error: Error | null, item?: AssetInstance) => any): Promise<AssetInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AssetInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: AssetContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<AssetInstance>) => any): Promise<ApiResponse<AssetInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<AssetResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<AssetInstance> => ({ + ...response, + body: new AssetInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AssetPayload extends TwilioResponsePayload { + assets: AssetResource[]; +} + +interface AssetResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class AssetInstance { + protected _solution: AssetContextSolution; + protected _context?: AssetContext; + + constructor(protected _version: V1, payload: AssetResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Asset resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Asset resource. + */ + accountSid: string; + /** + * The SID of the Service that the Asset resource is associated with. + */ + serviceSid: string; + /** + * The string that you assigned to describe the Asset resource. It can be a maximum of 255 characters. + */ + friendlyName: string; + /** + * The date and time in GMT when the Asset resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Asset resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Asset resource. + */ + url: string; + /** + * The URLs of the Asset resource\'s nested resources. + */ + links: Record<string, string>; + + private get _proxy(): AssetContext { + this._context = this._context || new AssetContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a AssetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AssetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AssetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetInstance + */ + fetch(callback?: (error: Error | null, item?: AssetInstance) => any): Promise<AssetInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AssetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AssetInstance>) => any): Promise<ApiResponse<AssetInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a AssetInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetInstance + */ + update(params: AssetContextUpdateOptions, callback?: (error: Error | null, item?: AssetInstance) => any): Promise<AssetInstance>; + + update(params?: any, callback?: (error: Error | null, item?: AssetInstance) => any): Promise<AssetInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a AssetInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetInstance with HTTP metadata + */ + updateWithHttpInfo(params: AssetContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<AssetInstance>) => any): Promise<ApiResponse<AssetInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<AssetInstance>) => any): Promise<ApiResponse<AssetInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the assetVersions. + */ + assetVersions(): AssetVersionListInstance { + return this._proxy.assetVersions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AssetSolution { + serviceSid: string; +} + +export interface AssetListInstance { + _version: V1; + _solution: AssetSolution; + _uri: string; + + (sid: string, ): AssetContext; + get(sid: string, ): AssetContext; + + + + + + + + + /** + * Create a AssetInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetInstance + */ + create(params: AssetListInstanceCreateOptions, callback?: (error: Error | null, item?: AssetInstance) => any): Promise<AssetInstance>; + + /** + * Create a AssetInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetInstance with HTTP metadata + */ + createWithHttpInfo(params: AssetListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<AssetInstance>) => any): Promise<ApiResponse<AssetInstance>>; + + + + + /** + * Streams AssetInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AssetInstance, done: (err?: Error) => void) => void): void; + each(params: AssetListInstanceEachOptions, callback?: (item: AssetInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AssetInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AssetInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AssetListInstanceEachOptions, callback?: (item: AssetInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AssetInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AssetPage) => any): Promise<AssetPage>; + /** + * Retrieve a single target page of AssetInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AssetPage>) => any): Promise<ApiResponse<AssetPage>>; + /** + * Lists AssetInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AssetInstance[]) => any): Promise<AssetInstance[]>; + list(params: AssetListInstanceOptions, callback?: (error: Error | null, items: AssetInstance[]) => any): Promise<AssetInstance[]>; + /** + * Lists AssetInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AssetInstance[]>) => any): Promise<ApiResponse<AssetInstance[]>>; + listWithHttpInfo(params: AssetListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AssetInstance[]>) => any): Promise<ApiResponse<AssetInstance[]>>; + /** + * Retrieve a single page of AssetInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AssetPage) => any): Promise<AssetPage>; + page(params: AssetListInstancePageOptions, callback?: (error: Error | null, items: AssetPage) => any): Promise<AssetPage>; + /** + * Retrieve a single page of AssetInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AssetPage>) => any): Promise<ApiResponse<AssetPage>>; + pageWithHttpInfo(params: AssetListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AssetPage>) => any): Promise<ApiResponse<AssetPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AssetListInstance(version: V1, serviceSid: string): AssetListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as AssetListInstance; + + instance.get = function get(sid, ): AssetContext { + return new AssetContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Assets`; + + instance.create = function create(params: AssetListInstanceCreateOptions, callback?: (error: Error | null, items: AssetInstance) => any): Promise<AssetInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AssetInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AssetListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<AssetInstance>) => any): Promise<ApiResponse<AssetInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<AssetResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<AssetInstance> => ({ + ...response, + body: new AssetInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: AssetListInstancePageOptions | ((error: Error | null, items: AssetPage) => any), callback?: (error: Error | null, items: AssetPage) => any): Promise<AssetPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AssetPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AssetPage) => any): Promise<AssetPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AssetPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AssetListInstancePageOptions | ((error: Error | null, items: ApiResponse<AssetPage>) => any), callback?: (error: Error | null, items: ApiResponse<AssetPage>) => any): Promise<ApiResponse<AssetPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AssetPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssetPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AssetPage>) => any): Promise<ApiResponse<AssetPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AssetPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssetPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AssetPage extends Page<V1, AssetPayload, AssetResource, AssetInstance> { +/** +* Initialize the AssetPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: AssetSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AssetInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AssetResource): AssetInstance { + + return new AssetInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/serverless/v1/service/asset/assetVersion.ts b/rest/serverless/v1/service/asset/assetVersion.ts new file mode 100644 index 000000000..50fdbfc2c --- /dev/null +++ b/rest/serverless/v1/service/asset/assetVersion.ts @@ -0,0 +1,589 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The access control that determines how the Asset Version resource can be accessed. Can be: `public`, `protected`, or `private`. + */ +export type AssetVersionVisibility = 'public'|'private'|'protected'; + + + +/** + * Options to pass to each + */ +export interface AssetVersionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: AssetVersionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface AssetVersionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface AssetVersionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface AssetVersionContext { + + /** + * Fetch a AssetVersionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetVersionInstance + */ + fetch(callback?: (error: Error | null, item?: AssetVersionInstance) => any): Promise<AssetVersionInstance> + + /** + * Fetch a AssetVersionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetVersionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AssetVersionInstance>) => any): Promise<ApiResponse<AssetVersionInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AssetVersionContextSolution { + "serviceSid": string; + "assetSid": string; + "sid": string; +} + +export class AssetVersionContextImpl implements AssetVersionContext { + protected _solution: AssetVersionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, assetSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(assetSid)) { + throw new Error('Parameter \'assetSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, assetSid, sid, }; + this._uri = `/Services/${serviceSid}/Assets/${assetSid}/Versions/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: AssetVersionInstance) => any): Promise<AssetVersionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AssetVersionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.assetSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AssetVersionInstance>) => any): Promise<ApiResponse<AssetVersionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AssetVersionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AssetVersionInstance> => ({ + ...response, + body: new AssetVersionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.assetSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AssetVersionPayload extends TwilioResponsePayload { + asset_versions: AssetVersionResource[]; +} + +interface AssetVersionResource { + sid: string; + account_sid: string; + service_sid: string; + asset_sid: string; + path: string; + visibility: AssetVersionVisibility; + date_created: Date; + url: string; +} + +export class AssetVersionInstance { + protected _solution: AssetVersionContextSolution; + protected _context?: AssetVersionContext; + + constructor(protected _version: V1, payload: AssetVersionResource, serviceSid: string, assetSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.assetSid = (payload.asset_sid); + this.path = (payload.path); + this.visibility = payload.visibility; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { serviceSid, assetSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Asset Version resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Asset Version resource. + */ + accountSid: string; + /** + * The SID of the Service that the Asset Version resource is associated with. + */ + serviceSid: string; + /** + * The SID of the Asset resource that is the parent of the Asset Version. + */ + assetSid: string; + /** + * The URL-friendly string by which the Asset Version can be referenced. It can be a maximum of 255 characters. All paths begin with a forward slash (\'/\'). If an Asset Version creation request is submitted with a path not containing a leading slash, the path will automatically be prepended with one. + */ + path: string; + visibility: AssetVersionVisibility; + /** + * The date and time in GMT when the Asset Version resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Asset Version resource. + */ + url: string; + + private get _proxy(): AssetVersionContext { + this._context = this._context || new AssetVersionContextImpl(this._version, this._solution.serviceSid, this._solution.assetSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a AssetVersionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetVersionInstance + */ + fetch(callback?: (error: Error | null, item?: AssetVersionInstance) => any): Promise<AssetVersionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AssetVersionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AssetVersionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AssetVersionInstance>) => any): Promise<ApiResponse<AssetVersionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + assetSid: this.assetSid, + path: this.path, + visibility: this.visibility, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AssetVersionSolution { + serviceSid: string; + assetSid: string; +} + +export interface AssetVersionListInstance { + _version: V1; + _solution: AssetVersionSolution; + _uri: string; + + (sid: string, ): AssetVersionContext; + get(sid: string, ): AssetVersionContext; + + + + + + /** + * Streams AssetVersionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetVersionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: AssetVersionInstance, done: (err?: Error) => void) => void): void; + each(params: AssetVersionListInstanceEachOptions, callback?: (item: AssetVersionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams AssetVersionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetVersionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: AssetVersionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: AssetVersionListInstanceEachOptions, callback?: (item: AssetVersionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of AssetVersionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: AssetVersionPage) => any): Promise<AssetVersionPage>; + /** + * Retrieve a single target page of AssetVersionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<AssetVersionPage>) => any): Promise<ApiResponse<AssetVersionPage>>; + /** + * Lists AssetVersionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetVersionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: AssetVersionInstance[]) => any): Promise<AssetVersionInstance[]>; + list(params: AssetVersionListInstanceOptions, callback?: (error: Error | null, items: AssetVersionInstance[]) => any): Promise<AssetVersionInstance[]>; + /** + * Lists AssetVersionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetVersionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AssetVersionInstance[]>) => any): Promise<ApiResponse<AssetVersionInstance[]>>; + listWithHttpInfo(params: AssetVersionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<AssetVersionInstance[]>) => any): Promise<ApiResponse<AssetVersionInstance[]>>; + /** + * Retrieve a single page of AssetVersionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetVersionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: AssetVersionPage) => any): Promise<AssetVersionPage>; + page(params: AssetVersionListInstancePageOptions, callback?: (error: Error | null, items: AssetVersionPage) => any): Promise<AssetVersionPage>; + /** + * Retrieve a single page of AssetVersionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { AssetVersionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<AssetVersionPage>) => any): Promise<ApiResponse<AssetVersionPage>>; + pageWithHttpInfo(params: AssetVersionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<AssetVersionPage>) => any): Promise<ApiResponse<AssetVersionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AssetVersionListInstance(version: V1, serviceSid: string, assetSid: string): AssetVersionListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(assetSid)) { + throw new Error('Parameter \'assetSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as AssetVersionListInstance; + + instance.get = function get(sid, ): AssetVersionContext { + return new AssetVersionContextImpl(version, serviceSid, assetSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, assetSid, }; + instance._uri = `/Services/${serviceSid}/Assets/${assetSid}/Versions`; + + instance.page = function page(params?: AssetVersionListInstancePageOptions | ((error: Error | null, items: AssetVersionPage) => any), callback?: (error: Error | null, items: AssetVersionPage) => any): Promise<AssetVersionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new AssetVersionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: AssetVersionPage) => any): Promise<AssetVersionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new AssetVersionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: AssetVersionListInstancePageOptions | ((error: Error | null, items: ApiResponse<AssetVersionPage>) => any), callback?: (error: Error | null, items: ApiResponse<AssetVersionPage>) => any): Promise<ApiResponse<AssetVersionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<AssetVersionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssetVersionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<AssetVersionPage>) => any): Promise<ApiResponse<AssetVersionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<AssetVersionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new AssetVersionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class AssetVersionPage extends Page<V1, AssetVersionPayload, AssetVersionResource, AssetVersionInstance> { +/** +* Initialize the AssetVersionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: AssetVersionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of AssetVersionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: AssetVersionResource): AssetVersionInstance { + + return new AssetVersionInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.assetSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/serverless/v1/service/build.ts b/rest/serverless/v1/service/build.ts new file mode 100644 index 000000000..9abfd1bc8 --- /dev/null +++ b/rest/serverless/v1/service/build.ts @@ -0,0 +1,829 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { BuildStatusListInstance } from "./build/buildStatus"; + + +/** + * The Runtime version that will be used to run the Build resource when it is deployed. + */ +export type BuildRuntime = 'node8'|'node10'|'node12'|'node14'|'node16'|'node18'|'node20'|'node22'|'node24'; + +/** + * The status of the Build. Can be: `building`, `completed`, or `failed`. + */ +export type BuildStatus = 'building'|'completed'|'failed'; + + + + +/** + * Options to pass to create a BuildInstance + */ +export interface BuildListInstanceCreateOptions { + /** The list of Asset Version resource SIDs to include in the Build. */ + "assetVersions"?: Array<string>; + /** The list of the Function Version resource SIDs to include in the Build. */ + "functionVersions"?: Array<string>; + /** A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. */ + "dependencies"?: string; + /** The Runtime version that will be used to run the Build resource when it is deployed. */ + "runtime"?: string; +} + +/** + * Options to pass to each + */ +export interface BuildListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BuildInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BuildListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BuildListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface BuildContext { + buildStatus: BuildStatusListInstance; + + /** + * Remove a BuildInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a BuildInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a BuildInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildInstance + */ + fetch(callback?: (error: Error | null, item?: BuildInstance) => any): Promise<BuildInstance> + + /** + * Fetch a BuildInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BuildInstance>) => any): Promise<ApiResponse<BuildInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BuildContextSolution { + "serviceSid": string; + "sid": string; +} + +export class BuildContextImpl implements BuildContext { + protected _solution: BuildContextSolution; + protected _uri: string; + + protected _buildStatus?: BuildStatusListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Builds/${sid}`; + } + + get buildStatus(): BuildStatusListInstance { + this._buildStatus = this._buildStatus || BuildStatusListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._buildStatus; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: BuildInstance) => any): Promise<BuildInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BuildInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BuildInstance>) => any): Promise<ApiResponse<BuildInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<BuildResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<BuildInstance> => ({ + ...response, + body: new BuildInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BuildPayload extends TwilioResponsePayload { + builds: BuildResource[]; +} + +interface BuildResource { + sid: string; + account_sid: string; + service_sid: string; + status: BuildStatus; + asset_versions: Array<any>; + function_versions: Array<any>; + dependencies: Array<any>; + runtime: BuildRuntime; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class BuildInstance { + protected _solution: BuildContextSolution; + protected _context?: BuildContext; + + constructor(protected _version: V1, payload: BuildResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.status = payload.status; + this.assetVersions = (payload.asset_versions); + this.functionVersions = (payload.function_versions); + this.dependencies = (payload.dependencies); + this.runtime = payload.runtime; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Build resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Build resource. + */ + accountSid: string; + /** + * The SID of the Service that the Build resource is associated with. + */ + serviceSid: string; + status: BuildStatus; + /** + * The list of Asset Version resource SIDs that are included in the Build. + */ + assetVersions: Array<any>; + /** + * The list of Function Version resource SIDs that are included in the Build. + */ + functionVersions: Array<any>; + /** + * A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + */ + dependencies: Array<any>; + runtime: BuildRuntime; + /** + * The date and time in GMT when the Build resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Build resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Build resource. + */ + url: string; + links: Record<string, string>; + + private get _proxy(): BuildContext { + this._context = this._context || new BuildContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a BuildInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a BuildInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a BuildInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildInstance + */ + fetch(callback?: (error: Error | null, item?: BuildInstance) => any): Promise<BuildInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BuildInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BuildInstance>) => any): Promise<ApiResponse<BuildInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the buildStatus. + */ + buildStatus(): BuildStatusListInstance { + return this._proxy.buildStatus; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + status: this.status, + assetVersions: this.assetVersions, + functionVersions: this.functionVersions, + dependencies: this.dependencies, + runtime: this.runtime, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BuildSolution { + serviceSid: string; +} + +export interface BuildListInstance { + _version: V1; + _solution: BuildSolution; + _uri: string; + + (sid: string, ): BuildContext; + get(sid: string, ): BuildContext; + + + + + + + /** + * Create a BuildInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildInstance + */ + create(callback?: (error: Error | null, item?: BuildInstance) => any): Promise<BuildInstance>; + /** + * Create a BuildInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildInstance + */ + create(params: BuildListInstanceCreateOptions, callback?: (error: Error | null, item?: BuildInstance) => any): Promise<BuildInstance>; + + /** + * Create a BuildInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BuildInstance>) => any): Promise<ApiResponse<BuildInstance>>; + /** + * Create a BuildInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildInstance with HTTP metadata + */ + createWithHttpInfo(params: BuildListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<BuildInstance>) => any): Promise<ApiResponse<BuildInstance>>; + + + + + /** + * Streams BuildInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BuildListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BuildInstance, done: (err?: Error) => void) => void): void; + each(params: BuildListInstanceEachOptions, callback?: (item: BuildInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BuildInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BuildListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BuildInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BuildListInstanceEachOptions, callback?: (item: BuildInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BuildInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BuildPage) => any): Promise<BuildPage>; + /** + * Retrieve a single target page of BuildInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<BuildPage>) => any): Promise<ApiResponse<BuildPage>>; + /** + * Lists BuildInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BuildListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BuildInstance[]) => any): Promise<BuildInstance[]>; + list(params: BuildListInstanceOptions, callback?: (error: Error | null, items: BuildInstance[]) => any): Promise<BuildInstance[]>; + /** + * Lists BuildInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BuildListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BuildInstance[]>) => any): Promise<ApiResponse<BuildInstance[]>>; + listWithHttpInfo(params: BuildListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<BuildInstance[]>) => any): Promise<ApiResponse<BuildInstance[]>>; + /** + * Retrieve a single page of BuildInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BuildListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BuildPage) => any): Promise<BuildPage>; + page(params: BuildListInstancePageOptions, callback?: (error: Error | null, items: BuildPage) => any): Promise<BuildPage>; + /** + * Retrieve a single page of BuildInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BuildListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BuildPage>) => any): Promise<ApiResponse<BuildPage>>; + pageWithHttpInfo(params: BuildListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<BuildPage>) => any): Promise<ApiResponse<BuildPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BuildListInstance(version: V1, serviceSid: string): BuildListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as BuildListInstance; + + instance.get = function get(sid, ): BuildContext { + return new BuildContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Builds`; + + instance.create = function create(params?: BuildListInstanceCreateOptions | ((error: Error | null, items: BuildInstance) => any), callback?: (error: Error | null, items: BuildInstance) => any): Promise<BuildInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["assetVersions"] !== undefined) + data["AssetVersions"] = serialize.map(params["assetVersions"], (e: string) => (e)); + if (params["functionVersions"] !== undefined) + data["FunctionVersions"] = serialize.map(params["functionVersions"], (e: string) => (e)); + if (params["dependencies"] !== undefined) + data["Dependencies"] = params["dependencies"]; + if (params["runtime"] !== undefined) + data["Runtime"] = params["runtime"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BuildInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: BuildListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<BuildInstance>) => any), callback?: (error: Error | null, items: ApiResponse<BuildInstance>) => any): Promise<ApiResponse<BuildInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["assetVersions"] !== undefined) + data["AssetVersions"] = serialize.map(params["assetVersions"], (e: string) => (e)); + if (params["functionVersions"] !== undefined) + data["FunctionVersions"] = serialize.map(params["functionVersions"], (e: string) => (e)); + if (params["dependencies"] !== undefined) + data["Dependencies"] = params["dependencies"]; + if (params["runtime"] !== undefined) + data["Runtime"] = params["runtime"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BuildResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BuildInstance> => ({ + ...response, + body: new BuildInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: BuildListInstancePageOptions | ((error: Error | null, items: BuildPage) => any), callback?: (error: Error | null, items: BuildPage) => any): Promise<BuildPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BuildPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BuildPage) => any): Promise<BuildPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BuildPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BuildListInstancePageOptions | ((error: Error | null, items: ApiResponse<BuildPage>) => any), callback?: (error: Error | null, items: ApiResponse<BuildPage>) => any): Promise<ApiResponse<BuildPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<BuildPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BuildPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<BuildPage>) => any): Promise<ApiResponse<BuildPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<BuildPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BuildPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class BuildPage extends Page<V1, BuildPayload, BuildResource, BuildInstance> { +/** +* Initialize the BuildPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: BuildSolution) { + super(version, response, solution); + } + + /** + * Build an instance of BuildInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BuildResource): BuildInstance { + + return new BuildInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/serverless/v1/service/build/buildStatus.ts b/rest/serverless/v1/service/build/buildStatus.ts new file mode 100644 index 000000000..a19ed0a7e --- /dev/null +++ b/rest/serverless/v1/service/build/buildStatus.ts @@ -0,0 +1,279 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The status of the Build. Can be: `building`, `completed`, or `failed`. + */ +export type BuildStatusStatus = 'building'|'completed'|'failed'; + + + +export interface BuildStatusContext { + + /** + * Fetch a BuildStatusInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildStatusInstance + */ + fetch(callback?: (error: Error | null, item?: BuildStatusInstance) => any): Promise<BuildStatusInstance> + + /** + * Fetch a BuildStatusInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildStatusInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BuildStatusInstance>) => any): Promise<ApiResponse<BuildStatusInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BuildStatusContextSolution { + "serviceSid": string; + "sid": string; +} + +export class BuildStatusContextImpl implements BuildStatusContext { + protected _solution: BuildStatusContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Builds/${sid}/Status`; + } + + fetch(callback?: (error: Error | null, item?: BuildStatusInstance) => any): Promise<BuildStatusInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BuildStatusInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BuildStatusInstance>) => any): Promise<ApiResponse<BuildStatusInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<BuildStatusResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<BuildStatusInstance> => ({ + ...response, + body: new BuildStatusInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BuildStatusPayload extends BuildStatusResource {} + +interface BuildStatusResource { + sid: string; + account_sid: string; + service_sid: string; + status: BuildStatusStatus; + url: string; +} + +export class BuildStatusInstance { + protected _solution: BuildStatusContextSolution; + protected _context?: BuildStatusContext; + + constructor(protected _version: V1, payload: BuildStatusResource, serviceSid: string, sid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.status = payload.status; + this.url = (payload.url); + + this._solution = { serviceSid, sid, }; + } + + /** + * The unique string that we created to identify the Build resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Build resource. + */ + accountSid: string; + /** + * The SID of the Service that the Build resource is associated with. + */ + serviceSid: string; + status: BuildStatusStatus; + /** + * The absolute URL of the Build Status resource. + */ + url: string; + + private get _proxy(): BuildStatusContext { + this._context = this._context || new BuildStatusContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a BuildStatusInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildStatusInstance + */ + fetch(callback?: (error: Error | null, item?: BuildStatusInstance) => any): Promise<BuildStatusInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BuildStatusInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BuildStatusInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BuildStatusInstance>) => any): Promise<ApiResponse<BuildStatusInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + status: this.status, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BuildStatusSolution { + serviceSid: string; + sid: string; +} + +export interface BuildStatusListInstance { + _version: V1; + _solution: BuildStatusSolution; + _uri: string; + + (): BuildStatusContext; + get(): BuildStatusContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BuildStatusListInstance(version: V1, serviceSid: string, sid: string): BuildStatusListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + const instance = (() => instance.get()) as BuildStatusListInstance; + + instance.get = function get(): BuildStatusContext { + return new BuildStatusContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, sid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/serverless/v1/service/environment.ts b/rest/serverless/v1/service/environment.ts new file mode 100644 index 000000000..1e6c72417 --- /dev/null +++ b/rest/serverless/v1/service/environment.ts @@ -0,0 +1,825 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { DeploymentListInstance } from "./environment/deployment"; +import { LogListInstance } from "./environment/log"; +import { VariableListInstance } from "./environment/variable"; + + + + + +/** + * Options to pass to create a EnvironmentInstance + */ +export interface EnvironmentListInstanceCreateOptions { + /** A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. */ + "uniqueName": string; + /** A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. */ + "domainSuffix"?: string; +} + +/** + * Options to pass to each + */ +export interface EnvironmentListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EnvironmentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EnvironmentListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EnvironmentListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EnvironmentContext { + deployments: DeploymentListInstance; + logs: LogListInstance; + variables: VariableListInstance; + + /** + * Remove a EnvironmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a EnvironmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a EnvironmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EnvironmentInstance + */ + fetch(callback?: (error: Error | null, item?: EnvironmentInstance) => any): Promise<EnvironmentInstance> + + /** + * Fetch a EnvironmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EnvironmentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EnvironmentInstance>) => any): Promise<ApiResponse<EnvironmentInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EnvironmentContextSolution { + "serviceSid": string; + "sid": string; +} + +export class EnvironmentContextImpl implements EnvironmentContext { + protected _solution: EnvironmentContextSolution; + protected _uri: string; + + protected _deployments?: DeploymentListInstance; + protected _logs?: LogListInstance; + protected _variables?: VariableListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Environments/${sid}`; + } + + get deployments(): DeploymentListInstance { + this._deployments = this._deployments || DeploymentListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._deployments; + } + + get logs(): LogListInstance { + this._logs = this._logs || LogListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._logs; + } + + get variables(): VariableListInstance { + this._variables = this._variables || VariableListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._variables; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: EnvironmentInstance) => any): Promise<EnvironmentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EnvironmentInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EnvironmentInstance>) => any): Promise<ApiResponse<EnvironmentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EnvironmentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EnvironmentInstance> => ({ + ...response, + body: new EnvironmentInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EnvironmentPayload extends TwilioResponsePayload { + environments: EnvironmentResource[]; +} + +interface EnvironmentResource { + sid: string; + account_sid: string; + service_sid: string; + build_sid: string; + unique_name: string; + domain_suffix: string; + domain_name: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class EnvironmentInstance { + protected _solution: EnvironmentContextSolution; + protected _context?: EnvironmentContext; + + constructor(protected _version: V1, payload: EnvironmentResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.buildSid = (payload.build_sid); + this.uniqueName = (payload.unique_name); + this.domainSuffix = (payload.domain_suffix); + this.domainName = (payload.domain_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Environment resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Environment resource. + */ + accountSid: string; + /** + * The SID of the Service that the Environment resource is associated with. + */ + serviceSid: string; + /** + * The SID of the build deployed in the environment. + */ + buildSid: string; + /** + * A user-defined string that uniquely identifies the Environment resource. + */ + uniqueName: string; + /** + * A URL-friendly name that represents the environment and forms part of the domain name. + */ + domainSuffix: string; + /** + * The domain name for all Functions and Assets deployed in the Environment, using the Service unique name, a randomly-generated Service suffix, and an optional Environment domain suffix. + */ + domainName: string; + /** + * The date and time in GMT when the Environment resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Environment resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Environment resource. + */ + url: string; + /** + * The URLs of the Environment resource\'s nested resources. + */ + links: Record<string, string>; + + private get _proxy(): EnvironmentContext { + this._context = this._context || new EnvironmentContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a EnvironmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a EnvironmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a EnvironmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EnvironmentInstance + */ + fetch(callback?: (error: Error | null, item?: EnvironmentInstance) => any): Promise<EnvironmentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EnvironmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EnvironmentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EnvironmentInstance>) => any): Promise<ApiResponse<EnvironmentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the deployments. + */ + deployments(): DeploymentListInstance { + return this._proxy.deployments; + } + + /** + * Access the logs. + */ + logs(): LogListInstance { + return this._proxy.logs; + } + + /** + * Access the variables. + */ + variables(): VariableListInstance { + return this._proxy.variables; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + buildSid: this.buildSid, + uniqueName: this.uniqueName, + domainSuffix: this.domainSuffix, + domainName: this.domainName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EnvironmentSolution { + serviceSid: string; +} + +export interface EnvironmentListInstance { + _version: V1; + _solution: EnvironmentSolution; + _uri: string; + + (sid: string, ): EnvironmentContext; + get(sid: string, ): EnvironmentContext; + + + + + + + /** + * Create a EnvironmentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EnvironmentInstance + */ + create(params: EnvironmentListInstanceCreateOptions, callback?: (error: Error | null, item?: EnvironmentInstance) => any): Promise<EnvironmentInstance>; + + /** + * Create a EnvironmentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EnvironmentInstance with HTTP metadata + */ + createWithHttpInfo(params: EnvironmentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<EnvironmentInstance>) => any): Promise<ApiResponse<EnvironmentInstance>>; + + + + + /** + * Streams EnvironmentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EnvironmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EnvironmentInstance, done: (err?: Error) => void) => void): void; + each(params: EnvironmentListInstanceEachOptions, callback?: (item: EnvironmentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EnvironmentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EnvironmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EnvironmentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EnvironmentListInstanceEachOptions, callback?: (item: EnvironmentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EnvironmentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EnvironmentPage) => any): Promise<EnvironmentPage>; + /** + * Retrieve a single target page of EnvironmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EnvironmentPage>) => any): Promise<ApiResponse<EnvironmentPage>>; + /** + * Lists EnvironmentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EnvironmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EnvironmentInstance[]) => any): Promise<EnvironmentInstance[]>; + list(params: EnvironmentListInstanceOptions, callback?: (error: Error | null, items: EnvironmentInstance[]) => any): Promise<EnvironmentInstance[]>; + /** + * Lists EnvironmentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EnvironmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EnvironmentInstance[]>) => any): Promise<ApiResponse<EnvironmentInstance[]>>; + listWithHttpInfo(params: EnvironmentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EnvironmentInstance[]>) => any): Promise<ApiResponse<EnvironmentInstance[]>>; + /** + * Retrieve a single page of EnvironmentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EnvironmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EnvironmentPage) => any): Promise<EnvironmentPage>; + page(params: EnvironmentListInstancePageOptions, callback?: (error: Error | null, items: EnvironmentPage) => any): Promise<EnvironmentPage>; + /** + * Retrieve a single page of EnvironmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EnvironmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EnvironmentPage>) => any): Promise<ApiResponse<EnvironmentPage>>; + pageWithHttpInfo(params: EnvironmentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EnvironmentPage>) => any): Promise<ApiResponse<EnvironmentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EnvironmentListInstance(version: V1, serviceSid: string): EnvironmentListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as EnvironmentListInstance; + + instance.get = function get(sid, ): EnvironmentContext { + return new EnvironmentContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Environments`; + + instance.create = function create(params: EnvironmentListInstanceCreateOptions, callback?: (error: Error | null, items: EnvironmentInstance) => any): Promise<EnvironmentInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + if (params["domainSuffix"] !== undefined) + data["DomainSuffix"] = params["domainSuffix"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new EnvironmentInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: EnvironmentListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<EnvironmentInstance>) => any): Promise<ApiResponse<EnvironmentInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + if (params["domainSuffix"] !== undefined) + data["DomainSuffix"] = params["domainSuffix"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<EnvironmentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<EnvironmentInstance> => ({ + ...response, + body: new EnvironmentInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: EnvironmentListInstancePageOptions | ((error: Error | null, items: EnvironmentPage) => any), callback?: (error: Error | null, items: EnvironmentPage) => any): Promise<EnvironmentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EnvironmentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EnvironmentPage) => any): Promise<EnvironmentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EnvironmentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EnvironmentListInstancePageOptions | ((error: Error | null, items: ApiResponse<EnvironmentPage>) => any), callback?: (error: Error | null, items: ApiResponse<EnvironmentPage>) => any): Promise<ApiResponse<EnvironmentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EnvironmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EnvironmentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EnvironmentPage>) => any): Promise<ApiResponse<EnvironmentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EnvironmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EnvironmentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EnvironmentPage extends Page<V1, EnvironmentPayload, EnvironmentResource, EnvironmentInstance> { +/** +* Initialize the EnvironmentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: EnvironmentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EnvironmentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EnvironmentResource): EnvironmentInstance { + + return new EnvironmentInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/serverless/v1/service/environment/deployment.ts b/rest/serverless/v1/service/environment/deployment.ts new file mode 100644 index 000000000..974a956f8 --- /dev/null +++ b/rest/serverless/v1/service/environment/deployment.ts @@ -0,0 +1,706 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + +/** + * Options to pass to create a DeploymentInstance + */ +export interface DeploymentListInstanceCreateOptions { + /** The SID of the Build for the Deployment. */ + "buildSid"?: string; + /** Whether the Deployment is a plugin. */ + "isPlugin"?: boolean; +} + +/** + * Options to pass to each + */ +export interface DeploymentListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DeploymentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DeploymentListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DeploymentListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface DeploymentContext { + + /** + * Fetch a DeploymentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeploymentInstance + */ + fetch(callback?: (error: Error | null, item?: DeploymentInstance) => any): Promise<DeploymentInstance> + + /** + * Fetch a DeploymentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeploymentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DeploymentInstance>) => any): Promise<ApiResponse<DeploymentInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DeploymentContextSolution { + "serviceSid": string; + "environmentSid": string; + "sid": string; +} + +export class DeploymentContextImpl implements DeploymentContext { + protected _solution: DeploymentContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, environmentSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(environmentSid)) { + throw new Error('Parameter \'environmentSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, environmentSid, sid, }; + this._uri = `/Services/${serviceSid}/Environments/${environmentSid}/Deployments/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: DeploymentInstance) => any): Promise<DeploymentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DeploymentInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.environmentSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DeploymentInstance>) => any): Promise<ApiResponse<DeploymentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DeploymentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DeploymentInstance> => ({ + ...response, + body: new DeploymentInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.environmentSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DeploymentPayload extends TwilioResponsePayload { + deployments: DeploymentResource[]; +} + +interface DeploymentResource { + sid: string; + account_sid: string; + service_sid: string; + environment_sid: string; + build_sid: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class DeploymentInstance { + protected _solution: DeploymentContextSolution; + protected _context?: DeploymentContext; + + constructor(protected _version: V1, payload: DeploymentResource, serviceSid: string, environmentSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.environmentSid = (payload.environment_sid); + this.buildSid = (payload.build_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, environmentSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Deployment resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Deployment resource. + */ + accountSid: string; + /** + * The SID of the Service that the Deployment resource is associated with. + */ + serviceSid: string; + /** + * The SID of the Environment for the Deployment. + */ + environmentSid: string; + /** + * The SID of the Build for the deployment. + */ + buildSid: string; + /** + * The date and time in GMT when the Deployment resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Deployment resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Deployment resource. + */ + url: string; + + private get _proxy(): DeploymentContext { + this._context = this._context || new DeploymentContextImpl(this._version, this._solution.serviceSid, this._solution.environmentSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a DeploymentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeploymentInstance + */ + fetch(callback?: (error: Error | null, item?: DeploymentInstance) => any): Promise<DeploymentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DeploymentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeploymentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DeploymentInstance>) => any): Promise<ApiResponse<DeploymentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + environmentSid: this.environmentSid, + buildSid: this.buildSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DeploymentSolution { + serviceSid: string; + environmentSid: string; +} + +export interface DeploymentListInstance { + _version: V1; + _solution: DeploymentSolution; + _uri: string; + + (sid: string, ): DeploymentContext; + get(sid: string, ): DeploymentContext; + + + + + /** + * Create a DeploymentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeploymentInstance + */ + create(callback?: (error: Error | null, item?: DeploymentInstance) => any): Promise<DeploymentInstance>; + /** + * Create a DeploymentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeploymentInstance + */ + create(params: DeploymentListInstanceCreateOptions, callback?: (error: Error | null, item?: DeploymentInstance) => any): Promise<DeploymentInstance>; + + /** + * Create a DeploymentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeploymentInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DeploymentInstance>) => any): Promise<ApiResponse<DeploymentInstance>>; + /** + * Create a DeploymentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DeploymentInstance with HTTP metadata + */ + createWithHttpInfo(params: DeploymentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<DeploymentInstance>) => any): Promise<ApiResponse<DeploymentInstance>>; + + + + + /** + * Streams DeploymentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeploymentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DeploymentInstance, done: (err?: Error) => void) => void): void; + each(params: DeploymentListInstanceEachOptions, callback?: (item: DeploymentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DeploymentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeploymentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DeploymentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DeploymentListInstanceEachOptions, callback?: (item: DeploymentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DeploymentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DeploymentPage) => any): Promise<DeploymentPage>; + /** + * Retrieve a single target page of DeploymentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<DeploymentPage>) => any): Promise<ApiResponse<DeploymentPage>>; + /** + * Lists DeploymentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeploymentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DeploymentInstance[]) => any): Promise<DeploymentInstance[]>; + list(params: DeploymentListInstanceOptions, callback?: (error: Error | null, items: DeploymentInstance[]) => any): Promise<DeploymentInstance[]>; + /** + * Lists DeploymentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeploymentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DeploymentInstance[]>) => any): Promise<ApiResponse<DeploymentInstance[]>>; + listWithHttpInfo(params: DeploymentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<DeploymentInstance[]>) => any): Promise<ApiResponse<DeploymentInstance[]>>; + /** + * Retrieve a single page of DeploymentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeploymentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DeploymentPage) => any): Promise<DeploymentPage>; + page(params: DeploymentListInstancePageOptions, callback?: (error: Error | null, items: DeploymentPage) => any): Promise<DeploymentPage>; + /** + * Retrieve a single page of DeploymentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DeploymentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DeploymentPage>) => any): Promise<ApiResponse<DeploymentPage>>; + pageWithHttpInfo(params: DeploymentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<DeploymentPage>) => any): Promise<ApiResponse<DeploymentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DeploymentListInstance(version: V1, serviceSid: string, environmentSid: string): DeploymentListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(environmentSid)) { + throw new Error('Parameter \'environmentSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as DeploymentListInstance; + + instance.get = function get(sid, ): DeploymentContext { + return new DeploymentContextImpl(version, serviceSid, environmentSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, environmentSid, }; + instance._uri = `/Services/${serviceSid}/Environments/${environmentSid}/Deployments`; + + instance.create = function create(params?: DeploymentListInstanceCreateOptions | ((error: Error | null, items: DeploymentInstance) => any), callback?: (error: Error | null, items: DeploymentInstance) => any): Promise<DeploymentInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["buildSid"] !== undefined) + data["BuildSid"] = params["buildSid"]; + if (params["isPlugin"] !== undefined) + data["IsPlugin"] = serialize.bool(params["isPlugin"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DeploymentInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.environmentSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: DeploymentListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<DeploymentInstance>) => any), callback?: (error: Error | null, items: ApiResponse<DeploymentInstance>) => any): Promise<ApiResponse<DeploymentInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["buildSid"] !== undefined) + data["BuildSid"] = params["buildSid"]; + if (params["isPlugin"] !== undefined) + data["IsPlugin"] = serialize.bool(params["isPlugin"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<DeploymentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<DeploymentInstance> => ({ + ...response, + body: new DeploymentInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.environmentSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: DeploymentListInstancePageOptions | ((error: Error | null, items: DeploymentPage) => any), callback?: (error: Error | null, items: DeploymentPage) => any): Promise<DeploymentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DeploymentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DeploymentPage) => any): Promise<DeploymentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DeploymentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DeploymentListInstancePageOptions | ((error: Error | null, items: ApiResponse<DeploymentPage>) => any), callback?: (error: Error | null, items: ApiResponse<DeploymentPage>) => any): Promise<ApiResponse<DeploymentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<DeploymentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DeploymentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<DeploymentPage>) => any): Promise<ApiResponse<DeploymentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<DeploymentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DeploymentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class DeploymentPage extends Page<V1, DeploymentPayload, DeploymentResource, DeploymentInstance> { +/** +* Initialize the DeploymentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: DeploymentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DeploymentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DeploymentResource): DeploymentInstance { + + return new DeploymentInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.environmentSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/serverless/v1/service/environment/log.ts b/rest/serverless/v1/service/environment/log.ts new file mode 100644 index 000000000..e82e3c22e --- /dev/null +++ b/rest/serverless/v1/service/environment/log.ts @@ -0,0 +1,645 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface LogListInstanceEachOptions { + /** The SID of the function whose invocation produced the Log resources to read. */ + "functionSid"?: string; + /** The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. */ + "startDate"?: Date; + /** The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. */ + "endDate"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: LogInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface LogListInstanceOptions { + /** The SID of the function whose invocation produced the Log resources to read. */ + "functionSid"?: string; + /** The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. */ + "startDate"?: Date; + /** The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. */ + "endDate"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface LogListInstancePageOptions { + /** The SID of the function whose invocation produced the Log resources to read. */ + "functionSid"?: string; + /** The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. */ + "startDate"?: Date; + /** The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. */ + "endDate"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface LogContext { + + /** + * Fetch a LogInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LogInstance + */ + fetch(callback?: (error: Error | null, item?: LogInstance) => any): Promise<LogInstance> + + /** + * Fetch a LogInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LogInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LogInstance>) => any): Promise<ApiResponse<LogInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface LogContextSolution { + "serviceSid": string; + "environmentSid": string; + "sid": string; +} + +export class LogContextImpl implements LogContext { + protected _solution: LogContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, environmentSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(environmentSid)) { + throw new Error('Parameter \'environmentSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, environmentSid, sid, }; + this._uri = `/Services/${serviceSid}/Environments/${environmentSid}/Logs/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: LogInstance) => any): Promise<LogInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new LogInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.environmentSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LogInstance>) => any): Promise<ApiResponse<LogInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<LogResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<LogInstance> => ({ + ...response, + body: new LogInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.environmentSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface LogPayload extends TwilioResponsePayload { + logs: LogResource[]; +} + +interface LogResource { + sid: string; + account_sid: string; + service_sid: string; + environment_sid: string; + build_sid: string; + deployment_sid: string; + function_sid: string; + request_sid: string; + level: string; + message: string; + date_created: Date; + url: string; +} + +export class LogInstance { + protected _solution: LogContextSolution; + protected _context?: LogContext; + + constructor(protected _version: V1, payload: LogResource, serviceSid: string, environmentSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.environmentSid = (payload.environment_sid); + this.buildSid = (payload.build_sid); + this.deploymentSid = (payload.deployment_sid); + this.functionSid = (payload.function_sid); + this.requestSid = (payload.request_sid); + this.level = (payload.level); + this.message = (payload.message); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { serviceSid, environmentSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Log resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Log resource. + */ + accountSid: string; + /** + * The SID of the Service that the Log resource is associated with. + */ + serviceSid: string; + /** + * The SID of the environment in which the log occurred. + */ + environmentSid: string; + /** + * The SID of the build that corresponds to the log. + */ + buildSid: string; + /** + * The SID of the deployment that corresponds to the log. + */ + deploymentSid: string; + /** + * The SID of the function whose invocation produced the log. + */ + functionSid: string; + /** + * The SID of the request associated with the log. + */ + requestSid: string; + /** + * The log level. + */ + level: string; + /** + * The log message. + */ + message: string; + /** + * The date and time in GMT when the Log resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Log resource. + */ + url: string; + + private get _proxy(): LogContext { + this._context = this._context || new LogContextImpl(this._version, this._solution.serviceSid, this._solution.environmentSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a LogInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LogInstance + */ + fetch(callback?: (error: Error | null, item?: LogInstance) => any): Promise<LogInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a LogInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed LogInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<LogInstance>) => any): Promise<ApiResponse<LogInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + environmentSid: this.environmentSid, + buildSid: this.buildSid, + deploymentSid: this.deploymentSid, + functionSid: this.functionSid, + requestSid: this.requestSid, + level: this.level, + message: this.message, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface LogSolution { + serviceSid: string; + environmentSid: string; +} + +export interface LogListInstance { + _version: V1; + _solution: LogSolution; + _uri: string; + + (sid: string, ): LogContext; + get(sid: string, ): LogContext; + + + + + + /** + * Streams LogInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LogListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: LogInstance, done: (err?: Error) => void) => void): void; + each(params: LogListInstanceEachOptions, callback?: (item: LogInstance, done: (err?: Error) => void) => void): void; + /** + * Streams LogInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LogListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: LogInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: LogListInstanceEachOptions, callback?: (item: LogInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of LogInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: LogPage) => any): Promise<LogPage>; + /** + * Retrieve a single target page of LogInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<LogPage>) => any): Promise<ApiResponse<LogPage>>; + /** + * Lists LogInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LogListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: LogInstance[]) => any): Promise<LogInstance[]>; + list(params: LogListInstanceOptions, callback?: (error: Error | null, items: LogInstance[]) => any): Promise<LogInstance[]>; + /** + * Lists LogInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LogListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<LogInstance[]>) => any): Promise<ApiResponse<LogInstance[]>>; + listWithHttpInfo(params: LogListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<LogInstance[]>) => any): Promise<ApiResponse<LogInstance[]>>; + /** + * Retrieve a single page of LogInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LogListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: LogPage) => any): Promise<LogPage>; + page(params: LogListInstancePageOptions, callback?: (error: Error | null, items: LogPage) => any): Promise<LogPage>; + /** + * Retrieve a single page of LogInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { LogListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<LogPage>) => any): Promise<ApiResponse<LogPage>>; + pageWithHttpInfo(params: LogListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<LogPage>) => any): Promise<ApiResponse<LogPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function LogListInstance(version: V1, serviceSid: string, environmentSid: string): LogListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(environmentSid)) { + throw new Error('Parameter \'environmentSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as LogListInstance; + + instance.get = function get(sid, ): LogContext { + return new LogContextImpl(version, serviceSid, environmentSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, environmentSid, }; + instance._uri = `/Services/${serviceSid}/Environments/${environmentSid}/Logs`; + + instance.page = function page(params?: LogListInstancePageOptions | ((error: Error | null, items: LogPage) => any), callback?: (error: Error | null, items: LogPage) => any): Promise<LogPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["functionSid"] !== undefined) + data["FunctionSid"] = params["functionSid"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new LogPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: LogPage) => any): Promise<LogPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new LogPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: LogListInstancePageOptions | ((error: Error | null, items: ApiResponse<LogPage>) => any), callback?: (error: Error | null, items: ApiResponse<LogPage>) => any): Promise<ApiResponse<LogPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["functionSid"] !== undefined) + data["FunctionSid"] = params["functionSid"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<LogPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new LogPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<LogPage>) => any): Promise<ApiResponse<LogPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<LogPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new LogPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class LogPage extends Page<V1, LogPayload, LogResource, LogInstance> { +/** +* Initialize the LogPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: LogSolution) { + super(version, response, solution); + } + + /** + * Build an instance of LogInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: LogResource): LogInstance { + + return new LogInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.environmentSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/serverless/v1/service/environment/variable.ts b/rest/serverless/v1/service/environment/variable.ts new file mode 100644 index 000000000..656c72349 --- /dev/null +++ b/rest/serverless/v1/service/environment/variable.ts @@ -0,0 +1,952 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a VariableInstance + */ +export interface VariableContextUpdateOptions { + /** A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. */ + "key"?: string; + /** A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. */ + "value"?: string; +} + +/** + * Options to pass to create a VariableInstance + */ +export interface VariableListInstanceCreateOptions { + /** A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. */ + "key": string; + /** A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. */ + "value": string; +} + +/** + * Options to pass to each + */ +export interface VariableListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: VariableInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface VariableListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface VariableListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface VariableContext { + + /** + * Remove a VariableInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a VariableInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a VariableInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance + */ + fetch(callback?: (error: Error | null, item?: VariableInstance) => any): Promise<VariableInstance> + + /** + * Fetch a VariableInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>> + + /** + * Update a VariableInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance + */ + update(callback?: (error: Error | null, item?: VariableInstance) => any): Promise<VariableInstance>; + /** + * Update a VariableInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance + */ + update(params: VariableContextUpdateOptions, callback?: (error: Error | null, item?: VariableInstance) => any): Promise<VariableInstance>; + + /** + * Update a VariableInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>>; + /** + * Update a VariableInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance with HTTP metadata + */ + updateWithHttpInfo(params: VariableContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface VariableContextSolution { + "serviceSid": string; + "environmentSid": string; + "sid": string; +} + +export class VariableContextImpl implements VariableContext { + protected _solution: VariableContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, environmentSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(environmentSid)) { + throw new Error('Parameter \'environmentSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, environmentSid, sid, }; + this._uri = `/Services/${serviceSid}/Environments/${environmentSid}/Variables/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: VariableInstance) => any): Promise<VariableInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new VariableInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.environmentSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<VariableResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<VariableInstance> => ({ + ...response, + body: new VariableInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.environmentSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: VariableContextUpdateOptions | ((error: Error | null, item?: VariableInstance) => any),callback?: (error: Error | null, item?: VariableInstance) => any): Promise<VariableInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["key"] !== undefined) + data["Key"] = params["key"]; + if (params["value"] !== undefined) + data["Value"] = params["value"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new VariableInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.environmentSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: VariableContextUpdateOptions | ((error: Error | null, item?: ApiResponse<VariableInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["key"] !== undefined) + data["Key"] = params["key"]; + if (params["value"] !== undefined) + data["Value"] = params["value"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<VariableResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<VariableInstance> => ({ + ...response, + body: new VariableInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.environmentSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface VariablePayload extends TwilioResponsePayload { + variables: VariableResource[]; +} + +interface VariableResource { + sid: string; + account_sid: string; + service_sid: string; + environment_sid: string; + key: string; + value: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class VariableInstance { + protected _solution: VariableContextSolution; + protected _context?: VariableContext; + + constructor(protected _version: V1, payload: VariableResource, serviceSid: string, environmentSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.environmentSid = (payload.environment_sid); + this.key = (payload.key); + this.value = (payload.value); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, environmentSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Variable resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Variable resource. + */ + accountSid: string; + /** + * The SID of the Service that the Variable resource is associated with. + */ + serviceSid: string; + /** + * The SID of the Environment in which the Variable exists. + */ + environmentSid: string; + /** + * A string by which the Variable resource can be referenced. + */ + key: string; + /** + * A string that contains the actual value of the Variable. + */ + value: string; + /** + * The date and time in GMT when the Variable resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Variable resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Variable resource. + */ + url: string; + + private get _proxy(): VariableContext { + this._context = this._context || new VariableContextImpl(this._version, this._solution.serviceSid, this._solution.environmentSid, this._solution.sid); + return this._context; + } + + /** + * Remove a VariableInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a VariableInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a VariableInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance + */ + fetch(callback?: (error: Error | null, item?: VariableInstance) => any): Promise<VariableInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a VariableInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a VariableInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance + */ + update(callback?: (error: Error | null, item?: VariableInstance) => any): Promise<VariableInstance>; + /** + * Update a VariableInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance + */ + update(params: VariableContextUpdateOptions, callback?: (error: Error | null, item?: VariableInstance) => any): Promise<VariableInstance>; + + update(params?: any, callback?: (error: Error | null, item?: VariableInstance) => any): Promise<VariableInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a VariableInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>>; + /** + * Update a VariableInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance with HTTP metadata + */ + updateWithHttpInfo(params: VariableContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + environmentSid: this.environmentSid, + key: this.key, + value: this.value, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface VariableSolution { + serviceSid: string; + environmentSid: string; +} + +export interface VariableListInstance { + _version: V1; + _solution: VariableSolution; + _uri: string; + + (sid: string, ): VariableContext; + get(sid: string, ): VariableContext; + + + + + + + + + /** + * Create a VariableInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance + */ + create(params: VariableListInstanceCreateOptions, callback?: (error: Error | null, item?: VariableInstance) => any): Promise<VariableInstance>; + + /** + * Create a VariableInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VariableInstance with HTTP metadata + */ + createWithHttpInfo(params: VariableListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>>; + + + + + /** + * Streams VariableInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VariableListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: VariableInstance, done: (err?: Error) => void) => void): void; + each(params: VariableListInstanceEachOptions, callback?: (item: VariableInstance, done: (err?: Error) => void) => void): void; + /** + * Streams VariableInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VariableListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: VariableInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: VariableListInstanceEachOptions, callback?: (item: VariableInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of VariableInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: VariablePage) => any): Promise<VariablePage>; + /** + * Retrieve a single target page of VariableInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<VariablePage>) => any): Promise<ApiResponse<VariablePage>>; + /** + * Lists VariableInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VariableListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: VariableInstance[]) => any): Promise<VariableInstance[]>; + list(params: VariableListInstanceOptions, callback?: (error: Error | null, items: VariableInstance[]) => any): Promise<VariableInstance[]>; + /** + * Lists VariableInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VariableListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<VariableInstance[]>) => any): Promise<ApiResponse<VariableInstance[]>>; + listWithHttpInfo(params: VariableListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<VariableInstance[]>) => any): Promise<ApiResponse<VariableInstance[]>>; + /** + * Retrieve a single page of VariableInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VariableListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: VariablePage) => any): Promise<VariablePage>; + page(params: VariableListInstancePageOptions, callback?: (error: Error | null, items: VariablePage) => any): Promise<VariablePage>; + /** + * Retrieve a single page of VariableInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VariableListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<VariablePage>) => any): Promise<ApiResponse<VariablePage>>; + pageWithHttpInfo(params: VariableListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<VariablePage>) => any): Promise<ApiResponse<VariablePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function VariableListInstance(version: V1, serviceSid: string, environmentSid: string): VariableListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(environmentSid)) { + throw new Error('Parameter \'environmentSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as VariableListInstance; + + instance.get = function get(sid, ): VariableContext { + return new VariableContextImpl(version, serviceSid, environmentSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, environmentSid, }; + instance._uri = `/Services/${serviceSid}/Environments/${environmentSid}/Variables`; + + instance.create = function create(params: VariableListInstanceCreateOptions, callback?: (error: Error | null, items: VariableInstance) => any): Promise<VariableInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["key"] === null || params["key"] === undefined) { + throw new Error('Required parameter "params[\'key\']" missing.'); + } + + if (params["value"] === null || params["value"] === undefined) { + throw new Error('Required parameter "params[\'value\']" missing.'); + } + + let data: any = {}; + + + + data["Key"] = params["key"]; + + data["Value"] = params["value"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new VariableInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.environmentSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: VariableListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<VariableInstance>) => any): Promise<ApiResponse<VariableInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["key"] === null || params["key"] === undefined) { + throw new Error('Required parameter "params[\'key\']" missing.'); + } + + if (params["value"] === null || params["value"] === undefined) { + throw new Error('Required parameter "params[\'value\']" missing.'); + } + + let data: any = {}; + + + + data["Key"] = params["key"]; + + data["Value"] = params["value"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<VariableResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<VariableInstance> => ({ + ...response, + body: new VariableInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.environmentSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: VariableListInstancePageOptions | ((error: Error | null, items: VariablePage) => any), callback?: (error: Error | null, items: VariablePage) => any): Promise<VariablePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new VariablePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: VariablePage) => any): Promise<VariablePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new VariablePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: VariableListInstancePageOptions | ((error: Error | null, items: ApiResponse<VariablePage>) => any), callback?: (error: Error | null, items: ApiResponse<VariablePage>) => any): Promise<ApiResponse<VariablePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<VariablePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new VariablePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<VariablePage>) => any): Promise<ApiResponse<VariablePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<VariablePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new VariablePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class VariablePage extends Page<V1, VariablePayload, VariableResource, VariableInstance> { +/** +* Initialize the VariablePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: VariableSolution) { + super(version, response, solution); + } + + /** + * Build an instance of VariableInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: VariableResource): VariableInstance { + + return new VariableInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.environmentSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/serverless/v1/service/function.ts b/rest/serverless/v1/service/function.ts new file mode 100644 index 000000000..29eaa5e63 --- /dev/null +++ b/rest/serverless/v1/service/function.ts @@ -0,0 +1,899 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { FunctionVersionListInstance } from "./function/functionVersion"; + + + + + +/** + * Options to pass to update a FunctionInstance + */ +export interface FunctionContextUpdateOptions { + /** A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. */ + "friendlyName": string; +} + +/** + * Options to pass to create a FunctionInstance + */ +export interface FunctionListInstanceCreateOptions { + /** A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. */ + "friendlyName": string; +} + +/** + * Options to pass to each + */ +export interface FunctionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: FunctionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface FunctionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface FunctionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface FunctionContext { + functionVersions: FunctionVersionListInstance; + + /** + * Remove a FunctionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a FunctionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a FunctionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionInstance + */ + fetch(callback?: (error: Error | null, item?: FunctionInstance) => any): Promise<FunctionInstance> + + /** + * Fetch a FunctionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FunctionInstance>) => any): Promise<ApiResponse<FunctionInstance>> + + /** + * Update a FunctionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionInstance + */ + update(params: FunctionContextUpdateOptions, callback?: (error: Error | null, item?: FunctionInstance) => any): Promise<FunctionInstance>; + + /** + * Update a FunctionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionInstance with HTTP metadata + */ + updateWithHttpInfo(params: FunctionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FunctionInstance>) => any): Promise<ApiResponse<FunctionInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FunctionContextSolution { + "serviceSid": string; + "sid": string; +} + +export class FunctionContextImpl implements FunctionContext { + protected _solution: FunctionContextSolution; + protected _uri: string; + + protected _functionVersions?: FunctionVersionListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Functions/${sid}`; + } + + get functionVersions(): FunctionVersionListInstance { + this._functionVersions = this._functionVersions || FunctionVersionListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._functionVersions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: FunctionInstance) => any): Promise<FunctionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FunctionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FunctionInstance>) => any): Promise<ApiResponse<FunctionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<FunctionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<FunctionInstance> => ({ + ...response, + body: new FunctionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: FunctionContextUpdateOptions,callback?: (error: Error | null, item?: FunctionInstance) => any): Promise<FunctionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FunctionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: FunctionContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<FunctionInstance>) => any): Promise<ApiResponse<FunctionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<FunctionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<FunctionInstance> => ({ + ...response, + body: new FunctionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FunctionPayload extends TwilioResponsePayload { + functions: FunctionResource[]; +} + +interface FunctionResource { + sid: string; + account_sid: string; + service_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class FunctionInstance { + protected _solution: FunctionContextSolution; + protected _context?: FunctionContext; + + constructor(protected _version: V1, payload: FunctionResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Function resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function resource. + */ + accountSid: string; + /** + * The SID of the Service that the Function resource is associated with. + */ + serviceSid: string; + /** + * The string that you assigned to describe the Function resource. It can be a maximum of 255 characters. + */ + friendlyName: string; + /** + * The date and time in GMT when the Function resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Function resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Function resource. + */ + url: string; + /** + * The URLs of nested resources of the Function resource. + */ + links: Record<string, string>; + + private get _proxy(): FunctionContext { + this._context = this._context || new FunctionContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a FunctionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a FunctionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a FunctionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionInstance + */ + fetch(callback?: (error: Error | null, item?: FunctionInstance) => any): Promise<FunctionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FunctionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FunctionInstance>) => any): Promise<ApiResponse<FunctionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a FunctionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionInstance + */ + update(params: FunctionContextUpdateOptions, callback?: (error: Error | null, item?: FunctionInstance) => any): Promise<FunctionInstance>; + + update(params?: any, callback?: (error: Error | null, item?: FunctionInstance) => any): Promise<FunctionInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a FunctionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionInstance with HTTP metadata + */ + updateWithHttpInfo(params: FunctionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FunctionInstance>) => any): Promise<ApiResponse<FunctionInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<FunctionInstance>) => any): Promise<ApiResponse<FunctionInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the functionVersions. + */ + functionVersions(): FunctionVersionListInstance { + return this._proxy.functionVersions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FunctionSolution { + serviceSid: string; +} + +export interface FunctionListInstance { + _version: V1; + _solution: FunctionSolution; + _uri: string; + + (sid: string, ): FunctionContext; + get(sid: string, ): FunctionContext; + + + + + + + + + /** + * Create a FunctionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionInstance + */ + create(params: FunctionListInstanceCreateOptions, callback?: (error: Error | null, item?: FunctionInstance) => any): Promise<FunctionInstance>; + + /** + * Create a FunctionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionInstance with HTTP metadata + */ + createWithHttpInfo(params: FunctionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<FunctionInstance>) => any): Promise<ApiResponse<FunctionInstance>>; + + + + + /** + * Streams FunctionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: FunctionInstance, done: (err?: Error) => void) => void): void; + each(params: FunctionListInstanceEachOptions, callback?: (item: FunctionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams FunctionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: FunctionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: FunctionListInstanceEachOptions, callback?: (item: FunctionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of FunctionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: FunctionPage) => any): Promise<FunctionPage>; + /** + * Retrieve a single target page of FunctionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<FunctionPage>) => any): Promise<ApiResponse<FunctionPage>>; + /** + * Lists FunctionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: FunctionInstance[]) => any): Promise<FunctionInstance[]>; + list(params: FunctionListInstanceOptions, callback?: (error: Error | null, items: FunctionInstance[]) => any): Promise<FunctionInstance[]>; + /** + * Lists FunctionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FunctionInstance[]>) => any): Promise<ApiResponse<FunctionInstance[]>>; + listWithHttpInfo(params: FunctionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<FunctionInstance[]>) => any): Promise<ApiResponse<FunctionInstance[]>>; + /** + * Retrieve a single page of FunctionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: FunctionPage) => any): Promise<FunctionPage>; + page(params: FunctionListInstancePageOptions, callback?: (error: Error | null, items: FunctionPage) => any): Promise<FunctionPage>; + /** + * Retrieve a single page of FunctionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FunctionPage>) => any): Promise<ApiResponse<FunctionPage>>; + pageWithHttpInfo(params: FunctionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<FunctionPage>) => any): Promise<ApiResponse<FunctionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FunctionListInstance(version: V1, serviceSid: string): FunctionListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as FunctionListInstance; + + instance.get = function get(sid, ): FunctionContext { + return new FunctionContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Functions`; + + instance.create = function create(params: FunctionListInstanceCreateOptions, callback?: (error: Error | null, items: FunctionInstance) => any): Promise<FunctionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FunctionInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: FunctionListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<FunctionInstance>) => any): Promise<ApiResponse<FunctionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<FunctionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<FunctionInstance> => ({ + ...response, + body: new FunctionInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: FunctionListInstancePageOptions | ((error: Error | null, items: FunctionPage) => any), callback?: (error: Error | null, items: FunctionPage) => any): Promise<FunctionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new FunctionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: FunctionPage) => any): Promise<FunctionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new FunctionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: FunctionListInstancePageOptions | ((error: Error | null, items: ApiResponse<FunctionPage>) => any), callback?: (error: Error | null, items: ApiResponse<FunctionPage>) => any): Promise<ApiResponse<FunctionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<FunctionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FunctionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<FunctionPage>) => any): Promise<ApiResponse<FunctionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<FunctionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FunctionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class FunctionPage extends Page<V1, FunctionPayload, FunctionResource, FunctionInstance> { +/** +* Initialize the FunctionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: FunctionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of FunctionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: FunctionResource): FunctionInstance { + + return new FunctionInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/serverless/v1/service/function/functionVersion.ts b/rest/serverless/v1/service/function/functionVersion.ts new file mode 100644 index 000000000..32a1f7e42 --- /dev/null +++ b/rest/serverless/v1/service/function/functionVersion.ts @@ -0,0 +1,608 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { FunctionVersionContentListInstance } from "./functionVersion/functionVersionContent"; + + +/** + * The access control that determines how the Function Version resource can be accessed. Can be: `public`, `protected`, or `private`. + */ +export type FunctionVersionVisibility = 'public'|'private'|'protected'; + + + +/** + * Options to pass to each + */ +export interface FunctionVersionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: FunctionVersionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface FunctionVersionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface FunctionVersionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface FunctionVersionContext { + functionVersionContent: FunctionVersionContentListInstance; + + /** + * Fetch a FunctionVersionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionVersionInstance + */ + fetch(callback?: (error: Error | null, item?: FunctionVersionInstance) => any): Promise<FunctionVersionInstance> + + /** + * Fetch a FunctionVersionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionVersionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FunctionVersionInstance>) => any): Promise<ApiResponse<FunctionVersionInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FunctionVersionContextSolution { + "serviceSid": string; + "functionSid": string; + "sid": string; +} + +export class FunctionVersionContextImpl implements FunctionVersionContext { + protected _solution: FunctionVersionContextSolution; + protected _uri: string; + + protected _functionVersionContent?: FunctionVersionContentListInstance; + + constructor(protected _version: V1, serviceSid: string, functionSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(functionSid)) { + throw new Error('Parameter \'functionSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, functionSid, sid, }; + this._uri = `/Services/${serviceSid}/Functions/${functionSid}/Versions/${sid}`; + } + + get functionVersionContent(): FunctionVersionContentListInstance { + this._functionVersionContent = this._functionVersionContent || FunctionVersionContentListInstance(this._version, this._solution.serviceSid, this._solution.functionSid, this._solution.sid); + return this._functionVersionContent; + } + + fetch(callback?: (error: Error | null, item?: FunctionVersionInstance) => any): Promise<FunctionVersionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FunctionVersionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.functionSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FunctionVersionInstance>) => any): Promise<ApiResponse<FunctionVersionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<FunctionVersionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<FunctionVersionInstance> => ({ + ...response, + body: new FunctionVersionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.functionSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FunctionVersionPayload extends TwilioResponsePayload { + function_versions: FunctionVersionResource[]; +} + +interface FunctionVersionResource { + sid: string; + account_sid: string; + service_sid: string; + function_sid: string; + path: string; + visibility: FunctionVersionVisibility; + date_created: Date; + url: string; + links: Record<string, string>; +} + +export class FunctionVersionInstance { + protected _solution: FunctionVersionContextSolution; + protected _context?: FunctionVersionContext; + + constructor(protected _version: V1, payload: FunctionVersionResource, serviceSid: string, functionSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.functionSid = (payload.function_sid); + this.path = (payload.path); + this.visibility = payload.visibility; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, functionSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Function Version resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function Version resource. + */ + accountSid: string; + /** + * The SID of the Service that the Function Version resource is associated with. + */ + serviceSid: string; + /** + * The SID of the Function resource that is the parent of the Function Version resource. + */ + functionSid: string; + /** + * The URL-friendly string by which the Function Version resource can be referenced. It can be a maximum of 255 characters. All paths begin with a forward slash (\'/\'). If a Function Version creation request is submitted with a path not containing a leading slash, the path will automatically be prepended with one. + */ + path: string; + visibility: FunctionVersionVisibility; + /** + * The date and time in GMT when the Function Version resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Function Version resource. + */ + url: string; + links: Record<string, string>; + + private get _proxy(): FunctionVersionContext { + this._context = this._context || new FunctionVersionContextImpl(this._version, this._solution.serviceSid, this._solution.functionSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a FunctionVersionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionVersionInstance + */ + fetch(callback?: (error: Error | null, item?: FunctionVersionInstance) => any): Promise<FunctionVersionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FunctionVersionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionVersionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FunctionVersionInstance>) => any): Promise<ApiResponse<FunctionVersionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the functionVersionContent. + */ + functionVersionContent(): FunctionVersionContentListInstance { + return this._proxy.functionVersionContent; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + functionSid: this.functionSid, + path: this.path, + visibility: this.visibility, + dateCreated: this.dateCreated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FunctionVersionSolution { + serviceSid: string; + functionSid: string; +} + +export interface FunctionVersionListInstance { + _version: V1; + _solution: FunctionVersionSolution; + _uri: string; + + (sid: string, ): FunctionVersionContext; + get(sid: string, ): FunctionVersionContext; + + + + + + /** + * Streams FunctionVersionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionVersionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: FunctionVersionInstance, done: (err?: Error) => void) => void): void; + each(params: FunctionVersionListInstanceEachOptions, callback?: (item: FunctionVersionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams FunctionVersionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionVersionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: FunctionVersionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: FunctionVersionListInstanceEachOptions, callback?: (item: FunctionVersionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of FunctionVersionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: FunctionVersionPage) => any): Promise<FunctionVersionPage>; + /** + * Retrieve a single target page of FunctionVersionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<FunctionVersionPage>) => any): Promise<ApiResponse<FunctionVersionPage>>; + /** + * Lists FunctionVersionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionVersionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: FunctionVersionInstance[]) => any): Promise<FunctionVersionInstance[]>; + list(params: FunctionVersionListInstanceOptions, callback?: (error: Error | null, items: FunctionVersionInstance[]) => any): Promise<FunctionVersionInstance[]>; + /** + * Lists FunctionVersionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionVersionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FunctionVersionInstance[]>) => any): Promise<ApiResponse<FunctionVersionInstance[]>>; + listWithHttpInfo(params: FunctionVersionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<FunctionVersionInstance[]>) => any): Promise<ApiResponse<FunctionVersionInstance[]>>; + /** + * Retrieve a single page of FunctionVersionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionVersionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: FunctionVersionPage) => any): Promise<FunctionVersionPage>; + page(params: FunctionVersionListInstancePageOptions, callback?: (error: Error | null, items: FunctionVersionPage) => any): Promise<FunctionVersionPage>; + /** + * Retrieve a single page of FunctionVersionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FunctionVersionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FunctionVersionPage>) => any): Promise<ApiResponse<FunctionVersionPage>>; + pageWithHttpInfo(params: FunctionVersionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<FunctionVersionPage>) => any): Promise<ApiResponse<FunctionVersionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FunctionVersionListInstance(version: V1, serviceSid: string, functionSid: string): FunctionVersionListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(functionSid)) { + throw new Error('Parameter \'functionSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as FunctionVersionListInstance; + + instance.get = function get(sid, ): FunctionVersionContext { + return new FunctionVersionContextImpl(version, serviceSid, functionSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, functionSid, }; + instance._uri = `/Services/${serviceSid}/Functions/${functionSid}/Versions`; + + instance.page = function page(params?: FunctionVersionListInstancePageOptions | ((error: Error | null, items: FunctionVersionPage) => any), callback?: (error: Error | null, items: FunctionVersionPage) => any): Promise<FunctionVersionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new FunctionVersionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: FunctionVersionPage) => any): Promise<FunctionVersionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new FunctionVersionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: FunctionVersionListInstancePageOptions | ((error: Error | null, items: ApiResponse<FunctionVersionPage>) => any), callback?: (error: Error | null, items: ApiResponse<FunctionVersionPage>) => any): Promise<ApiResponse<FunctionVersionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<FunctionVersionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FunctionVersionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<FunctionVersionPage>) => any): Promise<ApiResponse<FunctionVersionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<FunctionVersionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FunctionVersionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class FunctionVersionPage extends Page<V1, FunctionVersionPayload, FunctionVersionResource, FunctionVersionInstance> { +/** +* Initialize the FunctionVersionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: FunctionVersionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of FunctionVersionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: FunctionVersionResource): FunctionVersionInstance { + + return new FunctionVersionInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.functionSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/serverless/v1/service/function/functionVersion/functionVersionContent.ts b/rest/serverless/v1/service/function/functionVersion/functionVersionContent.ts new file mode 100644 index 000000000..2c598662f --- /dev/null +++ b/rest/serverless/v1/service/function/functionVersion/functionVersionContent.ts @@ -0,0 +1,291 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Serverless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../../V1"; +const deserialize = require("../../../../../../base/deserialize"); +const serialize = require("../../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../../base/utility"; +import { ApiResponse } from "../../../../../../base/ApiResponse"; + + + + +export interface FunctionVersionContentContext { + + /** + * Fetch a FunctionVersionContentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionVersionContentInstance + */ + fetch(callback?: (error: Error | null, item?: FunctionVersionContentInstance) => any): Promise<FunctionVersionContentInstance> + + /** + * Fetch a FunctionVersionContentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionVersionContentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FunctionVersionContentInstance>) => any): Promise<ApiResponse<FunctionVersionContentInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FunctionVersionContentContextSolution { + "serviceSid": string; + "functionSid": string; + "sid": string; +} + +export class FunctionVersionContentContextImpl implements FunctionVersionContentContext { + protected _solution: FunctionVersionContentContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, functionSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(functionSid)) { + throw new Error('Parameter \'functionSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, functionSid, sid, }; + this._uri = `/Services/${serviceSid}/Functions/${functionSid}/Versions/${sid}/Content`; + } + + fetch(callback?: (error: Error | null, item?: FunctionVersionContentInstance) => any): Promise<FunctionVersionContentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FunctionVersionContentInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.functionSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FunctionVersionContentInstance>) => any): Promise<ApiResponse<FunctionVersionContentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<FunctionVersionContentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<FunctionVersionContentInstance> => ({ + ...response, + body: new FunctionVersionContentInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.functionSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FunctionVersionContentPayload extends FunctionVersionContentResource {} + +interface FunctionVersionContentResource { + sid: string; + account_sid: string; + service_sid: string; + function_sid: string; + content: string; + url: string; +} + +export class FunctionVersionContentInstance { + protected _solution: FunctionVersionContentContextSolution; + protected _context?: FunctionVersionContentContext; + + constructor(protected _version: V1, payload: FunctionVersionContentResource, serviceSid: string, functionSid: string, sid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.functionSid = (payload.function_sid); + this.content = (payload.content); + this.url = (payload.url); + + this._solution = { serviceSid, functionSid, sid, }; + } + + /** + * The unique string that we created to identify the Function Version resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function Version resource. + */ + accountSid: string; + /** + * The SID of the Service that the Function Version resource is associated with. + */ + serviceSid: string; + /** + * The SID of the Function that is the parent of the Function Version. + */ + functionSid: string; + /** + * The content of the Function Version resource. + */ + content: string; + url: string; + + private get _proxy(): FunctionVersionContentContext { + this._context = this._context || new FunctionVersionContentContextImpl(this._version, this._solution.serviceSid, this._solution.functionSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a FunctionVersionContentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionVersionContentInstance + */ + fetch(callback?: (error: Error | null, item?: FunctionVersionContentInstance) => any): Promise<FunctionVersionContentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FunctionVersionContentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FunctionVersionContentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FunctionVersionContentInstance>) => any): Promise<ApiResponse<FunctionVersionContentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + functionSid: this.functionSid, + content: this.content, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FunctionVersionContentSolution { + serviceSid: string; + functionSid: string; + sid: string; +} + +export interface FunctionVersionContentListInstance { + _version: V1; + _solution: FunctionVersionContentSolution; + _uri: string; + + (): FunctionVersionContentContext; + get(): FunctionVersionContentContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FunctionVersionContentListInstance(version: V1, serviceSid: string, functionSid: string, sid: string): FunctionVersionContentListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(functionSid)) { + throw new Error('Parameter \'functionSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + const instance = (() => instance.get()) as FunctionVersionContentListInstance; + + instance.get = function get(): FunctionVersionContentContext { + return new FunctionVersionContentContextImpl(version, serviceSid, functionSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, functionSid, sid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/studio/V1.ts b/rest/studio/V1.ts new file mode 100644 index 000000000..305f23b0b --- /dev/null +++ b/rest/studio/V1.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import StudioBase from "../StudioBase"; +import Version from "../../base/Version"; +import { FlowListInstance } from "./v1/flow"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Studio + * + * @param domain - The Twilio (Twilio.Studio) domain + */ + constructor(domain: StudioBase) { + super(domain, "v1"); + } + + /** flows - { Twilio.Studio.V1.FlowListInstance } resource */ + protected _flows?: FlowListInstance; + + /** Getter for flows resource */ + get flows(): FlowListInstance { + this._flows = this._flows || FlowListInstance(this); + return this._flows; + } + +} diff --git a/rest/studio/V2.ts b/rest/studio/V2.ts new file mode 100644 index 000000000..776435489 --- /dev/null +++ b/rest/studio/V2.ts @@ -0,0 +1,47 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import StudioBase from "../StudioBase"; +import Version from "../../base/Version"; +import { FlowListInstance } from "./v2/flow"; +import { FlowValidateListInstance } from "./v2/flowValidate"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Studio + * + * @param domain - The Twilio (Twilio.Studio) domain + */ + constructor(domain: StudioBase) { + super(domain, "v2"); + } + + /** flows - { Twilio.Studio.V2.FlowListInstance } resource */ + protected _flows?: FlowListInstance; + /** flowValidate - { Twilio.Studio.V2.FlowValidateListInstance } resource */ + protected _flowValidate?: FlowValidateListInstance; + + /** Getter for flows resource */ + get flows(): FlowListInstance { + this._flows = this._flows || FlowListInstance(this); + return this._flows; + } + + /** Getter for flowValidate resource */ + get flowValidate(): FlowValidateListInstance { + this._flowValidate = this._flowValidate || FlowValidateListInstance(this); + return this._flowValidate; + } + +} diff --git a/rest/studio/v1/flow.ts b/rest/studio/v1/flow.ts new file mode 100644 index 000000000..9693d27dc --- /dev/null +++ b/rest/studio/v1/flow.ts @@ -0,0 +1,682 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { EngagementListInstance } from "./flow/engagement"; +import { ExecutionListInstance } from "./flow/execution"; + + +/** + * The status of the Flow. Can be: `draft` or `published`. + */ +export type FlowStatus = 'draft'|'published'; + + + + +/** + * Options to pass to each + */ +export interface FlowListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: FlowInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface FlowListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface FlowListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface FlowContext { + engagements: EngagementListInstance; + executions: ExecutionListInstance; + + /** + * Remove a FlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a FlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a FlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance + */ + fetch(callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance> + + /** + * Fetch a FlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FlowContextSolution { + "sid": string; +} + +export class FlowContextImpl implements FlowContext { + protected _solution: FlowContextSolution; + protected _uri: string; + + protected _engagements?: EngagementListInstance; + protected _executions?: ExecutionListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Flows/${sid}`; + } + + get engagements(): EngagementListInstance { + this._engagements = this._engagements || EngagementListInstance(this._version, this._solution.sid); + return this._engagements; + } + + get executions(): ExecutionListInstance { + this._executions = this._executions || ExecutionListInstance(this._version, this._solution.sid); + return this._executions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FlowInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<FlowResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<FlowInstance> => ({ + ...response, + body: new FlowInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FlowPayload extends TwilioResponsePayload { + flows: FlowResource[]; +} + +interface FlowResource { + sid: string; + account_sid: string; + friendly_name: string; + status: FlowStatus; + version: number; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class FlowInstance { + protected _solution: FlowContextSolution; + protected _context?: FlowContext; + + constructor(protected _version: V1, payload: FlowResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.version = deserialize.integer(payload.version); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Flow resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the Flow. + */ + friendlyName: string; + status: FlowStatus; + /** + * The latest version number of the Flow\'s definition. + */ + version: number; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of the Flow\'s nested resources. + */ + links: Record<string, string>; + + private get _proxy(): FlowContext { + this._context = this._context || new FlowContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a FlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a FlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a FlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance + */ + fetch(callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the engagements. + */ + engagements(): EngagementListInstance { + return this._proxy.engagements; + } + + /** + * Access the executions. + */ + executions(): ExecutionListInstance { + return this._proxy.executions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + status: this.status, + version: this.version, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FlowSolution { +} + +export interface FlowListInstance { + _version: V1; + _solution: FlowSolution; + _uri: string; + + (sid: string, ): FlowContext; + get(sid: string, ): FlowContext; + + + + + + + + /** + * Streams FlowInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: FlowInstance, done: (err?: Error) => void) => void): void; + each(params: FlowListInstanceEachOptions, callback?: (item: FlowInstance, done: (err?: Error) => void) => void): void; + /** + * Streams FlowInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: FlowInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: FlowListInstanceEachOptions, callback?: (item: FlowInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of FlowInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: FlowPage) => any): Promise<FlowPage>; + /** + * Retrieve a single target page of FlowInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<FlowPage>) => any): Promise<ApiResponse<FlowPage>>; + /** + * Lists FlowInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: FlowInstance[]) => any): Promise<FlowInstance[]>; + list(params: FlowListInstanceOptions, callback?: (error: Error | null, items: FlowInstance[]) => any): Promise<FlowInstance[]>; + /** + * Lists FlowInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FlowInstance[]>) => any): Promise<ApiResponse<FlowInstance[]>>; + listWithHttpInfo(params: FlowListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<FlowInstance[]>) => any): Promise<ApiResponse<FlowInstance[]>>; + /** + * Retrieve a single page of FlowInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: FlowPage) => any): Promise<FlowPage>; + page(params: FlowListInstancePageOptions, callback?: (error: Error | null, items: FlowPage) => any): Promise<FlowPage>; + /** + * Retrieve a single page of FlowInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FlowPage>) => any): Promise<ApiResponse<FlowPage>>; + pageWithHttpInfo(params: FlowListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<FlowPage>) => any): Promise<ApiResponse<FlowPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FlowListInstance(version: V1): FlowListInstance { + const instance = ((sid, ) => instance.get(sid, )) as FlowListInstance; + + instance.get = function get(sid, ): FlowContext { + return new FlowContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Flows`; + + instance.page = function page(params?: FlowListInstancePageOptions | ((error: Error | null, items: FlowPage) => any), callback?: (error: Error | null, items: FlowPage) => any): Promise<FlowPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new FlowPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: FlowPage) => any): Promise<FlowPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new FlowPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: FlowListInstancePageOptions | ((error: Error | null, items: ApiResponse<FlowPage>) => any), callback?: (error: Error | null, items: ApiResponse<FlowPage>) => any): Promise<ApiResponse<FlowPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<FlowPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FlowPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<FlowPage>) => any): Promise<ApiResponse<FlowPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<FlowPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FlowPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class FlowPage extends Page<V1, FlowPayload, FlowResource, FlowInstance> { +/** +* Initialize the FlowPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: FlowSolution) { + super(version, response, solution); + } + + /** + * Build an instance of FlowInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: FlowResource): FlowInstance { + + return new FlowInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/studio/v1/flow/engagement.ts b/rest/studio/v1/flow/engagement.ts new file mode 100644 index 000000000..2cedb71a9 --- /dev/null +++ b/rest/studio/v1/flow/engagement.ts @@ -0,0 +1,826 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { EngagementContextListInstance } from "./engagement/engagementContext"; +import { StepListInstance } from "./engagement/step"; + + +/** + * The status of the Engagement. Can be: `active` or `ended`. + */ +export type EngagementStatus = 'active'|'ended'; + + + + +/** + * Options to pass to create a EngagementInstance + */ +export interface EngagementListInstanceCreateOptions { + /** The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. */ + "to": string; + /** The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` */ + "from": string; + /** A JSON string we will add to your flow\\\'s context and that you can access as variables inside your flow. For example, if you pass in `Parameters={\\\'name\\\':\\\'Zeke\\\'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string \\\'Zeke\\\'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. */ + "parameters"?: any; +} + +/** + * Options to pass to each + */ +export interface EngagementListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EngagementInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EngagementListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EngagementListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EngagementContext { + engagementContext: EngagementContextListInstance; + steps: StepListInstance; + + /** + * Remove a EngagementInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a EngagementInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a EngagementInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EngagementInstance + */ + fetch(callback?: (error: Error | null, item?: EngagementInstance) => any): Promise<EngagementInstance> + + /** + * Fetch a EngagementInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EngagementInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EngagementInstance>) => any): Promise<ApiResponse<EngagementInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EngagementContextSolution { + "flowSid": string; + "sid": string; +} + +export class EngagementContextImpl implements EngagementContext { + protected _solution: EngagementContextSolution; + protected _uri: string; + + protected _engagementContext?: EngagementContextListInstance; + protected _steps?: StepListInstance; + + constructor(protected _version: V1, flowSid: string, sid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { flowSid, sid, }; + this._uri = `/Flows/${flowSid}/Engagements/${sid}`; + } + + get engagementContext(): EngagementContextListInstance { + this._engagementContext = this._engagementContext || EngagementContextListInstance(this._version, this._solution.flowSid, this._solution.sid); + return this._engagementContext; + } + + get steps(): StepListInstance { + this._steps = this._steps || StepListInstance(this._version, this._solution.flowSid, this._solution.sid); + return this._steps; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: EngagementInstance) => any): Promise<EngagementInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EngagementInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EngagementInstance>) => any): Promise<ApiResponse<EngagementInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EngagementResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EngagementInstance> => ({ + ...response, + body: new EngagementInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EngagementPayload extends TwilioResponsePayload { + engagements: EngagementResource[]; +} + +interface EngagementResource { + sid: string; + account_sid: string; + flow_sid: string; + contact_sid: string; + contact_channel_address: string; + context: any; + status: EngagementStatus; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class EngagementInstance { + protected _solution: EngagementContextSolution; + protected _context?: EngagementContext; + + constructor(protected _version: V1, payload: EngagementResource, flowSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.flowSid = (payload.flow_sid); + this.contactSid = (payload.contact_sid); + this.contactChannelAddress = (payload.contact_channel_address); + this.context = (payload.context); + this.status = payload.status; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { flowSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Engagement resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Engagement resource. + */ + accountSid: string; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The SID of the Contact. + */ + contactSid: string; + /** + * The phone number, SIP address or Client identifier that triggered this Engagement. Phone numbers are in E.164 format (+16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + */ + contactChannelAddress: string; + /** + * The current state of the execution flow. As your flow executes, we save the state in a flow context. Your widgets can access the data in the flow context as variables, either in configuration fields or in text areas as variable substitution. + */ + context: any; + status: EngagementStatus; + /** + * The date and time in GMT when the Engagement was created in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Engagement was updated in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of the Engagement\'s nested resources. + */ + links: Record<string, string>; + + private get _proxy(): EngagementContext { + this._context = this._context || new EngagementContextImpl(this._version, this._solution.flowSid, this._solution.sid); + return this._context; + } + + /** + * Remove a EngagementInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a EngagementInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a EngagementInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EngagementInstance + */ + fetch(callback?: (error: Error | null, item?: EngagementInstance) => any): Promise<EngagementInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EngagementInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EngagementInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EngagementInstance>) => any): Promise<ApiResponse<EngagementInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the engagementContext. + */ + engagementContext(): EngagementContextListInstance { + return this._proxy.engagementContext; + } + + /** + * Access the steps. + */ + steps(): StepListInstance { + return this._proxy.steps; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + flowSid: this.flowSid, + contactSid: this.contactSid, + contactChannelAddress: this.contactChannelAddress, + context: this.context, + status: this.status, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EngagementSolution { + flowSid: string; +} + +export interface EngagementListInstance { + _version: V1; + _solution: EngagementSolution; + _uri: string; + + (sid: string, ): EngagementContext; + get(sid: string, ): EngagementContext; + + + + + + + /** + * Create a EngagementInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EngagementInstance + */ + create(params: EngagementListInstanceCreateOptions, callback?: (error: Error | null, item?: EngagementInstance) => any): Promise<EngagementInstance>; + + /** + * Create a EngagementInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EngagementInstance with HTTP metadata + */ + createWithHttpInfo(params: EngagementListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<EngagementInstance>) => any): Promise<ApiResponse<EngagementInstance>>; + + + + + /** + * Streams EngagementInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EngagementListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EngagementInstance, done: (err?: Error) => void) => void): void; + each(params: EngagementListInstanceEachOptions, callback?: (item: EngagementInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EngagementInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EngagementListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EngagementInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EngagementListInstanceEachOptions, callback?: (item: EngagementInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EngagementInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EngagementPage) => any): Promise<EngagementPage>; + /** + * Retrieve a single target page of EngagementInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EngagementPage>) => any): Promise<ApiResponse<EngagementPage>>; + /** + * Lists EngagementInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EngagementListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EngagementInstance[]) => any): Promise<EngagementInstance[]>; + list(params: EngagementListInstanceOptions, callback?: (error: Error | null, items: EngagementInstance[]) => any): Promise<EngagementInstance[]>; + /** + * Lists EngagementInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EngagementListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EngagementInstance[]>) => any): Promise<ApiResponse<EngagementInstance[]>>; + listWithHttpInfo(params: EngagementListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EngagementInstance[]>) => any): Promise<ApiResponse<EngagementInstance[]>>; + /** + * Retrieve a single page of EngagementInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EngagementListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EngagementPage) => any): Promise<EngagementPage>; + page(params: EngagementListInstancePageOptions, callback?: (error: Error | null, items: EngagementPage) => any): Promise<EngagementPage>; + /** + * Retrieve a single page of EngagementInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EngagementListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EngagementPage>) => any): Promise<ApiResponse<EngagementPage>>; + pageWithHttpInfo(params: EngagementListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EngagementPage>) => any): Promise<ApiResponse<EngagementPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EngagementListInstance(version: V1, flowSid: string): EngagementListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as EngagementListInstance; + + instance.get = function get(sid, ): EngagementContext { + return new EngagementContextImpl(version, flowSid, sid); + } + + instance._version = version; + instance._solution = { flowSid, }; + instance._uri = `/Flows/${flowSid}/Engagements`; + + instance.create = function create(params: EngagementListInstanceCreateOptions, callback?: (error: Error | null, items: EngagementInstance) => any): Promise<EngagementInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + if (params["from"] === null || params["from"] === undefined) { + throw new Error('Required parameter "params[\'from\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + + data["From"] = params["from"]; + if (params["parameters"] !== undefined) + data["Parameters"] = serialize.object(params["parameters"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new EngagementInstance(operationVersion, payload, instance._solution.flowSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: EngagementListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<EngagementInstance>) => any): Promise<ApiResponse<EngagementInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + if (params["from"] === null || params["from"] === undefined) { + throw new Error('Required parameter "params[\'from\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + + data["From"] = params["from"]; + if (params["parameters"] !== undefined) + data["Parameters"] = serialize.object(params["parameters"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<EngagementResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<EngagementInstance> => ({ + ...response, + body: new EngagementInstance(operationVersion, response.body, instance._solution.flowSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: EngagementListInstancePageOptions | ((error: Error | null, items: EngagementPage) => any), callback?: (error: Error | null, items: EngagementPage) => any): Promise<EngagementPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EngagementPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EngagementPage) => any): Promise<EngagementPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EngagementPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EngagementListInstancePageOptions | ((error: Error | null, items: ApiResponse<EngagementPage>) => any), callback?: (error: Error | null, items: ApiResponse<EngagementPage>) => any): Promise<ApiResponse<EngagementPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EngagementPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EngagementPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EngagementPage>) => any): Promise<ApiResponse<EngagementPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EngagementPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EngagementPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EngagementPage extends Page<V1, EngagementPayload, EngagementResource, EngagementInstance> { +/** +* Initialize the EngagementPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: EngagementSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EngagementInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EngagementResource): EngagementInstance { + + return new EngagementInstance( + this._version, + payload, + this._solution.flowSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/studio/v1/flow/engagement/engagementContext.ts b/rest/studio/v1/flow/engagement/engagementContext.ts new file mode 100644 index 000000000..fa2f748bd --- /dev/null +++ b/rest/studio/v1/flow/engagement/engagementContext.ts @@ -0,0 +1,277 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + +export interface EngagementContextContext { + + /** + * Fetch a EngagementContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EngagementContextInstance + */ + fetch(callback?: (error: Error | null, item?: EngagementContextInstance) => any): Promise<EngagementContextInstance> + + /** + * Fetch a EngagementContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EngagementContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EngagementContextInstance>) => any): Promise<ApiResponse<EngagementContextInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EngagementContextContextSolution { + "flowSid": string; + "engagementSid": string; +} + +export class EngagementContextContextImpl implements EngagementContextContext { + protected _solution: EngagementContextContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, flowSid: string, engagementSid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(engagementSid)) { + throw new Error('Parameter \'engagementSid\' is not valid.'); + } + + this._solution = { flowSid, engagementSid, }; + this._uri = `/Flows/${flowSid}/Engagements/${engagementSid}/Context`; + } + + fetch(callback?: (error: Error | null, item?: EngagementContextInstance) => any): Promise<EngagementContextInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EngagementContextInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.engagementSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EngagementContextInstance>) => any): Promise<ApiResponse<EngagementContextInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EngagementContextResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EngagementContextInstance> => ({ + ...response, + body: new EngagementContextInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.engagementSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EngagementContextPayload extends EngagementContextResource {} + +interface EngagementContextResource { + account_sid: string; + context: any; + engagement_sid: string; + flow_sid: string; + url: string; +} + +export class EngagementContextInstance { + protected _solution: EngagementContextContextSolution; + protected _context?: EngagementContextContext; + + constructor(protected _version: V1, payload: EngagementContextResource, flowSid: string, engagementSid: string) { + + this.accountSid = (payload.account_sid); + this.context = (payload.context); + this.engagementSid = (payload.engagement_sid); + this.flowSid = (payload.flow_sid); + this.url = (payload.url); + + this._solution = { flowSid, engagementSid, }; + } + + /** + * The SID of the Account. + */ + accountSid: string; + /** + * As your flow executes, we save the state in what\'s called the Flow Context. Any data in the flow context can be accessed by your widgets as variables, either in configuration fields or in text areas as variable substitution. + */ + context: any; + /** + * The SID of the Engagement. + */ + engagementSid: string; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The URL of the resource. + */ + url: string; + + private get _proxy(): EngagementContextContext { + this._context = this._context || new EngagementContextContextImpl(this._version, this._solution.flowSid, this._solution.engagementSid); + return this._context; + } + + /** + * Fetch a EngagementContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EngagementContextInstance + */ + fetch(callback?: (error: Error | null, item?: EngagementContextInstance) => any): Promise<EngagementContextInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EngagementContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EngagementContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EngagementContextInstance>) => any): Promise<ApiResponse<EngagementContextInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + context: this.context, + engagementSid: this.engagementSid, + flowSid: this.flowSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EngagementContextSolution { + flowSid: string; + engagementSid: string; +} + +export interface EngagementContextListInstance { + _version: V1; + _solution: EngagementContextSolution; + _uri: string; + + (): EngagementContextContext; + get(): EngagementContextContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EngagementContextListInstance(version: V1, flowSid: string, engagementSid: string): EngagementContextListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(engagementSid)) { + throw new Error('Parameter \'engagementSid\' is not valid.'); + } + + const instance = (() => instance.get()) as EngagementContextListInstance; + + instance.get = function get(): EngagementContextContext { + return new EngagementContextContextImpl(version, flowSid, engagementSid); + } + + instance._version = version; + instance._solution = { flowSid, engagementSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/studio/v1/flow/engagement/step.ts b/rest/studio/v1/flow/engagement/step.ts new file mode 100644 index 000000000..4e8c92084 --- /dev/null +++ b/rest/studio/v1/flow/engagement/step.ts @@ -0,0 +1,644 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { StepContextListInstance } from "./step/stepContext"; + + + + +/** + * Options to pass to each + */ +export interface StepListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: StepInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface StepListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface StepListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface StepContext { + stepContext: StepContextListInstance; + + /** + * Fetch a StepInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StepInstance + */ + fetch(callback?: (error: Error | null, item?: StepInstance) => any): Promise<StepInstance> + + /** + * Fetch a StepInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StepInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StepInstance>) => any): Promise<ApiResponse<StepInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface StepContextSolution { + "flowSid": string; + "engagementSid": string; + "sid": string; +} + +export class StepContextImpl implements StepContext { + protected _solution: StepContextSolution; + protected _uri: string; + + protected _stepContext?: StepContextListInstance; + + constructor(protected _version: V1, flowSid: string, engagementSid: string, sid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(engagementSid)) { + throw new Error('Parameter \'engagementSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { flowSid, engagementSid, sid, }; + this._uri = `/Flows/${flowSid}/Engagements/${engagementSid}/Steps/${sid}`; + } + + get stepContext(): StepContextListInstance { + this._stepContext = this._stepContext || StepContextListInstance(this._version, this._solution.flowSid, this._solution.engagementSid, this._solution.sid); + return this._stepContext; + } + + fetch(callback?: (error: Error | null, item?: StepInstance) => any): Promise<StepInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new StepInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.engagementSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StepInstance>) => any): Promise<ApiResponse<StepInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<StepResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<StepInstance> => ({ + ...response, + body: new StepInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.engagementSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface StepPayload extends TwilioResponsePayload { + steps: StepResource[]; +} + +interface StepResource { + sid: string; + account_sid: string; + flow_sid: string; + engagement_sid: string; + name: string; + context: any; + parent_step_sid: string; + transitioned_from: string; + transitioned_to: string; + type: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class StepInstance { + protected _solution: StepContextSolution; + protected _context?: StepContext; + + constructor(protected _version: V1, payload: StepResource, flowSid: string, engagementSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.flowSid = (payload.flow_sid); + this.engagementSid = (payload.engagement_sid); + this.name = (payload.name); + this.context = (payload.context); + this.parentStepSid = (payload.parent_step_sid); + this.transitionedFrom = (payload.transitioned_from); + this.transitionedTo = (payload.transitioned_to); + this.type = (payload.type); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { flowSid, engagementSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Step resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Step resource. + */ + accountSid: string; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The SID of the Engagement. + */ + engagementSid: string; + /** + * The event that caused the Flow to transition to the Step. + */ + name: string; + /** + * The current state of the Flow\'s Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + */ + context: any; + /** + * The SID of the parent Step. + */ + parentStepSid: string; + /** + * The Widget that preceded the Widget for the Step. + */ + transitionedFrom: string; + /** + * The Widget that will follow the Widget for the Step. + */ + transitionedTo: string; + /** + * The type of the widget that was executed. + */ + type: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): StepContext { + this._context = this._context || new StepContextImpl(this._version, this._solution.flowSid, this._solution.engagementSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a StepInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StepInstance + */ + fetch(callback?: (error: Error | null, item?: StepInstance) => any): Promise<StepInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a StepInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StepInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StepInstance>) => any): Promise<ApiResponse<StepInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the stepContext. + */ + stepContext(): StepContextListInstance { + return this._proxy.stepContext; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + flowSid: this.flowSid, + engagementSid: this.engagementSid, + name: this.name, + context: this.context, + parentStepSid: this.parentStepSid, + transitionedFrom: this.transitionedFrom, + transitionedTo: this.transitionedTo, + type: this.type, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface StepSolution { + flowSid: string; + engagementSid: string; +} + +export interface StepListInstance { + _version: V1; + _solution: StepSolution; + _uri: string; + + (sid: string, ): StepContext; + get(sid: string, ): StepContext; + + + + + + /** + * Streams StepInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StepListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: StepInstance, done: (err?: Error) => void) => void): void; + each(params: StepListInstanceEachOptions, callback?: (item: StepInstance, done: (err?: Error) => void) => void): void; + /** + * Streams StepInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StepListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: StepInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: StepListInstanceEachOptions, callback?: (item: StepInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of StepInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: StepPage) => any): Promise<StepPage>; + /** + * Retrieve a single target page of StepInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<StepPage>) => any): Promise<ApiResponse<StepPage>>; + /** + * Lists StepInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StepListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: StepInstance[]) => any): Promise<StepInstance[]>; + list(params: StepListInstanceOptions, callback?: (error: Error | null, items: StepInstance[]) => any): Promise<StepInstance[]>; + /** + * Lists StepInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StepListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<StepInstance[]>) => any): Promise<ApiResponse<StepInstance[]>>; + listWithHttpInfo(params: StepListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<StepInstance[]>) => any): Promise<ApiResponse<StepInstance[]>>; + /** + * Retrieve a single page of StepInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StepListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: StepPage) => any): Promise<StepPage>; + page(params: StepListInstancePageOptions, callback?: (error: Error | null, items: StepPage) => any): Promise<StepPage>; + /** + * Retrieve a single page of StepInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { StepListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<StepPage>) => any): Promise<ApiResponse<StepPage>>; + pageWithHttpInfo(params: StepListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<StepPage>) => any): Promise<ApiResponse<StepPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function StepListInstance(version: V1, flowSid: string, engagementSid: string): StepListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(engagementSid)) { + throw new Error('Parameter \'engagementSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as StepListInstance; + + instance.get = function get(sid, ): StepContext { + return new StepContextImpl(version, flowSid, engagementSid, sid); + } + + instance._version = version; + instance._solution = { flowSid, engagementSid, }; + instance._uri = `/Flows/${flowSid}/Engagements/${engagementSid}/Steps`; + + instance.page = function page(params?: StepListInstancePageOptions | ((error: Error | null, items: StepPage) => any), callback?: (error: Error | null, items: StepPage) => any): Promise<StepPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new StepPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: StepPage) => any): Promise<StepPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new StepPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: StepListInstancePageOptions | ((error: Error | null, items: ApiResponse<StepPage>) => any), callback?: (error: Error | null, items: ApiResponse<StepPage>) => any): Promise<ApiResponse<StepPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<StepPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new StepPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<StepPage>) => any): Promise<ApiResponse<StepPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<StepPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new StepPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class StepPage extends Page<V1, StepPayload, StepResource, StepInstance> { +/** +* Initialize the StepPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: StepSolution) { + super(version, response, solution); + } + + /** + * Build an instance of StepInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: StepResource): StepInstance { + + return new StepInstance( + this._version, + payload, + this._solution.flowSid, + this._solution.engagementSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/studio/v1/flow/engagement/step/stepContext.ts b/rest/studio/v1/flow/engagement/step/stepContext.ts new file mode 100644 index 000000000..ffbc7801e --- /dev/null +++ b/rest/studio/v1/flow/engagement/step/stepContext.ts @@ -0,0 +1,294 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../../V1"; +const deserialize = require("../../../../../../base/deserialize"); +const serialize = require("../../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../../base/utility"; +import { ApiResponse } from "../../../../../../base/ApiResponse"; + + + + +export interface StepContextContext { + + /** + * Fetch a StepContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StepContextInstance + */ + fetch(callback?: (error: Error | null, item?: StepContextInstance) => any): Promise<StepContextInstance> + + /** + * Fetch a StepContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StepContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StepContextInstance>) => any): Promise<ApiResponse<StepContextInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface StepContextContextSolution { + "flowSid": string; + "engagementSid": string; + "stepSid": string; +} + +export class StepContextContextImpl implements StepContextContext { + protected _solution: StepContextContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, flowSid: string, engagementSid: string, stepSid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(engagementSid)) { + throw new Error('Parameter \'engagementSid\' is not valid.'); + } + + if (!isValidPathParam(stepSid)) { + throw new Error('Parameter \'stepSid\' is not valid.'); + } + + this._solution = { flowSid, engagementSid, stepSid, }; + this._uri = `/Flows/${flowSid}/Engagements/${engagementSid}/Steps/${stepSid}/Context`; + } + + fetch(callback?: (error: Error | null, item?: StepContextInstance) => any): Promise<StepContextInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new StepContextInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.engagementSid, instance._solution.stepSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StepContextInstance>) => any): Promise<ApiResponse<StepContextInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<StepContextResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<StepContextInstance> => ({ + ...response, + body: new StepContextInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.engagementSid, instance._solution.stepSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface StepContextPayload extends StepContextResource {} + +interface StepContextResource { + account_sid: string; + context: any; + engagement_sid: string; + flow_sid: string; + step_sid: string; + url: string; +} + +export class StepContextInstance { + protected _solution: StepContextContextSolution; + protected _context?: StepContextContext; + + constructor(protected _version: V1, payload: StepContextResource, flowSid: string, engagementSid: string, stepSid: string) { + + this.accountSid = (payload.account_sid); + this.context = (payload.context); + this.engagementSid = (payload.engagement_sid); + this.flowSid = (payload.flow_sid); + this.stepSid = (payload.step_sid); + this.url = (payload.url); + + this._solution = { flowSid, engagementSid, stepSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the StepContext resource. + */ + accountSid: string; + /** + * The current state of the Flow\'s Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + */ + context: any; + /** + * The SID of the Engagement. + */ + engagementSid: string; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The SID of the Step the context is associated with. + */ + stepSid: string; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): StepContextContext { + this._context = this._context || new StepContextContextImpl(this._version, this._solution.flowSid, this._solution.engagementSid, this._solution.stepSid); + return this._context; + } + + /** + * Fetch a StepContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StepContextInstance + */ + fetch(callback?: (error: Error | null, item?: StepContextInstance) => any): Promise<StepContextInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a StepContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StepContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<StepContextInstance>) => any): Promise<ApiResponse<StepContextInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + context: this.context, + engagementSid: this.engagementSid, + flowSid: this.flowSid, + stepSid: this.stepSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface StepContextSolution { + flowSid: string; + engagementSid: string; + stepSid: string; +} + +export interface StepContextListInstance { + _version: V1; + _solution: StepContextSolution; + _uri: string; + + (): StepContextContext; + get(): StepContextContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function StepContextListInstance(version: V1, flowSid: string, engagementSid: string, stepSid: string): StepContextListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(engagementSid)) { + throw new Error('Parameter \'engagementSid\' is not valid.'); + } + + if (!isValidPathParam(stepSid)) { + throw new Error('Parameter \'stepSid\' is not valid.'); + } + + const instance = (() => instance.get()) as StepContextListInstance; + + instance.get = function get(): StepContextContext { + return new StepContextContextImpl(version, flowSid, engagementSid, stepSid); + } + + instance._version = version; + instance._solution = { flowSid, engagementSid, stepSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/studio/v1/flow/execution.ts b/rest/studio/v1/flow/execution.ts new file mode 100644 index 000000000..9d8b08762 --- /dev/null +++ b/rest/studio/v1/flow/execution.ts @@ -0,0 +1,977 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { ExecutionContextListInstance } from "./execution/executionContext"; +import { ExecutionStepListInstance } from "./execution/executionStep"; + + +/** + * The status of the Execution. Can be: `active` or `ended`. + */ +export type ExecutionStatus = 'active'|'ended'; + + + + +/** + * Options to pass to update a ExecutionInstance + */ +export interface ExecutionContextUpdateOptions { + /** */ + "status": ExecutionStatus; +} + +/** + * Options to pass to create a ExecutionInstance + */ +export interface ExecutionListInstanceCreateOptions { + /** The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. */ + "to": string; + /** The Twilio phone number to send messages or initiate calls from during the Flow\\\'s Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. */ + "from": string; + /** JSON data that will be added to the Flow\\\'s context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. */ + "parameters"?: any; +} + +/** + * Options to pass to each + */ +export interface ExecutionListInstanceEachOptions { + /** Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedFrom"?: Date; + /** Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedTo"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ExecutionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ExecutionListInstanceOptions { + /** Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedFrom"?: Date; + /** Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedTo"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ExecutionListInstancePageOptions { + /** Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedFrom"?: Date; + /** Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedTo"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ExecutionContext { + executionContext: ExecutionContextListInstance; + steps: ExecutionStepListInstance; + + /** + * Remove a ExecutionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ExecutionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ExecutionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance> + + /** + * Fetch a ExecutionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> + + /** + * Update a ExecutionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance + */ + update(params: ExecutionContextUpdateOptions, callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance>; + + /** + * Update a ExecutionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance with HTTP metadata + */ + updateWithHttpInfo(params: ExecutionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ExecutionContextSolution { + "flowSid": string; + "sid": string; +} + +export class ExecutionContextImpl implements ExecutionContext { + protected _solution: ExecutionContextSolution; + protected _uri: string; + + protected _executionContext?: ExecutionContextListInstance; + protected _steps?: ExecutionStepListInstance; + + constructor(protected _version: V1, flowSid: string, sid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { flowSid, sid, }; + this._uri = `/Flows/${flowSid}/Executions/${sid}`; + } + + get executionContext(): ExecutionContextListInstance { + this._executionContext = this._executionContext || ExecutionContextListInstance(this._version, this._solution.flowSid, this._solution.sid); + return this._executionContext; + } + + get steps(): ExecutionStepListInstance { + this._steps = this._steps || ExecutionStepListInstance(this._version, this._solution.flowSid, this._solution.sid); + return this._steps; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ExecutionInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ExecutionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ExecutionInstance> => ({ + ...response, + body: new ExecutionInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: ExecutionContextUpdateOptions,callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ExecutionInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: ExecutionContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ExecutionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ExecutionInstance> => ({ + ...response, + body: new ExecutionInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ExecutionPayload extends TwilioResponsePayload { + executions: ExecutionResource[]; +} + +interface ExecutionResource { + sid: string; + account_sid: string; + flow_sid: string; + contact_sid: string; + contact_channel_address: string; + context: any; + status: ExecutionStatus; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class ExecutionInstance { + protected _solution: ExecutionContextSolution; + protected _context?: ExecutionContext; + + constructor(protected _version: V1, payload: ExecutionResource, flowSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.flowSid = (payload.flow_sid); + this.contactSid = (payload.contact_sid); + this.contactChannelAddress = (payload.contact_channel_address); + this.context = (payload.context); + this.status = payload.status; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { flowSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Execution resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Execution resource. + */ + accountSid: string; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The SID of the Contact. + */ + contactSid: string; + /** + * The phone number, SIP address or Client identifier that triggered the Execution. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + */ + contactChannelAddress: string; + /** + * The current state of the Flow\'s Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + */ + context: any; + status: ExecutionStatus; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of nested resources. + */ + links: Record<string, string>; + + private get _proxy(): ExecutionContext { + this._context = this._context || new ExecutionContextImpl(this._version, this._solution.flowSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ExecutionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ExecutionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ExecutionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ExecutionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ExecutionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance + */ + update(params: ExecutionContextUpdateOptions, callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ExecutionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance with HTTP metadata + */ + updateWithHttpInfo(params: ExecutionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the executionContext. + */ + executionContext(): ExecutionContextListInstance { + return this._proxy.executionContext; + } + + /** + * Access the steps. + */ + steps(): ExecutionStepListInstance { + return this._proxy.steps; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + flowSid: this.flowSid, + contactSid: this.contactSid, + contactChannelAddress: this.contactChannelAddress, + context: this.context, + status: this.status, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ExecutionSolution { + flowSid: string; +} + +export interface ExecutionListInstance { + _version: V1; + _solution: ExecutionSolution; + _uri: string; + + (sid: string, ): ExecutionContext; + get(sid: string, ): ExecutionContext; + + + + + + + + + /** + * Create a ExecutionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance + */ + create(params: ExecutionListInstanceCreateOptions, callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance>; + + /** + * Create a ExecutionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance with HTTP metadata + */ + createWithHttpInfo(params: ExecutionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>>; + + + + + /** + * Streams ExecutionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ExecutionInstance, done: (err?: Error) => void) => void): void; + each(params: ExecutionListInstanceEachOptions, callback?: (item: ExecutionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ExecutionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ExecutionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ExecutionListInstanceEachOptions, callback?: (item: ExecutionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ExecutionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ExecutionPage) => any): Promise<ExecutionPage>; + /** + * Retrieve a single target page of ExecutionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ExecutionPage>) => any): Promise<ApiResponse<ExecutionPage>>; + /** + * Lists ExecutionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ExecutionInstance[]) => any): Promise<ExecutionInstance[]>; + list(params: ExecutionListInstanceOptions, callback?: (error: Error | null, items: ExecutionInstance[]) => any): Promise<ExecutionInstance[]>; + /** + * Lists ExecutionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ExecutionInstance[]>) => any): Promise<ApiResponse<ExecutionInstance[]>>; + listWithHttpInfo(params: ExecutionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ExecutionInstance[]>) => any): Promise<ApiResponse<ExecutionInstance[]>>; + /** + * Retrieve a single page of ExecutionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ExecutionPage) => any): Promise<ExecutionPage>; + page(params: ExecutionListInstancePageOptions, callback?: (error: Error | null, items: ExecutionPage) => any): Promise<ExecutionPage>; + /** + * Retrieve a single page of ExecutionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ExecutionPage>) => any): Promise<ApiResponse<ExecutionPage>>; + pageWithHttpInfo(params: ExecutionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ExecutionPage>) => any): Promise<ApiResponse<ExecutionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExecutionListInstance(version: V1, flowSid: string): ExecutionListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ExecutionListInstance; + + instance.get = function get(sid, ): ExecutionContext { + return new ExecutionContextImpl(version, flowSid, sid); + } + + instance._version = version; + instance._solution = { flowSid, }; + instance._uri = `/Flows/${flowSid}/Executions`; + + instance.create = function create(params: ExecutionListInstanceCreateOptions, callback?: (error: Error | null, items: ExecutionInstance) => any): Promise<ExecutionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + if (params["from"] === null || params["from"] === undefined) { + throw new Error('Required parameter "params[\'from\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + + data["From"] = params["from"]; + if (params["parameters"] !== undefined) + data["Parameters"] = serialize.object(params["parameters"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ExecutionInstance(operationVersion, payload, instance._solution.flowSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ExecutionListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + if (params["from"] === null || params["from"] === undefined) { + throw new Error('Required parameter "params[\'from\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + + data["From"] = params["from"]; + if (params["parameters"] !== undefined) + data["Parameters"] = serialize.object(params["parameters"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ExecutionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ExecutionInstance> => ({ + ...response, + body: new ExecutionInstance(operationVersion, response.body, instance._solution.flowSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ExecutionListInstancePageOptions | ((error: Error | null, items: ExecutionPage) => any), callback?: (error: Error | null, items: ExecutionPage) => any): Promise<ExecutionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreatedFrom"] !== undefined) + data["DateCreatedFrom"] = serialize.iso8601DateTime(params["dateCreatedFrom"]); + if (params["dateCreatedTo"] !== undefined) + data["DateCreatedTo"] = serialize.iso8601DateTime(params["dateCreatedTo"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ExecutionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ExecutionPage) => any): Promise<ExecutionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ExecutionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ExecutionListInstancePageOptions | ((error: Error | null, items: ApiResponse<ExecutionPage>) => any), callback?: (error: Error | null, items: ApiResponse<ExecutionPage>) => any): Promise<ApiResponse<ExecutionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreatedFrom"] !== undefined) + data["DateCreatedFrom"] = serialize.iso8601DateTime(params["dateCreatedFrom"]); + if (params["dateCreatedTo"] !== undefined) + data["DateCreatedTo"] = serialize.iso8601DateTime(params["dateCreatedTo"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ExecutionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ExecutionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ExecutionPage>) => any): Promise<ApiResponse<ExecutionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ExecutionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ExecutionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ExecutionPage extends Page<V1, ExecutionPayload, ExecutionResource, ExecutionInstance> { +/** +* Initialize the ExecutionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ExecutionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ExecutionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ExecutionResource): ExecutionInstance { + + return new ExecutionInstance( + this._version, + payload, + this._solution.flowSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/studio/v1/flow/execution/executionContext.ts b/rest/studio/v1/flow/execution/executionContext.ts new file mode 100644 index 000000000..09e28979c --- /dev/null +++ b/rest/studio/v1/flow/execution/executionContext.ts @@ -0,0 +1,277 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + +export interface ExecutionContextContext { + + /** + * Fetch a ExecutionContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionContextInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionContextInstance) => any): Promise<ExecutionContextInstance> + + /** + * Fetch a ExecutionContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionContextInstance>) => any): Promise<ApiResponse<ExecutionContextInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ExecutionContextContextSolution { + "flowSid": string; + "executionSid": string; +} + +export class ExecutionContextContextImpl implements ExecutionContextContext { + protected _solution: ExecutionContextContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, flowSid: string, executionSid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + this._solution = { flowSid, executionSid, }; + this._uri = `/Flows/${flowSid}/Executions/${executionSid}/Context`; + } + + fetch(callback?: (error: Error | null, item?: ExecutionContextInstance) => any): Promise<ExecutionContextInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ExecutionContextInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.executionSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionContextInstance>) => any): Promise<ApiResponse<ExecutionContextInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ExecutionContextResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ExecutionContextInstance> => ({ + ...response, + body: new ExecutionContextInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.executionSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ExecutionContextPayload extends ExecutionContextResource {} + +interface ExecutionContextResource { + account_sid: string; + context: any; + flow_sid: string; + execution_sid: string; + url: string; +} + +export class ExecutionContextInstance { + protected _solution: ExecutionContextContextSolution; + protected _context?: ExecutionContextContext; + + constructor(protected _version: V1, payload: ExecutionContextResource, flowSid: string, executionSid: string) { + + this.accountSid = (payload.account_sid); + this.context = (payload.context); + this.flowSid = (payload.flow_sid); + this.executionSid = (payload.execution_sid); + this.url = (payload.url); + + this._solution = { flowSid, executionSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionContext resource. + */ + accountSid: string; + /** + * The current state of the Flow\'s Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + */ + context: any; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The SID of the context\'s Execution resource. + */ + executionSid: string; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): ExecutionContextContext { + this._context = this._context || new ExecutionContextContextImpl(this._version, this._solution.flowSid, this._solution.executionSid); + return this._context; + } + + /** + * Fetch a ExecutionContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionContextInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionContextInstance) => any): Promise<ExecutionContextInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ExecutionContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionContextInstance>) => any): Promise<ApiResponse<ExecutionContextInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + context: this.context, + flowSid: this.flowSid, + executionSid: this.executionSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ExecutionContextSolution { + flowSid: string; + executionSid: string; +} + +export interface ExecutionContextListInstance { + _version: V1; + _solution: ExecutionContextSolution; + _uri: string; + + (): ExecutionContextContext; + get(): ExecutionContextContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExecutionContextListInstance(version: V1, flowSid: string, executionSid: string): ExecutionContextListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + const instance = (() => instance.get()) as ExecutionContextListInstance; + + instance.get = function get(): ExecutionContextContext { + return new ExecutionContextContextImpl(version, flowSid, executionSid); + } + + instance._version = version; + instance._solution = { flowSid, executionSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/studio/v1/flow/execution/executionStep.ts b/rest/studio/v1/flow/execution/executionStep.ts new file mode 100644 index 000000000..44ba0b1cc --- /dev/null +++ b/rest/studio/v1/flow/execution/executionStep.ts @@ -0,0 +1,644 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { ExecutionStepContextListInstance } from "./executionStep/executionStepContext"; + + + + +/** + * Options to pass to each + */ +export interface ExecutionStepListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ExecutionStepInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ExecutionStepListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ExecutionStepListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ExecutionStepContext { + stepContext: ExecutionStepContextListInstance; + + /** + * Fetch a ExecutionStepInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionStepInstance) => any): Promise<ExecutionStepInstance> + + /** + * Fetch a ExecutionStepInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepInstance>) => any): Promise<ApiResponse<ExecutionStepInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ExecutionStepContextSolution { + "flowSid": string; + "executionSid": string; + "sid": string; +} + +export class ExecutionStepContextImpl implements ExecutionStepContext { + protected _solution: ExecutionStepContextSolution; + protected _uri: string; + + protected _stepContext?: ExecutionStepContextListInstance; + + constructor(protected _version: V1, flowSid: string, executionSid: string, sid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { flowSid, executionSid, sid, }; + this._uri = `/Flows/${flowSid}/Executions/${executionSid}/Steps/${sid}`; + } + + get stepContext(): ExecutionStepContextListInstance { + this._stepContext = this._stepContext || ExecutionStepContextListInstance(this._version, this._solution.flowSid, this._solution.executionSid, this._solution.sid); + return this._stepContext; + } + + fetch(callback?: (error: Error | null, item?: ExecutionStepInstance) => any): Promise<ExecutionStepInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ExecutionStepInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.executionSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepInstance>) => any): Promise<ApiResponse<ExecutionStepInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ExecutionStepResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ExecutionStepInstance> => ({ + ...response, + body: new ExecutionStepInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.executionSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ExecutionStepPayload extends TwilioResponsePayload { + steps: ExecutionStepResource[]; +} + +interface ExecutionStepResource { + sid: string; + account_sid: string; + flow_sid: string; + execution_sid: string; + parent_step_sid: string; + name: string; + context: any; + transitioned_from: string; + transitioned_to: string; + type: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class ExecutionStepInstance { + protected _solution: ExecutionStepContextSolution; + protected _context?: ExecutionStepContext; + + constructor(protected _version: V1, payload: ExecutionStepResource, flowSid: string, executionSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.flowSid = (payload.flow_sid); + this.executionSid = (payload.execution_sid); + this.parentStepSid = (payload.parent_step_sid); + this.name = (payload.name); + this.context = (payload.context); + this.transitionedFrom = (payload.transitioned_from); + this.transitionedTo = (payload.transitioned_to); + this.type = (payload.type); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { flowSid, executionSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the ExecutionStep resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStep resource. + */ + accountSid: string; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The SID of the Step\'s Execution resource. + */ + executionSid: string; + /** + * This field shows the Step SID of the Widget in the parent Flow that started the Subflow. If this Step is not part of a Subflow execution, the value is null. + */ + parentStepSid: string; + /** + * The event that caused the Flow to transition to the Step. + */ + name: string; + /** + * The current state of the Flow\'s Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + */ + context: any; + /** + * The Widget that preceded the Widget for the Step. + */ + transitionedFrom: string; + /** + * The Widget that will follow the Widget for the Step. + */ + transitionedTo: string; + /** + * The type of the widget that was executed. + */ + type: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): ExecutionStepContext { + this._context = this._context || new ExecutionStepContextImpl(this._version, this._solution.flowSid, this._solution.executionSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a ExecutionStepInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionStepInstance) => any): Promise<ExecutionStepInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ExecutionStepInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepInstance>) => any): Promise<ApiResponse<ExecutionStepInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the stepContext. + */ + stepContext(): ExecutionStepContextListInstance { + return this._proxy.stepContext; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + flowSid: this.flowSid, + executionSid: this.executionSid, + parentStepSid: this.parentStepSid, + name: this.name, + context: this.context, + transitionedFrom: this.transitionedFrom, + transitionedTo: this.transitionedTo, + type: this.type, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ExecutionStepSolution { + flowSid: string; + executionSid: string; +} + +export interface ExecutionStepListInstance { + _version: V1; + _solution: ExecutionStepSolution; + _uri: string; + + (sid: string, ): ExecutionStepContext; + get(sid: string, ): ExecutionStepContext; + + + + + + /** + * Streams ExecutionStepInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ExecutionStepInstance, done: (err?: Error) => void) => void): void; + each(params: ExecutionStepListInstanceEachOptions, callback?: (item: ExecutionStepInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ExecutionStepInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ExecutionStepInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ExecutionStepListInstanceEachOptions, callback?: (item: ExecutionStepInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ExecutionStepInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ExecutionStepPage) => any): Promise<ExecutionStepPage>; + /** + * Retrieve a single target page of ExecutionStepInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ExecutionStepPage>) => any): Promise<ApiResponse<ExecutionStepPage>>; + /** + * Lists ExecutionStepInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ExecutionStepInstance[]) => any): Promise<ExecutionStepInstance[]>; + list(params: ExecutionStepListInstanceOptions, callback?: (error: Error | null, items: ExecutionStepInstance[]) => any): Promise<ExecutionStepInstance[]>; + /** + * Lists ExecutionStepInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ExecutionStepInstance[]>) => any): Promise<ApiResponse<ExecutionStepInstance[]>>; + listWithHttpInfo(params: ExecutionStepListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ExecutionStepInstance[]>) => any): Promise<ApiResponse<ExecutionStepInstance[]>>; + /** + * Retrieve a single page of ExecutionStepInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ExecutionStepPage) => any): Promise<ExecutionStepPage>; + page(params: ExecutionStepListInstancePageOptions, callback?: (error: Error | null, items: ExecutionStepPage) => any): Promise<ExecutionStepPage>; + /** + * Retrieve a single page of ExecutionStepInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ExecutionStepPage>) => any): Promise<ApiResponse<ExecutionStepPage>>; + pageWithHttpInfo(params: ExecutionStepListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ExecutionStepPage>) => any): Promise<ApiResponse<ExecutionStepPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExecutionStepListInstance(version: V1, flowSid: string, executionSid: string): ExecutionStepListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ExecutionStepListInstance; + + instance.get = function get(sid, ): ExecutionStepContext { + return new ExecutionStepContextImpl(version, flowSid, executionSid, sid); + } + + instance._version = version; + instance._solution = { flowSid, executionSid, }; + instance._uri = `/Flows/${flowSid}/Executions/${executionSid}/Steps`; + + instance.page = function page(params?: ExecutionStepListInstancePageOptions | ((error: Error | null, items: ExecutionStepPage) => any), callback?: (error: Error | null, items: ExecutionStepPage) => any): Promise<ExecutionStepPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ExecutionStepPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ExecutionStepPage) => any): Promise<ExecutionStepPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ExecutionStepPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ExecutionStepListInstancePageOptions | ((error: Error | null, items: ApiResponse<ExecutionStepPage>) => any), callback?: (error: Error | null, items: ApiResponse<ExecutionStepPage>) => any): Promise<ApiResponse<ExecutionStepPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ExecutionStepPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ExecutionStepPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ExecutionStepPage>) => any): Promise<ApiResponse<ExecutionStepPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ExecutionStepPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ExecutionStepPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ExecutionStepPage extends Page<V1, ExecutionStepPayload, ExecutionStepResource, ExecutionStepInstance> { +/** +* Initialize the ExecutionStepPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ExecutionStepSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ExecutionStepInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ExecutionStepResource): ExecutionStepInstance { + + return new ExecutionStepInstance( + this._version, + payload, + this._solution.flowSid, + this._solution.executionSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/studio/v1/flow/execution/executionStep/executionStepContext.ts b/rest/studio/v1/flow/execution/executionStep/executionStepContext.ts new file mode 100644 index 000000000..7cd6502c4 --- /dev/null +++ b/rest/studio/v1/flow/execution/executionStep/executionStepContext.ts @@ -0,0 +1,294 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../../V1"; +const deserialize = require("../../../../../../base/deserialize"); +const serialize = require("../../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../../base/utility"; +import { ApiResponse } from "../../../../../../base/ApiResponse"; + + + + +export interface ExecutionStepContextContext { + + /** + * Fetch a ExecutionStepContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepContextInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionStepContextInstance) => any): Promise<ExecutionStepContextInstance> + + /** + * Fetch a ExecutionStepContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepContextInstance>) => any): Promise<ApiResponse<ExecutionStepContextInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ExecutionStepContextContextSolution { + "flowSid": string; + "executionSid": string; + "stepSid": string; +} + +export class ExecutionStepContextContextImpl implements ExecutionStepContextContext { + protected _solution: ExecutionStepContextContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, flowSid: string, executionSid: string, stepSid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + if (!isValidPathParam(stepSid)) { + throw new Error('Parameter \'stepSid\' is not valid.'); + } + + this._solution = { flowSid, executionSid, stepSid, }; + this._uri = `/Flows/${flowSid}/Executions/${executionSid}/Steps/${stepSid}/Context`; + } + + fetch(callback?: (error: Error | null, item?: ExecutionStepContextInstance) => any): Promise<ExecutionStepContextInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ExecutionStepContextInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.executionSid, instance._solution.stepSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepContextInstance>) => any): Promise<ApiResponse<ExecutionStepContextInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ExecutionStepContextResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ExecutionStepContextInstance> => ({ + ...response, + body: new ExecutionStepContextInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.executionSid, instance._solution.stepSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ExecutionStepContextPayload extends ExecutionStepContextResource {} + +interface ExecutionStepContextResource { + account_sid: string; + context: any; + execution_sid: string; + flow_sid: string; + step_sid: string; + url: string; +} + +export class ExecutionStepContextInstance { + protected _solution: ExecutionStepContextContextSolution; + protected _context?: ExecutionStepContextContext; + + constructor(protected _version: V1, payload: ExecutionStepContextResource, flowSid: string, executionSid: string, stepSid: string) { + + this.accountSid = (payload.account_sid); + this.context = (payload.context); + this.executionSid = (payload.execution_sid); + this.flowSid = (payload.flow_sid); + this.stepSid = (payload.step_sid); + this.url = (payload.url); + + this._solution = { flowSid, executionSid, stepSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStepContext resource. + */ + accountSid: string; + /** + * The current state of the Flow\'s Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + */ + context: any; + /** + * The SID of the context\'s Execution resource. + */ + executionSid: string; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The SID of the Step that the context is associated with. + */ + stepSid: string; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): ExecutionStepContextContext { + this._context = this._context || new ExecutionStepContextContextImpl(this._version, this._solution.flowSid, this._solution.executionSid, this._solution.stepSid); + return this._context; + } + + /** + * Fetch a ExecutionStepContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepContextInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionStepContextInstance) => any): Promise<ExecutionStepContextInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ExecutionStepContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepContextInstance>) => any): Promise<ApiResponse<ExecutionStepContextInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + context: this.context, + executionSid: this.executionSid, + flowSid: this.flowSid, + stepSid: this.stepSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ExecutionStepContextSolution { + flowSid: string; + executionSid: string; + stepSid: string; +} + +export interface ExecutionStepContextListInstance { + _version: V1; + _solution: ExecutionStepContextSolution; + _uri: string; + + (): ExecutionStepContextContext; + get(): ExecutionStepContextContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExecutionStepContextListInstance(version: V1, flowSid: string, executionSid: string, stepSid: string): ExecutionStepContextListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + if (!isValidPathParam(stepSid)) { + throw new Error('Parameter \'stepSid\' is not valid.'); + } + + const instance = (() => instance.get()) as ExecutionStepContextListInstance; + + instance.get = function get(): ExecutionStepContextContext { + return new ExecutionStepContextContextImpl(version, flowSid, executionSid, stepSid); + } + + instance._version = version; + instance._solution = { flowSid, executionSid, stepSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/studio/v2/flow.ts b/rest/studio/v2/flow.ts new file mode 100644 index 000000000..be85d5e84 --- /dev/null +++ b/rest/studio/v2/flow.ts @@ -0,0 +1,1037 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ExecutionListInstance } from "./flow/execution"; +import { FlowRevisionListInstance } from "./flow/flowRevision"; +import { FlowTestUserListInstance } from "./flow/flowTestUser"; + + +/** + * The status of the Flow. Can be: `draft` or `published`. + */ +export type FlowStatus = 'draft'|'published'; + + + + +/** + * Options to pass to update a FlowInstance + */ +export interface FlowContextUpdateOptions { + /** */ + "status": FlowStatus; + /** The string that you assigned to describe the Flow. */ + "friendlyName"?: string; + /** JSON representation of flow definition. */ + "definition"?: any; + /** Description of change made in the revision. */ + "commitMessage"?: string; + /** The SID of the User that created or last updated the Flow. */ + "authorSid"?: string; +} + +/** + * Options to pass to create a FlowInstance + */ +export interface FlowListInstanceCreateOptions { + /** The string that you assigned to describe the Flow. */ + "friendlyName": string; + /** */ + "status": FlowStatus; + /** JSON representation of flow definition. */ + "definition": any; + /** Description of change made in the revision. */ + "commitMessage"?: string; + /** The SID of the User that created the Flow. */ + "authorSid"?: string; +} + +/** + * Options to pass to each + */ +export interface FlowListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: FlowInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface FlowListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface FlowListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface FlowContext { + executions: ExecutionListInstance; + revisions: FlowRevisionListInstance; + testUsers: FlowTestUserListInstance; + + /** + * Remove a FlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a FlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a FlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance + */ + fetch(callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance> + + /** + * Fetch a FlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>> + + /** + * Update a FlowInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance + */ + update(params: FlowContextUpdateOptions, callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance>; + + /** + * Update a FlowInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance with HTTP metadata + */ + updateWithHttpInfo(params: FlowContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FlowContextSolution { + "sid": string; +} + +export class FlowContextImpl implements FlowContext { + protected _solution: FlowContextSolution; + protected _uri: string; + + protected _executions?: ExecutionListInstance; + protected _revisions?: FlowRevisionListInstance; + protected _testUsers?: FlowTestUserListInstance; + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Flows/${sid}`; + } + + get executions(): ExecutionListInstance { + this._executions = this._executions || ExecutionListInstance(this._version, this._solution.sid); + return this._executions; + } + + get revisions(): FlowRevisionListInstance { + this._revisions = this._revisions || FlowRevisionListInstance(this._version, this._solution.sid); + return this._revisions; + } + + get testUsers(): FlowTestUserListInstance { + this._testUsers = this._testUsers || FlowTestUserListInstance(this._version, this._solution.sid); + return this._testUsers; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FlowInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<FlowResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<FlowInstance> => ({ + ...response, + body: new FlowInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: FlowContextUpdateOptions,callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["definition"] !== undefined) + data["Definition"] = serialize.object(params["definition"]); + if (params["commitMessage"] !== undefined) + data["CommitMessage"] = params["commitMessage"]; + if (params["authorSid"] !== undefined) + data["AuthorSid"] = params["authorSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FlowInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: FlowContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["definition"] !== undefined) + data["Definition"] = serialize.object(params["definition"]); + if (params["commitMessage"] !== undefined) + data["CommitMessage"] = params["commitMessage"]; + if (params["authorSid"] !== undefined) + data["AuthorSid"] = params["authorSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<FlowResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<FlowInstance> => ({ + ...response, + body: new FlowInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FlowPayload extends TwilioResponsePayload { + flows: FlowResource[]; +} + +interface FlowResource { + sid: string; + account_sid: string; + author_sid: string; + friendly_name: string; + definition: any; + status: FlowStatus; + revision: number; + commit_message: string; + valid: boolean; + errors: Array<any>; + warnings: Array<any>; + date_created: Date; + date_updated: Date; + webhook_url: string; + url: string; + links: Record<string, string>; +} + +export class FlowInstance { + protected _solution: FlowContextSolution; + protected _context?: FlowContext; + + constructor(protected _version: V2, payload: FlowResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.authorSid = (payload.author_sid); + this.friendlyName = (payload.friendly_name); + this.definition = (payload.definition); + this.status = payload.status; + this.revision = deserialize.integer(payload.revision); + this.commitMessage = (payload.commit_message); + this.valid = (payload.valid); + this.errors = (payload.errors); + this.warnings = (payload.warnings); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.webhookUrl = (payload.webhook_url); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Flow resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + */ + accountSid: string; + /** + * The SID of the User that created or last updated the Flow. + */ + authorSid: string; + /** + * The string that you assigned to describe the Flow. + */ + friendlyName: string; + /** + * JSON representation of flow definition. + */ + definition: any; + status: FlowStatus; + /** + * The latest revision number of the Flow\'s definition. + */ + revision: number; + /** + * Description of change made in the revision. + */ + commitMessage: string; + /** + * Boolean if the flow definition is valid. + */ + valid: boolean; + /** + * List of error in the flow definition. + */ + errors: Array<any>; + /** + * List of warnings in the flow definition. + */ + warnings: Array<any>; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + webhookUrl: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of the Flow\'s nested resources. + */ + links: Record<string, string>; + + private get _proxy(): FlowContext { + this._context = this._context || new FlowContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a FlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a FlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a FlowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance + */ + fetch(callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FlowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a FlowInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance + */ + update(params: FlowContextUpdateOptions, callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance>; + + update(params?: any, callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a FlowInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance with HTTP metadata + */ + updateWithHttpInfo(params: FlowContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the executions. + */ + executions(): ExecutionListInstance { + return this._proxy.executions; + } + + /** + * Access the revisions. + */ + revisions(): FlowRevisionListInstance { + return this._proxy.revisions; + } + + /** + * Access the testUsers. + */ + testUsers(): FlowTestUserListInstance { + return this._proxy.testUsers; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + authorSid: this.authorSid, + friendlyName: this.friendlyName, + definition: this.definition, + status: this.status, + revision: this.revision, + commitMessage: this.commitMessage, + valid: this.valid, + errors: this.errors, + warnings: this.warnings, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + webhookUrl: this.webhookUrl, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FlowSolution { +} + +export interface FlowListInstance { + _version: V2; + _solution: FlowSolution; + _uri: string; + + (sid: string, ): FlowContext; + get(sid: string, ): FlowContext; + + + + + + + + + /** + * Create a FlowInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance + */ + create(params: FlowListInstanceCreateOptions, callback?: (error: Error | null, item?: FlowInstance) => any): Promise<FlowInstance>; + + /** + * Create a FlowInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowInstance with HTTP metadata + */ + createWithHttpInfo(params: FlowListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>>; + + + + + /** + * Streams FlowInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: FlowInstance, done: (err?: Error) => void) => void): void; + each(params: FlowListInstanceEachOptions, callback?: (item: FlowInstance, done: (err?: Error) => void) => void): void; + /** + * Streams FlowInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: FlowInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: FlowListInstanceEachOptions, callback?: (item: FlowInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of FlowInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: FlowPage) => any): Promise<FlowPage>; + /** + * Retrieve a single target page of FlowInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<FlowPage>) => any): Promise<ApiResponse<FlowPage>>; + /** + * Lists FlowInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: FlowInstance[]) => any): Promise<FlowInstance[]>; + list(params: FlowListInstanceOptions, callback?: (error: Error | null, items: FlowInstance[]) => any): Promise<FlowInstance[]>; + /** + * Lists FlowInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FlowInstance[]>) => any): Promise<ApiResponse<FlowInstance[]>>; + listWithHttpInfo(params: FlowListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<FlowInstance[]>) => any): Promise<ApiResponse<FlowInstance[]>>; + /** + * Retrieve a single page of FlowInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: FlowPage) => any): Promise<FlowPage>; + page(params: FlowListInstancePageOptions, callback?: (error: Error | null, items: FlowPage) => any): Promise<FlowPage>; + /** + * Retrieve a single page of FlowInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FlowPage>) => any): Promise<ApiResponse<FlowPage>>; + pageWithHttpInfo(params: FlowListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<FlowPage>) => any): Promise<ApiResponse<FlowPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FlowListInstance(version: V2): FlowListInstance { + const instance = ((sid, ) => instance.get(sid, )) as FlowListInstance; + + instance.get = function get(sid, ): FlowContext { + return new FlowContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Flows`; + + instance.create = function create(params: FlowListInstanceCreateOptions, callback?: (error: Error | null, items: FlowInstance) => any): Promise<FlowInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + if (params["definition"] === null || params["definition"] === undefined) { + throw new Error('Required parameter "params[\'definition\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Status"] = params["status"]; + + data["Definition"] = serialize.object(params["definition"]); + if (params["commitMessage"] !== undefined) + data["CommitMessage"] = params["commitMessage"]; + if (params["authorSid"] !== undefined) + data["AuthorSid"] = params["authorSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FlowInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: FlowListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<FlowInstance>) => any): Promise<ApiResponse<FlowInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + if (params["definition"] === null || params["definition"] === undefined) { + throw new Error('Required parameter "params[\'definition\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Status"] = params["status"]; + + data["Definition"] = serialize.object(params["definition"]); + if (params["commitMessage"] !== undefined) + data["CommitMessage"] = params["commitMessage"]; + if (params["authorSid"] !== undefined) + data["AuthorSid"] = params["authorSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<FlowResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<FlowInstance> => ({ + ...response, + body: new FlowInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: FlowListInstancePageOptions | ((error: Error | null, items: FlowPage) => any), callback?: (error: Error | null, items: FlowPage) => any): Promise<FlowPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new FlowPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: FlowPage) => any): Promise<FlowPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new FlowPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: FlowListInstancePageOptions | ((error: Error | null, items: ApiResponse<FlowPage>) => any), callback?: (error: Error | null, items: ApiResponse<FlowPage>) => any): Promise<ApiResponse<FlowPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<FlowPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FlowPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<FlowPage>) => any): Promise<ApiResponse<FlowPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<FlowPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FlowPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class FlowPage extends Page<V2, FlowPayload, FlowResource, FlowInstance> { +/** +* Initialize the FlowPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: FlowSolution) { + super(version, response, solution); + } + + /** + * Build an instance of FlowInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: FlowResource): FlowInstance { + + return new FlowInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/studio/v2/flow/execution.ts b/rest/studio/v2/flow/execution.ts new file mode 100644 index 000000000..90f580f1d --- /dev/null +++ b/rest/studio/v2/flow/execution.ts @@ -0,0 +1,1001 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { ExecutionContextListInstance } from "./execution/executionContext"; +import { ExecutionStepListInstance } from "./execution/executionStep"; + + +/** + * The status of the Execution. Can be: `active` or `ended`. + */ +export type ExecutionStatus = 'active'|'ended'; + + + + +/** + * Options to pass to update a ExecutionInstance + */ +export interface ExecutionContextUpdateOptions { + /** */ + "status": ExecutionStatus; +} + +/** + * Options to pass to create a ExecutionInstance + */ +export interface ExecutionListInstanceCreateOptions { + /** The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. */ + "to": string; + /** The Twilio phone number to send messages or initiate calls from during the Flow\\\'s Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. */ + "from": string; + /** JSON data that will be added to the Flow\\\'s context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. */ + "parameters"?: any; +} + +/** + * Options to pass to each + */ +export interface ExecutionListInstanceEachOptions { + /** Only show Execution resources with the given status. Can be: `active` or `ended`. */ + "status"?: ExecutionStatus; + /** Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedFrom"?: Date; + /** Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedTo"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ExecutionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ExecutionListInstanceOptions { + /** Only show Execution resources with the given status. Can be: `active` or `ended`. */ + "status"?: ExecutionStatus; + /** Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedFrom"?: Date; + /** Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedTo"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ExecutionListInstancePageOptions { + /** Only show Execution resources with the given status. Can be: `active` or `ended`. */ + "status"?: ExecutionStatus; + /** Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedFrom"?: Date; + /** Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. */ + "dateCreatedTo"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ExecutionContext { + executionContext: ExecutionContextListInstance; + steps: ExecutionStepListInstance; + + /** + * Remove a ExecutionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ExecutionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ExecutionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance> + + /** + * Fetch a ExecutionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> + + /** + * Update a ExecutionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance + */ + update(params: ExecutionContextUpdateOptions, callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance>; + + /** + * Update a ExecutionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance with HTTP metadata + */ + updateWithHttpInfo(params: ExecutionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ExecutionContextSolution { + "flowSid": string; + "sid": string; +} + +export class ExecutionContextImpl implements ExecutionContext { + protected _solution: ExecutionContextSolution; + protected _uri: string; + + protected _executionContext?: ExecutionContextListInstance; + protected _steps?: ExecutionStepListInstance; + + constructor(protected _version: V2, flowSid: string, sid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { flowSid, sid, }; + this._uri = `/Flows/${flowSid}/Executions/${sid}`; + } + + get executionContext(): ExecutionContextListInstance { + this._executionContext = this._executionContext || ExecutionContextListInstance(this._version, this._solution.flowSid, this._solution.sid); + return this._executionContext; + } + + get steps(): ExecutionStepListInstance { + this._steps = this._steps || ExecutionStepListInstance(this._version, this._solution.flowSid, this._solution.sid); + return this._steps; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ExecutionInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ExecutionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ExecutionInstance> => ({ + ...response, + body: new ExecutionInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: ExecutionContextUpdateOptions,callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ExecutionInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: ExecutionContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ExecutionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ExecutionInstance> => ({ + ...response, + body: new ExecutionInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ExecutionPayload extends TwilioResponsePayload { + executions: ExecutionResource[]; +} + +interface ExecutionResource { + sid: string; + account_sid: string; + flow_sid: string; + contact_channel_address: string; + contact_sid: string; + flow_version: number; + context: any; + status: ExecutionStatus; + date_created: Date; + date_updated: Date; + initiated_by: string; + url: string; + links: Record<string, string>; +} + +export class ExecutionInstance { + protected _solution: ExecutionContextSolution; + protected _context?: ExecutionContext; + + constructor(protected _version: V2, payload: ExecutionResource, flowSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.flowSid = (payload.flow_sid); + this.contactChannelAddress = (payload.contact_channel_address); + this.contactSid = (payload.contact_sid); + this.flowVersion = deserialize.integer(payload.flow_version); + this.context = (payload.context); + this.status = payload.status; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.initiatedBy = (payload.initiated_by); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { flowSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Execution resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Execution resource. + */ + accountSid: string; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The phone number, SIP address or Client identifier that triggered the Execution. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + */ + contactChannelAddress: string; + /** + * The SID of the Contact. + */ + contactSid: string; + /** + * The Flow version number at the time of Execution creation. + */ + flowVersion: number; + /** + * The current state of the Flow\'s Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + */ + context: any; + status: ExecutionStatus; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The SID or identifier that triggered this Execution. For example, a Call SID if triggered by an incoming call, a Message SID if triggered by an incoming message, a Request SID if triggered by a REST API request, and so on. + */ + initiatedBy: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of nested resources. + */ + links: Record<string, string>; + + private get _proxy(): ExecutionContext { + this._context = this._context || new ExecutionContextImpl(this._version, this._solution.flowSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ExecutionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ExecutionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ExecutionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ExecutionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ExecutionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance + */ + update(params: ExecutionContextUpdateOptions, callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ExecutionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance with HTTP metadata + */ + updateWithHttpInfo(params: ExecutionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the executionContext. + */ + executionContext(): ExecutionContextListInstance { + return this._proxy.executionContext; + } + + /** + * Access the steps. + */ + steps(): ExecutionStepListInstance { + return this._proxy.steps; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + flowSid: this.flowSid, + contactChannelAddress: this.contactChannelAddress, + contactSid: this.contactSid, + flowVersion: this.flowVersion, + context: this.context, + status: this.status, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + initiatedBy: this.initiatedBy, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ExecutionSolution { + flowSid: string; +} + +export interface ExecutionListInstance { + _version: V2; + _solution: ExecutionSolution; + _uri: string; + + (sid: string, ): ExecutionContext; + get(sid: string, ): ExecutionContext; + + + + + + + + + /** + * Create a ExecutionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance + */ + create(params: ExecutionListInstanceCreateOptions, callback?: (error: Error | null, item?: ExecutionInstance) => any): Promise<ExecutionInstance>; + + /** + * Create a ExecutionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionInstance with HTTP metadata + */ + createWithHttpInfo(params: ExecutionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>>; + + + + + /** + * Streams ExecutionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ExecutionInstance, done: (err?: Error) => void) => void): void; + each(params: ExecutionListInstanceEachOptions, callback?: (item: ExecutionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ExecutionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ExecutionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ExecutionListInstanceEachOptions, callback?: (item: ExecutionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ExecutionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ExecutionPage) => any): Promise<ExecutionPage>; + /** + * Retrieve a single target page of ExecutionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ExecutionPage>) => any): Promise<ApiResponse<ExecutionPage>>; + /** + * Lists ExecutionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ExecutionInstance[]) => any): Promise<ExecutionInstance[]>; + list(params: ExecutionListInstanceOptions, callback?: (error: Error | null, items: ExecutionInstance[]) => any): Promise<ExecutionInstance[]>; + /** + * Lists ExecutionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ExecutionInstance[]>) => any): Promise<ApiResponse<ExecutionInstance[]>>; + listWithHttpInfo(params: ExecutionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ExecutionInstance[]>) => any): Promise<ApiResponse<ExecutionInstance[]>>; + /** + * Retrieve a single page of ExecutionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ExecutionPage) => any): Promise<ExecutionPage>; + page(params: ExecutionListInstancePageOptions, callback?: (error: Error | null, items: ExecutionPage) => any): Promise<ExecutionPage>; + /** + * Retrieve a single page of ExecutionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ExecutionPage>) => any): Promise<ApiResponse<ExecutionPage>>; + pageWithHttpInfo(params: ExecutionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ExecutionPage>) => any): Promise<ApiResponse<ExecutionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExecutionListInstance(version: V2, flowSid: string): ExecutionListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ExecutionListInstance; + + instance.get = function get(sid, ): ExecutionContext { + return new ExecutionContextImpl(version, flowSid, sid); + } + + instance._version = version; + instance._solution = { flowSid, }; + instance._uri = `/Flows/${flowSid}/Executions`; + + instance.create = function create(params: ExecutionListInstanceCreateOptions, callback?: (error: Error | null, items: ExecutionInstance) => any): Promise<ExecutionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + if (params["from"] === null || params["from"] === undefined) { + throw new Error('Required parameter "params[\'from\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + + data["From"] = params["from"]; + if (params["parameters"] !== undefined) + data["Parameters"] = serialize.object(params["parameters"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ExecutionInstance(operationVersion, payload, instance._solution.flowSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ExecutionListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ExecutionInstance>) => any): Promise<ApiResponse<ExecutionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + if (params["from"] === null || params["from"] === undefined) { + throw new Error('Required parameter "params[\'from\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + + data["From"] = params["from"]; + if (params["parameters"] !== undefined) + data["Parameters"] = serialize.object(params["parameters"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ExecutionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ExecutionInstance> => ({ + ...response, + body: new ExecutionInstance(operationVersion, response.body, instance._solution.flowSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ExecutionListInstancePageOptions | ((error: Error | null, items: ExecutionPage) => any), callback?: (error: Error | null, items: ExecutionPage) => any): Promise<ExecutionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["status"] = params["status"]; + if (params["dateCreatedFrom"] !== undefined) + data["DateCreatedFrom"] = serialize.iso8601DateTime(params["dateCreatedFrom"]); + if (params["dateCreatedTo"] !== undefined) + data["DateCreatedTo"] = serialize.iso8601DateTime(params["dateCreatedTo"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ExecutionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ExecutionPage) => any): Promise<ExecutionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ExecutionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ExecutionListInstancePageOptions | ((error: Error | null, items: ApiResponse<ExecutionPage>) => any), callback?: (error: Error | null, items: ApiResponse<ExecutionPage>) => any): Promise<ApiResponse<ExecutionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["status"] = params["status"]; + if (params["dateCreatedFrom"] !== undefined) + data["DateCreatedFrom"] = serialize.iso8601DateTime(params["dateCreatedFrom"]); + if (params["dateCreatedTo"] !== undefined) + data["DateCreatedTo"] = serialize.iso8601DateTime(params["dateCreatedTo"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ExecutionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ExecutionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ExecutionPage>) => any): Promise<ApiResponse<ExecutionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ExecutionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ExecutionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ExecutionPage extends Page<V2, ExecutionPayload, ExecutionResource, ExecutionInstance> { +/** +* Initialize the ExecutionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: ExecutionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ExecutionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ExecutionResource): ExecutionInstance { + + return new ExecutionInstance( + this._version, + payload, + this._solution.flowSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/studio/v2/flow/execution/executionContext.ts b/rest/studio/v2/flow/execution/executionContext.ts new file mode 100644 index 000000000..aae768b3e --- /dev/null +++ b/rest/studio/v2/flow/execution/executionContext.ts @@ -0,0 +1,277 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + +export interface ExecutionContextContext { + + /** + * Fetch a ExecutionContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionContextInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionContextInstance) => any): Promise<ExecutionContextInstance> + + /** + * Fetch a ExecutionContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionContextInstance>) => any): Promise<ApiResponse<ExecutionContextInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ExecutionContextContextSolution { + "flowSid": string; + "executionSid": string; +} + +export class ExecutionContextContextImpl implements ExecutionContextContext { + protected _solution: ExecutionContextContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, flowSid: string, executionSid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + this._solution = { flowSid, executionSid, }; + this._uri = `/Flows/${flowSid}/Executions/${executionSid}/Context`; + } + + fetch(callback?: (error: Error | null, item?: ExecutionContextInstance) => any): Promise<ExecutionContextInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ExecutionContextInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.executionSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionContextInstance>) => any): Promise<ApiResponse<ExecutionContextInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ExecutionContextResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ExecutionContextInstance> => ({ + ...response, + body: new ExecutionContextInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.executionSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ExecutionContextPayload extends ExecutionContextResource {} + +interface ExecutionContextResource { + account_sid: string; + context: any; + flow_sid: string; + execution_sid: string; + url: string; +} + +export class ExecutionContextInstance { + protected _solution: ExecutionContextContextSolution; + protected _context?: ExecutionContextContext; + + constructor(protected _version: V2, payload: ExecutionContextResource, flowSid: string, executionSid: string) { + + this.accountSid = (payload.account_sid); + this.context = (payload.context); + this.flowSid = (payload.flow_sid); + this.executionSid = (payload.execution_sid); + this.url = (payload.url); + + this._solution = { flowSid, executionSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionContext resource. + */ + accountSid: string; + /** + * The current state of the Flow\'s Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + */ + context: any; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The SID of the context\'s Execution resource. + */ + executionSid: string; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): ExecutionContextContext { + this._context = this._context || new ExecutionContextContextImpl(this._version, this._solution.flowSid, this._solution.executionSid); + return this._context; + } + + /** + * Fetch a ExecutionContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionContextInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionContextInstance) => any): Promise<ExecutionContextInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ExecutionContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionContextInstance>) => any): Promise<ApiResponse<ExecutionContextInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + context: this.context, + flowSid: this.flowSid, + executionSid: this.executionSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ExecutionContextSolution { + flowSid: string; + executionSid: string; +} + +export interface ExecutionContextListInstance { + _version: V2; + _solution: ExecutionContextSolution; + _uri: string; + + (): ExecutionContextContext; + get(): ExecutionContextContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExecutionContextListInstance(version: V2, flowSid: string, executionSid: string): ExecutionContextListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + const instance = (() => instance.get()) as ExecutionContextListInstance; + + instance.get = function get(): ExecutionContextContext { + return new ExecutionContextContextImpl(version, flowSid, executionSid); + } + + instance._version = version; + instance._solution = { flowSid, executionSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/studio/v2/flow/execution/executionStep.ts b/rest/studio/v2/flow/execution/executionStep.ts new file mode 100644 index 000000000..4f958ab97 --- /dev/null +++ b/rest/studio/v2/flow/execution/executionStep.ts @@ -0,0 +1,644 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { ExecutionStepContextListInstance } from "./executionStep/executionStepContext"; + + + + +/** + * Options to pass to each + */ +export interface ExecutionStepListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ExecutionStepInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ExecutionStepListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ExecutionStepListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ExecutionStepContext { + stepContext: ExecutionStepContextListInstance; + + /** + * Fetch a ExecutionStepInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionStepInstance) => any): Promise<ExecutionStepInstance> + + /** + * Fetch a ExecutionStepInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepInstance>) => any): Promise<ApiResponse<ExecutionStepInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ExecutionStepContextSolution { + "flowSid": string; + "executionSid": string; + "sid": string; +} + +export class ExecutionStepContextImpl implements ExecutionStepContext { + protected _solution: ExecutionStepContextSolution; + protected _uri: string; + + protected _stepContext?: ExecutionStepContextListInstance; + + constructor(protected _version: V2, flowSid: string, executionSid: string, sid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { flowSid, executionSid, sid, }; + this._uri = `/Flows/${flowSid}/Executions/${executionSid}/Steps/${sid}`; + } + + get stepContext(): ExecutionStepContextListInstance { + this._stepContext = this._stepContext || ExecutionStepContextListInstance(this._version, this._solution.flowSid, this._solution.executionSid, this._solution.sid); + return this._stepContext; + } + + fetch(callback?: (error: Error | null, item?: ExecutionStepInstance) => any): Promise<ExecutionStepInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ExecutionStepInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.executionSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepInstance>) => any): Promise<ApiResponse<ExecutionStepInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ExecutionStepResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ExecutionStepInstance> => ({ + ...response, + body: new ExecutionStepInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.executionSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ExecutionStepPayload extends TwilioResponsePayload { + steps: ExecutionStepResource[]; +} + +interface ExecutionStepResource { + sid: string; + account_sid: string; + flow_sid: string; + execution_sid: string; + parent_step_sid: string; + name: string; + context: any; + transitioned_from: string; + transitioned_to: string; + type: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class ExecutionStepInstance { + protected _solution: ExecutionStepContextSolution; + protected _context?: ExecutionStepContext; + + constructor(protected _version: V2, payload: ExecutionStepResource, flowSid: string, executionSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.flowSid = (payload.flow_sid); + this.executionSid = (payload.execution_sid); + this.parentStepSid = (payload.parent_step_sid); + this.name = (payload.name); + this.context = (payload.context); + this.transitionedFrom = (payload.transitioned_from); + this.transitionedTo = (payload.transitioned_to); + this.type = (payload.type); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { flowSid, executionSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the ExecutionStep resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStep resource. + */ + accountSid: string; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The SID of the Step\'s Execution resource. + */ + executionSid: string; + /** + * The SID of the parent Step. + */ + parentStepSid: string; + /** + * The event that caused the Flow to transition to the Step. + */ + name: string; + /** + * The current state of the Flow\'s Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + */ + context: any; + /** + * The Widget that preceded the Widget for the Step. + */ + transitionedFrom: string; + /** + * The Widget that will follow the Widget for the Step. + */ + transitionedTo: string; + /** + * The type of the widget that was executed. + */ + type: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): ExecutionStepContext { + this._context = this._context || new ExecutionStepContextImpl(this._version, this._solution.flowSid, this._solution.executionSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a ExecutionStepInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionStepInstance) => any): Promise<ExecutionStepInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ExecutionStepInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepInstance>) => any): Promise<ApiResponse<ExecutionStepInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the stepContext. + */ + stepContext(): ExecutionStepContextListInstance { + return this._proxy.stepContext; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + flowSid: this.flowSid, + executionSid: this.executionSid, + parentStepSid: this.parentStepSid, + name: this.name, + context: this.context, + transitionedFrom: this.transitionedFrom, + transitionedTo: this.transitionedTo, + type: this.type, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ExecutionStepSolution { + flowSid: string; + executionSid: string; +} + +export interface ExecutionStepListInstance { + _version: V2; + _solution: ExecutionStepSolution; + _uri: string; + + (sid: string, ): ExecutionStepContext; + get(sid: string, ): ExecutionStepContext; + + + + + + /** + * Streams ExecutionStepInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ExecutionStepInstance, done: (err?: Error) => void) => void): void; + each(params: ExecutionStepListInstanceEachOptions, callback?: (item: ExecutionStepInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ExecutionStepInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ExecutionStepInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ExecutionStepListInstanceEachOptions, callback?: (item: ExecutionStepInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ExecutionStepInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ExecutionStepPage) => any): Promise<ExecutionStepPage>; + /** + * Retrieve a single target page of ExecutionStepInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ExecutionStepPage>) => any): Promise<ApiResponse<ExecutionStepPage>>; + /** + * Lists ExecutionStepInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ExecutionStepInstance[]) => any): Promise<ExecutionStepInstance[]>; + list(params: ExecutionStepListInstanceOptions, callback?: (error: Error | null, items: ExecutionStepInstance[]) => any): Promise<ExecutionStepInstance[]>; + /** + * Lists ExecutionStepInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ExecutionStepInstance[]>) => any): Promise<ApiResponse<ExecutionStepInstance[]>>; + listWithHttpInfo(params: ExecutionStepListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ExecutionStepInstance[]>) => any): Promise<ApiResponse<ExecutionStepInstance[]>>; + /** + * Retrieve a single page of ExecutionStepInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ExecutionStepPage) => any): Promise<ExecutionStepPage>; + page(params: ExecutionStepListInstancePageOptions, callback?: (error: Error | null, items: ExecutionStepPage) => any): Promise<ExecutionStepPage>; + /** + * Retrieve a single page of ExecutionStepInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ExecutionStepListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ExecutionStepPage>) => any): Promise<ApiResponse<ExecutionStepPage>>; + pageWithHttpInfo(params: ExecutionStepListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ExecutionStepPage>) => any): Promise<ApiResponse<ExecutionStepPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExecutionStepListInstance(version: V2, flowSid: string, executionSid: string): ExecutionStepListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ExecutionStepListInstance; + + instance.get = function get(sid, ): ExecutionStepContext { + return new ExecutionStepContextImpl(version, flowSid, executionSid, sid); + } + + instance._version = version; + instance._solution = { flowSid, executionSid, }; + instance._uri = `/Flows/${flowSid}/Executions/${executionSid}/Steps`; + + instance.page = function page(params?: ExecutionStepListInstancePageOptions | ((error: Error | null, items: ExecutionStepPage) => any), callback?: (error: Error | null, items: ExecutionStepPage) => any): Promise<ExecutionStepPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ExecutionStepPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ExecutionStepPage) => any): Promise<ExecutionStepPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ExecutionStepPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ExecutionStepListInstancePageOptions | ((error: Error | null, items: ApiResponse<ExecutionStepPage>) => any), callback?: (error: Error | null, items: ApiResponse<ExecutionStepPage>) => any): Promise<ApiResponse<ExecutionStepPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ExecutionStepPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ExecutionStepPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ExecutionStepPage>) => any): Promise<ApiResponse<ExecutionStepPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ExecutionStepPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ExecutionStepPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ExecutionStepPage extends Page<V2, ExecutionStepPayload, ExecutionStepResource, ExecutionStepInstance> { +/** +* Initialize the ExecutionStepPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: ExecutionStepSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ExecutionStepInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ExecutionStepResource): ExecutionStepInstance { + + return new ExecutionStepInstance( + this._version, + payload, + this._solution.flowSid, + this._solution.executionSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/studio/v2/flow/execution/executionStep/executionStepContext.ts b/rest/studio/v2/flow/execution/executionStep/executionStepContext.ts new file mode 100644 index 000000000..3d499a242 --- /dev/null +++ b/rest/studio/v2/flow/execution/executionStep/executionStepContext.ts @@ -0,0 +1,294 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../../../V2"; +const deserialize = require("../../../../../../base/deserialize"); +const serialize = require("../../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../../base/utility"; +import { ApiResponse } from "../../../../../../base/ApiResponse"; + + + + +export interface ExecutionStepContextContext { + + /** + * Fetch a ExecutionStepContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepContextInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionStepContextInstance) => any): Promise<ExecutionStepContextInstance> + + /** + * Fetch a ExecutionStepContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepContextInstance>) => any): Promise<ApiResponse<ExecutionStepContextInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ExecutionStepContextContextSolution { + "flowSid": string; + "executionSid": string; + "stepSid": string; +} + +export class ExecutionStepContextContextImpl implements ExecutionStepContextContext { + protected _solution: ExecutionStepContextContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, flowSid: string, executionSid: string, stepSid: string) { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + if (!isValidPathParam(stepSid)) { + throw new Error('Parameter \'stepSid\' is not valid.'); + } + + this._solution = { flowSid, executionSid, stepSid, }; + this._uri = `/Flows/${flowSid}/Executions/${executionSid}/Steps/${stepSid}/Context`; + } + + fetch(callback?: (error: Error | null, item?: ExecutionStepContextInstance) => any): Promise<ExecutionStepContextInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ExecutionStepContextInstance(operationVersion, payload, instance._solution.flowSid, instance._solution.executionSid, instance._solution.stepSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepContextInstance>) => any): Promise<ApiResponse<ExecutionStepContextInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ExecutionStepContextResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ExecutionStepContextInstance> => ({ + ...response, + body: new ExecutionStepContextInstance(operationVersion, response.body, instance._solution.flowSid, instance._solution.executionSid, instance._solution.stepSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ExecutionStepContextPayload extends ExecutionStepContextResource {} + +interface ExecutionStepContextResource { + account_sid: string; + context: any; + execution_sid: string; + flow_sid: string; + step_sid: string; + url: string; +} + +export class ExecutionStepContextInstance { + protected _solution: ExecutionStepContextContextSolution; + protected _context?: ExecutionStepContextContext; + + constructor(protected _version: V2, payload: ExecutionStepContextResource, flowSid: string, executionSid: string, stepSid: string) { + + this.accountSid = (payload.account_sid); + this.context = (payload.context); + this.executionSid = (payload.execution_sid); + this.flowSid = (payload.flow_sid); + this.stepSid = (payload.step_sid); + this.url = (payload.url); + + this._solution = { flowSid, executionSid, stepSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStepContext resource. + */ + accountSid: string; + /** + * The current state of the Flow\'s Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + */ + context: any; + /** + * The SID of the context\'s Execution resource. + */ + executionSid: string; + /** + * The SID of the Flow. + */ + flowSid: string; + /** + * The SID of the Step that the context is associated with. + */ + stepSid: string; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): ExecutionStepContextContext { + this._context = this._context || new ExecutionStepContextContextImpl(this._version, this._solution.flowSid, this._solution.executionSid, this._solution.stepSid); + return this._context; + } + + /** + * Fetch a ExecutionStepContextInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepContextInstance + */ + fetch(callback?: (error: Error | null, item?: ExecutionStepContextInstance) => any): Promise<ExecutionStepContextInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ExecutionStepContextInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ExecutionStepContextInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ExecutionStepContextInstance>) => any): Promise<ApiResponse<ExecutionStepContextInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + context: this.context, + executionSid: this.executionSid, + flowSid: this.flowSid, + stepSid: this.stepSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ExecutionStepContextSolution { + flowSid: string; + executionSid: string; + stepSid: string; +} + +export interface ExecutionStepContextListInstance { + _version: V2; + _solution: ExecutionStepContextSolution; + _uri: string; + + (): ExecutionStepContextContext; + get(): ExecutionStepContextContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ExecutionStepContextListInstance(version: V2, flowSid: string, executionSid: string, stepSid: string): ExecutionStepContextListInstance { + if (!isValidPathParam(flowSid)) { + throw new Error('Parameter \'flowSid\' is not valid.'); + } + + if (!isValidPathParam(executionSid)) { + throw new Error('Parameter \'executionSid\' is not valid.'); + } + + if (!isValidPathParam(stepSid)) { + throw new Error('Parameter \'stepSid\' is not valid.'); + } + + const instance = (() => instance.get()) as ExecutionStepContextListInstance; + + instance.get = function get(): ExecutionStepContextContext { + return new ExecutionStepContextContextImpl(version, flowSid, executionSid, stepSid); + } + + instance._version = version; + instance._solution = { flowSid, executionSid, stepSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/studio/v2/flow/flowRevision.ts b/rest/studio/v2/flow/flowRevision.ts new file mode 100644 index 000000000..ed99ebc9c --- /dev/null +++ b/rest/studio/v2/flow/flowRevision.ts @@ -0,0 +1,613 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The status of the Flow. Can be: `draft` or `published`. + */ +export type FlowRevisionStatus = 'draft'|'published'; + + + +/** + * Options to pass to each + */ +export interface FlowRevisionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: FlowRevisionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface FlowRevisionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface FlowRevisionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface FlowRevisionContext { + + /** + * Fetch a FlowRevisionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowRevisionInstance + */ + fetch(callback?: (error: Error | null, item?: FlowRevisionInstance) => any): Promise<FlowRevisionInstance> + + /** + * Fetch a FlowRevisionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowRevisionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowRevisionInstance>) => any): Promise<ApiResponse<FlowRevisionInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FlowRevisionContextSolution { + "sid": string; + "revision": string; +} + +export class FlowRevisionContextImpl implements FlowRevisionContext { + protected _solution: FlowRevisionContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string, revision: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + if (!isValidPathParam(revision)) { + throw new Error('Parameter \'revision\' is not valid.'); + } + + this._solution = { sid, revision, }; + this._uri = `/Flows/${sid}/Revisions/${revision}`; + } + + fetch(callback?: (error: Error | null, item?: FlowRevisionInstance) => any): Promise<FlowRevisionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FlowRevisionInstance(operationVersion, payload, instance._solution.sid, instance._solution.revision)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowRevisionInstance>) => any): Promise<ApiResponse<FlowRevisionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<FlowRevisionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<FlowRevisionInstance> => ({ + ...response, + body: new FlowRevisionInstance(operationVersion, response.body, instance._solution.sid, instance._solution.revision) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FlowRevisionPayload extends TwilioResponsePayload { + revisions: FlowRevisionResource[]; +} + +interface FlowRevisionResource { + sid: string; + account_sid: string; + author_sid: string; + friendly_name: string; + definition: any; + status: FlowRevisionStatus; + revision: number; + commit_message: string; + valid: boolean; + errors: Array<any>; + date_created: Date; + date_updated: Date; + url: string; +} + +export class FlowRevisionInstance { + protected _solution: FlowRevisionContextSolution; + protected _context?: FlowRevisionContext; + + constructor(protected _version: V2, payload: FlowRevisionResource, sid: string, revision?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.authorSid = (payload.author_sid); + this.friendlyName = (payload.friendly_name); + this.definition = (payload.definition); + this.status = payload.status; + this.revision = deserialize.integer(payload.revision); + this.commitMessage = (payload.commit_message); + this.valid = (payload.valid); + this.errors = (payload.errors); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid, revision: revision.toString(), }; + } + + /** + * The unique string that we created to identify the Flow resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + */ + accountSid: string; + /** + * The SID of the User that created or last updated the Flow. + */ + authorSid: string; + /** + * The string that you assigned to describe the Flow. + */ + friendlyName: string; + /** + * JSON representation of flow definition. + */ + definition: any; + status: FlowRevisionStatus; + /** + * The latest revision number of the Flow\'s definition. + */ + revision: number; + /** + * Description of change made in the revision. + */ + commitMessage: string; + /** + * Boolean if the flow definition is valid. + */ + valid: boolean; + /** + * List of error in the flow definition. + */ + errors: Array<any>; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): FlowRevisionContext { + this._context = this._context || new FlowRevisionContextImpl(this._version, this._solution.sid, this._solution.revision); + return this._context; + } + + /** + * Fetch a FlowRevisionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowRevisionInstance + */ + fetch(callback?: (error: Error | null, item?: FlowRevisionInstance) => any): Promise<FlowRevisionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FlowRevisionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowRevisionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowRevisionInstance>) => any): Promise<ApiResponse<FlowRevisionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + authorSid: this.authorSid, + friendlyName: this.friendlyName, + definition: this.definition, + status: this.status, + revision: this.revision, + commitMessage: this.commitMessage, + valid: this.valid, + errors: this.errors, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FlowRevisionSolution { + sid: string; +} + +export interface FlowRevisionListInstance { + _version: V2; + _solution: FlowRevisionSolution; + _uri: string; + + (revision: string, ): FlowRevisionContext; + get(revision: string, ): FlowRevisionContext; + + + + + + /** + * Streams FlowRevisionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowRevisionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: FlowRevisionInstance, done: (err?: Error) => void) => void): void; + each(params: FlowRevisionListInstanceEachOptions, callback?: (item: FlowRevisionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams FlowRevisionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowRevisionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: FlowRevisionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: FlowRevisionListInstanceEachOptions, callback?: (item: FlowRevisionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of FlowRevisionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: FlowRevisionPage) => any): Promise<FlowRevisionPage>; + /** + * Retrieve a single target page of FlowRevisionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<FlowRevisionPage>) => any): Promise<ApiResponse<FlowRevisionPage>>; + /** + * Lists FlowRevisionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowRevisionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: FlowRevisionInstance[]) => any): Promise<FlowRevisionInstance[]>; + list(params: FlowRevisionListInstanceOptions, callback?: (error: Error | null, items: FlowRevisionInstance[]) => any): Promise<FlowRevisionInstance[]>; + /** + * Lists FlowRevisionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowRevisionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FlowRevisionInstance[]>) => any): Promise<ApiResponse<FlowRevisionInstance[]>>; + listWithHttpInfo(params: FlowRevisionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<FlowRevisionInstance[]>) => any): Promise<ApiResponse<FlowRevisionInstance[]>>; + /** + * Retrieve a single page of FlowRevisionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowRevisionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: FlowRevisionPage) => any): Promise<FlowRevisionPage>; + page(params: FlowRevisionListInstancePageOptions, callback?: (error: Error | null, items: FlowRevisionPage) => any): Promise<FlowRevisionPage>; + /** + * Retrieve a single page of FlowRevisionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FlowRevisionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FlowRevisionPage>) => any): Promise<ApiResponse<FlowRevisionPage>>; + pageWithHttpInfo(params: FlowRevisionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<FlowRevisionPage>) => any): Promise<ApiResponse<FlowRevisionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FlowRevisionListInstance(version: V2, sid: string): FlowRevisionListInstance { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + const instance = ((revision, ) => instance.get(revision, )) as FlowRevisionListInstance; + + instance.get = function get(revision, ): FlowRevisionContext { + return new FlowRevisionContextImpl(version, sid, revision); + } + + instance._version = version; + instance._solution = { sid, }; + instance._uri = `/Flows/${sid}/Revisions`; + + instance.page = function page(params?: FlowRevisionListInstancePageOptions | ((error: Error | null, items: FlowRevisionPage) => any), callback?: (error: Error | null, items: FlowRevisionPage) => any): Promise<FlowRevisionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new FlowRevisionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: FlowRevisionPage) => any): Promise<FlowRevisionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new FlowRevisionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: FlowRevisionListInstancePageOptions | ((error: Error | null, items: ApiResponse<FlowRevisionPage>) => any), callback?: (error: Error | null, items: ApiResponse<FlowRevisionPage>) => any): Promise<ApiResponse<FlowRevisionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<FlowRevisionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FlowRevisionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<FlowRevisionPage>) => any): Promise<ApiResponse<FlowRevisionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<FlowRevisionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FlowRevisionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class FlowRevisionPage extends Page<V2, FlowRevisionPayload, FlowRevisionResource, FlowRevisionInstance> { +/** +* Initialize the FlowRevisionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: FlowRevisionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of FlowRevisionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: FlowRevisionResource): FlowRevisionInstance { + + return new FlowRevisionInstance( + this._version, + payload, + this._solution.sid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/studio/v2/flow/flowTestUser.ts b/rest/studio/v2/flow/flowTestUser.ts new file mode 100644 index 000000000..eb8881408 --- /dev/null +++ b/rest/studio/v2/flow/flowTestUser.ts @@ -0,0 +1,384 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a FlowTestUserInstance + */ +export interface FlowTestUserContextUpdateOptions { + /** List of test user identities that can test draft versions of the flow. */ + "testUsers": Array<string>; +} + +export interface FlowTestUserContext { + + /** + * Fetch a FlowTestUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowTestUserInstance + */ + fetch(callback?: (error: Error | null, item?: FlowTestUserInstance) => any): Promise<FlowTestUserInstance> + + /** + * Fetch a FlowTestUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowTestUserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowTestUserInstance>) => any): Promise<ApiResponse<FlowTestUserInstance>> + + /** + * Update a FlowTestUserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowTestUserInstance + */ + update(params: FlowTestUserContextUpdateOptions, callback?: (error: Error | null, item?: FlowTestUserInstance) => any): Promise<FlowTestUserInstance>; + + /** + * Update a FlowTestUserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowTestUserInstance with HTTP metadata + */ + updateWithHttpInfo(params: FlowTestUserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FlowTestUserInstance>) => any): Promise<ApiResponse<FlowTestUserInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FlowTestUserContextSolution { + "sid": string; +} + +export class FlowTestUserContextImpl implements FlowTestUserContext { + protected _solution: FlowTestUserContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Flows/${sid}/TestUsers`; + } + + fetch(callback?: (error: Error | null, item?: FlowTestUserInstance) => any): Promise<FlowTestUserInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FlowTestUserInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowTestUserInstance>) => any): Promise<ApiResponse<FlowTestUserInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<FlowTestUserResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<FlowTestUserInstance> => ({ + ...response, + body: new FlowTestUserInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: FlowTestUserContextUpdateOptions,callback?: (error: Error | null, item?: FlowTestUserInstance) => any): Promise<FlowTestUserInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["testUsers"] === null || params["testUsers"] === undefined) { + throw new Error('Required parameter "params[\'testUsers\']" missing.'); + } + + let data: any = {}; + + + + data["TestUsers"] = serialize.map(params["testUsers"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FlowTestUserInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: FlowTestUserContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<FlowTestUserInstance>) => any): Promise<ApiResponse<FlowTestUserInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["testUsers"] === null || params["testUsers"] === undefined) { + throw new Error('Required parameter "params[\'testUsers\']" missing.'); + } + + let data: any = {}; + + + + data["TestUsers"] = serialize.map(params["testUsers"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<FlowTestUserResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<FlowTestUserInstance> => ({ + ...response, + body: new FlowTestUserInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FlowTestUserPayload extends FlowTestUserResource {} + +interface FlowTestUserResource { + sid: string; + test_users: Array<string>; + url: string; +} + +export class FlowTestUserInstance { + protected _solution: FlowTestUserContextSolution; + protected _context?: FlowTestUserContext; + + constructor(protected _version: V2, payload: FlowTestUserResource, sid: string) { + + this.sid = (payload.sid); + this.testUsers = (payload.test_users); + this.url = (payload.url); + + this._solution = { sid, }; + } + + /** + * Unique identifier of the flow. + */ + sid: string; + /** + * List of test user identities that can test draft versions of the flow. + */ + testUsers: Array<string>; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): FlowTestUserContext { + this._context = this._context || new FlowTestUserContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a FlowTestUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowTestUserInstance + */ + fetch(callback?: (error: Error | null, item?: FlowTestUserInstance) => any): Promise<FlowTestUserInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FlowTestUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowTestUserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FlowTestUserInstance>) => any): Promise<ApiResponse<FlowTestUserInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a FlowTestUserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowTestUserInstance + */ + update(params: FlowTestUserContextUpdateOptions, callback?: (error: Error | null, item?: FlowTestUserInstance) => any): Promise<FlowTestUserInstance>; + + update(params?: any, callback?: (error: Error | null, item?: FlowTestUserInstance) => any): Promise<FlowTestUserInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a FlowTestUserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowTestUserInstance with HTTP metadata + */ + updateWithHttpInfo(params: FlowTestUserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FlowTestUserInstance>) => any): Promise<ApiResponse<FlowTestUserInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<FlowTestUserInstance>) => any): Promise<ApiResponse<FlowTestUserInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + testUsers: this.testUsers, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FlowTestUserSolution { + sid: string; +} + +export interface FlowTestUserListInstance { + _version: V2; + _solution: FlowTestUserSolution; + _uri: string; + + (): FlowTestUserContext; + get(): FlowTestUserContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FlowTestUserListInstance(version: V2, sid: string): FlowTestUserListInstance { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + const instance = (() => instance.get()) as FlowTestUserListInstance; + + instance.get = function get(): FlowTestUserContext { + return new FlowTestUserContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { sid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/studio/v2/flowValidate.ts b/rest/studio/v2/flowValidate.ts new file mode 100644 index 000000000..3498cc0f6 --- /dev/null +++ b/rest/studio/v2/flowValidate.ts @@ -0,0 +1,234 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Studio + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The status of the Flow. Can be: `draft` or `published`. + */ +export type FlowValidateStatus = 'draft'|'published'; + + +/** + * Options to pass to update a FlowValidateInstance + */ +export interface FlowValidateListInstanceUpdateOptions { + /** The string that you assigned to describe the Flow. */ + "friendlyName": string; + /** */ + "status": FlowValidateStatus; + /** JSON representation of flow definition. */ + "definition": any; + /** Description of change made in the revision. */ + "commitMessage"?: string; +} + + +export interface FlowValidateSolution { +} + +export interface FlowValidateListInstance { + _version: V2; + _solution: FlowValidateSolution; + _uri: string; + + + + /** + * Update a FlowValidateInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowValidateInstance + */ + update(params: FlowValidateListInstanceUpdateOptions, callback?: (error: Error | null, item?: FlowValidateInstance) => any): Promise<FlowValidateInstance>; + + /** + * Update a FlowValidateInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FlowValidateInstance with HTTP metadata + */ + updateWithHttpInfo(params: FlowValidateListInstanceUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FlowValidateInstance>) => any): Promise<ApiResponse<FlowValidateInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FlowValidateListInstance(version: V2): FlowValidateListInstance { + const instance = {} as FlowValidateListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Flows/Validate`; + + instance.update = function update(params: FlowValidateListInstanceUpdateOptions, callback?: (error: Error | null, items: FlowValidateInstance) => any): Promise<FlowValidateInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + if (params["definition"] === null || params["definition"] === undefined) { + throw new Error('Required parameter "params[\'definition\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Status"] = params["status"]; + + data["Definition"] = serialize.object(params["definition"]); + if (params["commitMessage"] !== undefined) + data["CommitMessage"] = params["commitMessage"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FlowValidateInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.updateWithHttpInfo = function updateWithHttpInfo(params: FlowValidateListInstanceUpdateOptions, callback?: (error: Error | null, items: ApiResponse<FlowValidateInstance>) => any): Promise<ApiResponse<FlowValidateInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + if (params["definition"] === null || params["definition"] === undefined) { + throw new Error('Required parameter "params[\'definition\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Status"] = params["status"]; + + data["Definition"] = serialize.object(params["definition"]); + if (params["commitMessage"] !== undefined) + data["CommitMessage"] = params["commitMessage"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<FlowValidateResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<FlowValidateInstance> => ({ + ...response, + body: new FlowValidateInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface FlowValidatePayload extends FlowValidateResource {} + +interface FlowValidateResource { + valid: boolean; +} + +export class FlowValidateInstance { + + constructor(protected _version: V2, payload: FlowValidateResource) { + + this.valid = (payload.valid); + + } + + /** + * Boolean if the flow definition is valid. + */ + valid: boolean; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + valid: this.valid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/supersim/V1.ts b/rest/supersim/V1.ts new file mode 100644 index 000000000..10b8ffa6b --- /dev/null +++ b/rest/supersim/V1.ts @@ -0,0 +1,110 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import SupersimBase from "../SupersimBase"; +import Version from "../../base/Version"; +import { EsimProfileListInstance } from "./v1/esimProfile"; +import { FleetListInstance } from "./v1/fleet"; +import { IpCommandListInstance } from "./v1/ipCommand"; +import { NetworkListInstance } from "./v1/network"; +import { NetworkAccessProfileListInstance } from "./v1/networkAccessProfile"; +import { SettingsUpdateListInstance } from "./v1/settingsUpdate"; +import { SimListInstance } from "./v1/sim"; +import { SmsCommandListInstance } from "./v1/smsCommand"; +import { UsageRecordListInstance } from "./v1/usageRecord"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Supersim + * + * @param domain - The Twilio (Twilio.Supersim) domain + */ + constructor(domain: SupersimBase) { + super(domain, "v1"); + } + + /** esimProfiles - { Twilio.Supersim.V1.EsimProfileListInstance } resource */ + protected _esimProfiles?: EsimProfileListInstance; + /** fleets - { Twilio.Supersim.V1.FleetListInstance } resource */ + protected _fleets?: FleetListInstance; + /** ipCommands - { Twilio.Supersim.V1.IpCommandListInstance } resource */ + protected _ipCommands?: IpCommandListInstance; + /** networks - { Twilio.Supersim.V1.NetworkListInstance } resource */ + protected _networks?: NetworkListInstance; + /** networkAccessProfiles - { Twilio.Supersim.V1.NetworkAccessProfileListInstance } resource */ + protected _networkAccessProfiles?: NetworkAccessProfileListInstance; + /** settingsUpdates - { Twilio.Supersim.V1.SettingsUpdateListInstance } resource */ + protected _settingsUpdates?: SettingsUpdateListInstance; + /** sims - { Twilio.Supersim.V1.SimListInstance } resource */ + protected _sims?: SimListInstance; + /** smsCommands - { Twilio.Supersim.V1.SmsCommandListInstance } resource */ + protected _smsCommands?: SmsCommandListInstance; + /** usageRecords - { Twilio.Supersim.V1.UsageRecordListInstance } resource */ + protected _usageRecords?: UsageRecordListInstance; + + /** Getter for esimProfiles resource */ + get esimProfiles(): EsimProfileListInstance { + this._esimProfiles = this._esimProfiles || EsimProfileListInstance(this); + return this._esimProfiles; + } + + /** Getter for fleets resource */ + get fleets(): FleetListInstance { + this._fleets = this._fleets || FleetListInstance(this); + return this._fleets; + } + + /** Getter for ipCommands resource */ + get ipCommands(): IpCommandListInstance { + this._ipCommands = this._ipCommands || IpCommandListInstance(this); + return this._ipCommands; + } + + /** Getter for networks resource */ + get networks(): NetworkListInstance { + this._networks = this._networks || NetworkListInstance(this); + return this._networks; + } + + /** Getter for networkAccessProfiles resource */ + get networkAccessProfiles(): NetworkAccessProfileListInstance { + this._networkAccessProfiles = this._networkAccessProfiles || NetworkAccessProfileListInstance(this); + return this._networkAccessProfiles; + } + + /** Getter for settingsUpdates resource */ + get settingsUpdates(): SettingsUpdateListInstance { + this._settingsUpdates = this._settingsUpdates || SettingsUpdateListInstance(this); + return this._settingsUpdates; + } + + /** Getter for sims resource */ + get sims(): SimListInstance { + this._sims = this._sims || SimListInstance(this); + return this._sims; + } + + /** Getter for smsCommands resource */ + get smsCommands(): SmsCommandListInstance { + this._smsCommands = this._smsCommands || SmsCommandListInstance(this); + return this._smsCommands; + } + + /** Getter for usageRecords resource */ + get usageRecords(): UsageRecordListInstance { + this._usageRecords = this._usageRecords || UsageRecordListInstance(this); + return this._usageRecords; + } + +} diff --git a/rest/supersim/v1/esimProfile.ts b/rest/supersim/v1/esimProfile.ts new file mode 100644 index 000000000..528403248 --- /dev/null +++ b/rest/supersim/v1/esimProfile.ts @@ -0,0 +1,770 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The status of the eSIM Profile. Can be: `new`, `reserving`, `available`, `downloaded`, `installed` or `failed`. See the [eSIM Profile Status Values](https://www.twilio.com/docs/iot/supersim/api/esimprofile-resource#status-values) for a description of each. + */ +export type EsimProfileStatus = 'new'|'reserving'|'available'|'downloaded'|'installed'|'failed'; + + + +/** + * Options to pass to create a EsimProfileInstance + */ +export interface EsimProfileListInstanceCreateOptions { + /** The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. */ + "callbackUrl"?: string; + /** The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. */ + "callbackMethod"?: string; + /** When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. */ + "generateMatchingId"?: boolean; + /** Identifier of the eUICC that will claim the eSIM Profile. */ + "eid"?: string; +} + +/** + * Options to pass to each + */ +export interface EsimProfileListInstanceEachOptions { + /** List the eSIM Profiles that have been associated with an EId. */ + "eid"?: string; + /** Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. */ + "simSid"?: string; + /** List the eSIM Profiles that are in a given status. */ + "status"?: EsimProfileStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EsimProfileInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EsimProfileListInstanceOptions { + /** List the eSIM Profiles that have been associated with an EId. */ + "eid"?: string; + /** Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. */ + "simSid"?: string; + /** List the eSIM Profiles that are in a given status. */ + "status"?: EsimProfileStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EsimProfileListInstancePageOptions { + /** List the eSIM Profiles that have been associated with an EId. */ + "eid"?: string; + /** Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. */ + "simSid"?: string; + /** List the eSIM Profiles that are in a given status. */ + "status"?: EsimProfileStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EsimProfileContext { + + /** + * Fetch a EsimProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EsimProfileInstance + */ + fetch(callback?: (error: Error | null, item?: EsimProfileInstance) => any): Promise<EsimProfileInstance> + + /** + * Fetch a EsimProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EsimProfileInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EsimProfileInstance>) => any): Promise<ApiResponse<EsimProfileInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EsimProfileContextSolution { + "sid": string; +} + +export class EsimProfileContextImpl implements EsimProfileContext { + protected _solution: EsimProfileContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/ESimProfiles/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: EsimProfileInstance) => any): Promise<EsimProfileInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EsimProfileInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EsimProfileInstance>) => any): Promise<ApiResponse<EsimProfileInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EsimProfileResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EsimProfileInstance> => ({ + ...response, + body: new EsimProfileInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EsimProfilePayload extends TwilioResponsePayload { + esim_profiles: EsimProfileResource[]; +} + +interface EsimProfileResource { + sid: string; + account_sid: string; + iccid: string; + sim_sid: string; + status: EsimProfileStatus; + eid: string; + smdp_plus_address: string; + matching_id: string; + activation_code: string; + error_code: string; + error_message: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class EsimProfileInstance { + protected _solution: EsimProfileContextSolution; + protected _context?: EsimProfileContext; + + constructor(protected _version: V1, payload: EsimProfileResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.iccid = (payload.iccid); + this.simSid = (payload.sim_sid); + this.status = payload.status; + this.eid = (payload.eid); + this.smdpPlusAddress = (payload.smdp_plus_address); + this.matchingId = (payload.matching_id); + this.activationCode = (payload.activation_code); + this.errorCode = (payload.error_code); + this.errorMessage = (payload.error_message); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the eSIM Profile resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the eSIM Profile resource belongs. + */ + accountSid: string; + /** + * The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with the Sim resource. + */ + iccid: string; + /** + * The SID of the [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource that this eSIM Profile controls. + */ + simSid: string; + status: EsimProfileStatus; + /** + * Identifier of the eUICC that can claim the eSIM Profile. + */ + eid: string; + /** + * Address of the SM-DP+ server from which the Profile will be downloaded. The URL will appear once the eSIM Profile reaches the status `available`. + */ + smdpPlusAddress: string; + /** + * Unique identifier of the eSIM profile that can be used to identify and download the eSIM profile from the SM-DP+ server. Populated if `generate_matching_id` is set to `true` when creating the eSIM profile reservation. + */ + matchingId: string; + /** + * Combined machine-readable activation code for acquiring an eSIM Profile with the Activation Code download method. Can be used in a QR code to download an eSIM profile. + */ + activationCode: string; + /** + * Code indicating the failure if the download of the SIM Profile failed and the eSIM Profile is in `failed` state. + */ + errorCode: string; + /** + * Error message describing the failure if the download of the SIM Profile failed and the eSIM Profile is in `failed` state. + */ + errorMessage: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the eSIM Profile resource. + */ + url: string; + + private get _proxy(): EsimProfileContext { + this._context = this._context || new EsimProfileContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a EsimProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EsimProfileInstance + */ + fetch(callback?: (error: Error | null, item?: EsimProfileInstance) => any): Promise<EsimProfileInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EsimProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EsimProfileInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EsimProfileInstance>) => any): Promise<ApiResponse<EsimProfileInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + iccid: this.iccid, + simSid: this.simSid, + status: this.status, + eid: this.eid, + smdpPlusAddress: this.smdpPlusAddress, + matchingId: this.matchingId, + activationCode: this.activationCode, + errorCode: this.errorCode, + errorMessage: this.errorMessage, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EsimProfileSolution { +} + +export interface EsimProfileListInstance { + _version: V1; + _solution: EsimProfileSolution; + _uri: string; + + (sid: string, ): EsimProfileContext; + get(sid: string, ): EsimProfileContext; + + + + + /** + * Create a EsimProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EsimProfileInstance + */ + create(callback?: (error: Error | null, item?: EsimProfileInstance) => any): Promise<EsimProfileInstance>; + /** + * Create a EsimProfileInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EsimProfileInstance + */ + create(params: EsimProfileListInstanceCreateOptions, callback?: (error: Error | null, item?: EsimProfileInstance) => any): Promise<EsimProfileInstance>; + + /** + * Create a EsimProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EsimProfileInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EsimProfileInstance>) => any): Promise<ApiResponse<EsimProfileInstance>>; + /** + * Create a EsimProfileInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EsimProfileInstance with HTTP metadata + */ + createWithHttpInfo(params: EsimProfileListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<EsimProfileInstance>) => any): Promise<ApiResponse<EsimProfileInstance>>; + + + + + /** + * Streams EsimProfileInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EsimProfileListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EsimProfileInstance, done: (err?: Error) => void) => void): void; + each(params: EsimProfileListInstanceEachOptions, callback?: (item: EsimProfileInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EsimProfileInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EsimProfileListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EsimProfileInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EsimProfileListInstanceEachOptions, callback?: (item: EsimProfileInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EsimProfileInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EsimProfilePage) => any): Promise<EsimProfilePage>; + /** + * Retrieve a single target page of EsimProfileInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EsimProfilePage>) => any): Promise<ApiResponse<EsimProfilePage>>; + /** + * Lists EsimProfileInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EsimProfileListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EsimProfileInstance[]) => any): Promise<EsimProfileInstance[]>; + list(params: EsimProfileListInstanceOptions, callback?: (error: Error | null, items: EsimProfileInstance[]) => any): Promise<EsimProfileInstance[]>; + /** + * Lists EsimProfileInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EsimProfileListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EsimProfileInstance[]>) => any): Promise<ApiResponse<EsimProfileInstance[]>>; + listWithHttpInfo(params: EsimProfileListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EsimProfileInstance[]>) => any): Promise<ApiResponse<EsimProfileInstance[]>>; + /** + * Retrieve a single page of EsimProfileInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EsimProfileListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EsimProfilePage) => any): Promise<EsimProfilePage>; + page(params: EsimProfileListInstancePageOptions, callback?: (error: Error | null, items: EsimProfilePage) => any): Promise<EsimProfilePage>; + /** + * Retrieve a single page of EsimProfileInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EsimProfileListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EsimProfilePage>) => any): Promise<ApiResponse<EsimProfilePage>>; + pageWithHttpInfo(params: EsimProfileListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EsimProfilePage>) => any): Promise<ApiResponse<EsimProfilePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EsimProfileListInstance(version: V1): EsimProfileListInstance { + const instance = ((sid, ) => instance.get(sid, )) as EsimProfileListInstance; + + instance.get = function get(sid, ): EsimProfileContext { + return new EsimProfileContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ESimProfiles`; + + instance.create = function create(params?: EsimProfileListInstanceCreateOptions | ((error: Error | null, items: EsimProfileInstance) => any), callback?: (error: Error | null, items: EsimProfileInstance) => any): Promise<EsimProfileInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["generateMatchingId"] !== undefined) + data["GenerateMatchingId"] = serialize.bool(params["generateMatchingId"]); + if (params["eid"] !== undefined) + data["Eid"] = params["eid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new EsimProfileInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: EsimProfileListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<EsimProfileInstance>) => any), callback?: (error: Error | null, items: ApiResponse<EsimProfileInstance>) => any): Promise<ApiResponse<EsimProfileInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["generateMatchingId"] !== undefined) + data["GenerateMatchingId"] = serialize.bool(params["generateMatchingId"]); + if (params["eid"] !== undefined) + data["Eid"] = params["eid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<EsimProfileResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<EsimProfileInstance> => ({ + ...response, + body: new EsimProfileInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: EsimProfileListInstancePageOptions | ((error: Error | null, items: EsimProfilePage) => any), callback?: (error: Error | null, items: EsimProfilePage) => any): Promise<EsimProfilePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["eid"] !== undefined) + data["Eid"] = params["eid"]; + if (params["simSid"] !== undefined) + data["SimSid"] = params["simSid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EsimProfilePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EsimProfilePage) => any): Promise<EsimProfilePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EsimProfilePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EsimProfileListInstancePageOptions | ((error: Error | null, items: ApiResponse<EsimProfilePage>) => any), callback?: (error: Error | null, items: ApiResponse<EsimProfilePage>) => any): Promise<ApiResponse<EsimProfilePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["eid"] !== undefined) + data["Eid"] = params["eid"]; + if (params["simSid"] !== undefined) + data["SimSid"] = params["simSid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EsimProfilePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EsimProfilePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EsimProfilePage>) => any): Promise<ApiResponse<EsimProfilePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EsimProfilePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EsimProfilePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EsimProfilePage extends Page<V1, EsimProfilePayload, EsimProfileResource, EsimProfileInstance> { +/** +* Initialize the EsimProfilePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: EsimProfileSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EsimProfileInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EsimProfileResource): EsimProfileInstance { + + return new EsimProfileInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/fleet.ts b/rest/supersim/v1/fleet.ts new file mode 100644 index 000000000..98828c053 --- /dev/null +++ b/rest/supersim/v1/fleet.ts @@ -0,0 +1,970 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The model by which a SIMs usage is metered and billed. Defaults to `payg`. + */ +export type FleetDataMetering = 'payg'; + + + +/** + * Options to pass to update a FleetInstance + */ +export interface FleetContextUpdateOptions { + /** An application-defined string that uniquely identifies the resource. It can be used in place of the resource\\\'s `sid` in the URL to address the resource. */ + "uniqueName"?: string; + /** The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet\\\'s SIMs can connect to. */ + "networkAccessProfile"?: string; + /** The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. */ + "ipCommandsUrl"?: string; + /** A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. */ + "ipCommandsMethod"?: string; + /** The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. */ + "smsCommandsUrl"?: string; + /** A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. */ + "smsCommandsMethod"?: string; + /** The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). */ + "dataLimit"?: number; +} + +/** + * Options to pass to create a FleetInstance + */ +export interface FleetListInstanceCreateOptions { + /** The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet\\\'s SIMs can connect to. */ + "networkAccessProfile": string; + /** An application-defined string that uniquely identifies the resource. It can be used in place of the resource\\\'s `sid` in the URL to address the resource. */ + "uniqueName"?: string; + /** Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. */ + "dataEnabled"?: boolean; + /** The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). */ + "dataLimit"?: number; + /** The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. */ + "ipCommandsUrl"?: string; + /** A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. */ + "ipCommandsMethod"?: string; + /** Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. */ + "smsCommandsEnabled"?: boolean; + /** The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. */ + "smsCommandsUrl"?: string; + /** A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. */ + "smsCommandsMethod"?: string; +} + +/** + * Options to pass to each + */ +export interface FleetListInstanceEachOptions { + /** The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet\'s SIMs can connect to. */ + "networkAccessProfile"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: FleetInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface FleetListInstanceOptions { + /** The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet\'s SIMs can connect to. */ + "networkAccessProfile"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface FleetListInstancePageOptions { + /** The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet\'s SIMs can connect to. */ + "networkAccessProfile"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface FleetContext { + + /** + * Fetch a FleetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance + */ + fetch(callback?: (error: Error | null, item?: FleetInstance) => any): Promise<FleetInstance> + + /** + * Fetch a FleetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>> + + /** + * Update a FleetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance + */ + update(callback?: (error: Error | null, item?: FleetInstance) => any): Promise<FleetInstance>; + /** + * Update a FleetInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance + */ + update(params: FleetContextUpdateOptions, callback?: (error: Error | null, item?: FleetInstance) => any): Promise<FleetInstance>; + + /** + * Update a FleetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>>; + /** + * Update a FleetInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance with HTTP metadata + */ + updateWithHttpInfo(params: FleetContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FleetContextSolution { + "sid": string; +} + +export class FleetContextImpl implements FleetContext { + protected _solution: FleetContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Fleets/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: FleetInstance) => any): Promise<FleetInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FleetInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<FleetResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<FleetInstance> => ({ + ...response, + body: new FleetInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: FleetContextUpdateOptions | ((error: Error | null, item?: FleetInstance) => any),callback?: (error: Error | null, item?: FleetInstance) => any): Promise<FleetInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["networkAccessProfile"] !== undefined) + data["NetworkAccessProfile"] = params["networkAccessProfile"]; + if (params["ipCommandsUrl"] !== undefined) + data["IpCommandsUrl"] = params["ipCommandsUrl"]; + if (params["ipCommandsMethod"] !== undefined) + data["IpCommandsMethod"] = params["ipCommandsMethod"]; + if (params["smsCommandsUrl"] !== undefined) + data["SmsCommandsUrl"] = params["smsCommandsUrl"]; + if (params["smsCommandsMethod"] !== undefined) + data["SmsCommandsMethod"] = params["smsCommandsMethod"]; + if (params["dataLimit"] !== undefined) + data["DataLimit"] = params["dataLimit"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FleetInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: FleetContextUpdateOptions | ((error: Error | null, item?: ApiResponse<FleetInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["networkAccessProfile"] !== undefined) + data["NetworkAccessProfile"] = params["networkAccessProfile"]; + if (params["ipCommandsUrl"] !== undefined) + data["IpCommandsUrl"] = params["ipCommandsUrl"]; + if (params["ipCommandsMethod"] !== undefined) + data["IpCommandsMethod"] = params["ipCommandsMethod"]; + if (params["smsCommandsUrl"] !== undefined) + data["SmsCommandsUrl"] = params["smsCommandsUrl"]; + if (params["smsCommandsMethod"] !== undefined) + data["SmsCommandsMethod"] = params["smsCommandsMethod"]; + if (params["dataLimit"] !== undefined) + data["DataLimit"] = params["dataLimit"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<FleetResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<FleetInstance> => ({ + ...response, + body: new FleetInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FleetPayload extends TwilioResponsePayload { + fleets: FleetResource[]; +} + +interface FleetResource { + account_sid: string; + sid: string; + unique_name: string; + date_created: Date; + date_updated: Date; + url: string; + data_enabled: boolean; + data_limit: number; + data_metering: FleetDataMetering; + sms_commands_enabled: boolean; + sms_commands_url: string; + sms_commands_method: string; + network_access_profile_sid: string; + ip_commands_url: string; + ip_commands_method: string; +} + +export class FleetInstance { + protected _solution: FleetContextSolution; + protected _context?: FleetContext; + + constructor(protected _version: V1, payload: FleetResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.dataEnabled = (payload.data_enabled); + this.dataLimit = deserialize.integer(payload.data_limit); + this.dataMetering = payload.data_metering; + this.smsCommandsEnabled = (payload.sms_commands_enabled); + this.smsCommandsUrl = (payload.sms_commands_url); + this.smsCommandsMethod = (payload.sms_commands_method); + this.networkAccessProfileSid = (payload.network_access_profile_sid); + this.ipCommandsUrl = (payload.ip_commands_url); + this.ipCommandsMethod = (payload.ip_commands_method); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Fleet resource. + */ + accountSid: string; + /** + * The unique string that we created to identify the Fleet resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. + */ + uniqueName: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Fleet resource. + */ + url: string; + /** + * Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + */ + dataEnabled: boolean; + /** + * The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 250MB. + */ + dataLimit: number; + dataMetering: FleetDataMetering; + /** + * Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `false`. + */ + smsCommandsEnabled: boolean; + /** + * The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + */ + smsCommandsUrl: string; + /** + * A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + */ + smsCommandsMethod: string; + /** + * The SID of the Network Access Profile that controls which cellular networks the Fleet\'s SIMs can connect to. + */ + networkAccessProfileSid: string; + /** + * The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + */ + ipCommandsUrl: string; + /** + * A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + */ + ipCommandsMethod: string; + + private get _proxy(): FleetContext { + this._context = this._context || new FleetContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a FleetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance + */ + fetch(callback?: (error: Error | null, item?: FleetInstance) => any): Promise<FleetInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FleetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a FleetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance + */ + update(callback?: (error: Error | null, item?: FleetInstance) => any): Promise<FleetInstance>; + /** + * Update a FleetInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance + */ + update(params: FleetContextUpdateOptions, callback?: (error: Error | null, item?: FleetInstance) => any): Promise<FleetInstance>; + + update(params?: any, callback?: (error: Error | null, item?: FleetInstance) => any): Promise<FleetInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a FleetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>>; + /** + * Update a FleetInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance with HTTP metadata + */ + updateWithHttpInfo(params: FleetContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + uniqueName: this.uniqueName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + dataEnabled: this.dataEnabled, + dataLimit: this.dataLimit, + dataMetering: this.dataMetering, + smsCommandsEnabled: this.smsCommandsEnabled, + smsCommandsUrl: this.smsCommandsUrl, + smsCommandsMethod: this.smsCommandsMethod, + networkAccessProfileSid: this.networkAccessProfileSid, + ipCommandsUrl: this.ipCommandsUrl, + ipCommandsMethod: this.ipCommandsMethod, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FleetSolution { +} + +export interface FleetListInstance { + _version: V1; + _solution: FleetSolution; + _uri: string; + + (sid: string, ): FleetContext; + get(sid: string, ): FleetContext; + + + + + + + /** + * Create a FleetInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance + */ + create(params: FleetListInstanceCreateOptions, callback?: (error: Error | null, item?: FleetInstance) => any): Promise<FleetInstance>; + + /** + * Create a FleetInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FleetInstance with HTTP metadata + */ + createWithHttpInfo(params: FleetListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>>; + + + + + /** + * Streams FleetInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FleetListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: FleetInstance, done: (err?: Error) => void) => void): void; + each(params: FleetListInstanceEachOptions, callback?: (item: FleetInstance, done: (err?: Error) => void) => void): void; + /** + * Streams FleetInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FleetListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: FleetInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: FleetListInstanceEachOptions, callback?: (item: FleetInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of FleetInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: FleetPage) => any): Promise<FleetPage>; + /** + * Retrieve a single target page of FleetInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<FleetPage>) => any): Promise<ApiResponse<FleetPage>>; + /** + * Lists FleetInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FleetListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: FleetInstance[]) => any): Promise<FleetInstance[]>; + list(params: FleetListInstanceOptions, callback?: (error: Error | null, items: FleetInstance[]) => any): Promise<FleetInstance[]>; + /** + * Lists FleetInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FleetListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FleetInstance[]>) => any): Promise<ApiResponse<FleetInstance[]>>; + listWithHttpInfo(params: FleetListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<FleetInstance[]>) => any): Promise<ApiResponse<FleetInstance[]>>; + /** + * Retrieve a single page of FleetInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FleetListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: FleetPage) => any): Promise<FleetPage>; + page(params: FleetListInstancePageOptions, callback?: (error: Error | null, items: FleetPage) => any): Promise<FleetPage>; + /** + * Retrieve a single page of FleetInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FleetListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FleetPage>) => any): Promise<ApiResponse<FleetPage>>; + pageWithHttpInfo(params: FleetListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<FleetPage>) => any): Promise<ApiResponse<FleetPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FleetListInstance(version: V1): FleetListInstance { + const instance = ((sid, ) => instance.get(sid, )) as FleetListInstance; + + instance.get = function get(sid, ): FleetContext { + return new FleetContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Fleets`; + + instance.create = function create(params: FleetListInstanceCreateOptions, callback?: (error: Error | null, items: FleetInstance) => any): Promise<FleetInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["networkAccessProfile"] === null || params["networkAccessProfile"] === undefined) { + throw new Error('Required parameter "params[\'networkAccessProfile\']" missing.'); + } + + let data: any = {}; + + + + data["NetworkAccessProfile"] = params["networkAccessProfile"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dataEnabled"] !== undefined) + data["DataEnabled"] = serialize.bool(params["dataEnabled"]); + if (params["dataLimit"] !== undefined) + data["DataLimit"] = params["dataLimit"]; + if (params["ipCommandsUrl"] !== undefined) + data["IpCommandsUrl"] = params["ipCommandsUrl"]; + if (params["ipCommandsMethod"] !== undefined) + data["IpCommandsMethod"] = params["ipCommandsMethod"]; + if (params["smsCommandsEnabled"] !== undefined) + data["SmsCommandsEnabled"] = serialize.bool(params["smsCommandsEnabled"]); + if (params["smsCommandsUrl"] !== undefined) + data["SmsCommandsUrl"] = params["smsCommandsUrl"]; + if (params["smsCommandsMethod"] !== undefined) + data["SmsCommandsMethod"] = params["smsCommandsMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FleetInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: FleetListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<FleetInstance>) => any): Promise<ApiResponse<FleetInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["networkAccessProfile"] === null || params["networkAccessProfile"] === undefined) { + throw new Error('Required parameter "params[\'networkAccessProfile\']" missing.'); + } + + let data: any = {}; + + + + data["NetworkAccessProfile"] = params["networkAccessProfile"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dataEnabled"] !== undefined) + data["DataEnabled"] = serialize.bool(params["dataEnabled"]); + if (params["dataLimit"] !== undefined) + data["DataLimit"] = params["dataLimit"]; + if (params["ipCommandsUrl"] !== undefined) + data["IpCommandsUrl"] = params["ipCommandsUrl"]; + if (params["ipCommandsMethod"] !== undefined) + data["IpCommandsMethod"] = params["ipCommandsMethod"]; + if (params["smsCommandsEnabled"] !== undefined) + data["SmsCommandsEnabled"] = serialize.bool(params["smsCommandsEnabled"]); + if (params["smsCommandsUrl"] !== undefined) + data["SmsCommandsUrl"] = params["smsCommandsUrl"]; + if (params["smsCommandsMethod"] !== undefined) + data["SmsCommandsMethod"] = params["smsCommandsMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<FleetResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<FleetInstance> => ({ + ...response, + body: new FleetInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: FleetListInstancePageOptions | ((error: Error | null, items: FleetPage) => any), callback?: (error: Error | null, items: FleetPage) => any): Promise<FleetPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["networkAccessProfile"] !== undefined) + data["NetworkAccessProfile"] = params["networkAccessProfile"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new FleetPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: FleetPage) => any): Promise<FleetPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new FleetPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: FleetListInstancePageOptions | ((error: Error | null, items: ApiResponse<FleetPage>) => any), callback?: (error: Error | null, items: ApiResponse<FleetPage>) => any): Promise<ApiResponse<FleetPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["networkAccessProfile"] !== undefined) + data["NetworkAccessProfile"] = params["networkAccessProfile"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<FleetPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FleetPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<FleetPage>) => any): Promise<ApiResponse<FleetPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<FleetPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FleetPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class FleetPage extends Page<V1, FleetPayload, FleetResource, FleetInstance> { +/** +* Initialize the FleetPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: FleetSolution) { + super(version, response, solution); + } + + /** + * Build an instance of FleetInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: FleetResource): FleetInstance { + + return new FleetInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/ipCommand.ts b/rest/supersim/v1/ipCommand.ts new file mode 100644 index 000000000..ea1ff1e97 --- /dev/null +++ b/rest/supersim/v1/ipCommand.ts @@ -0,0 +1,791 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Either `to_sim` or `from_sim`. Indicates whether the IP Command resource was sent from or to the Super SIM. + */ +export type IpCommandDirection = 'to_sim'|'from_sim'; + +/** + * Either “text” or “binary”. For an IP Command sent to a Super SIM, `payload_type` is configurable. For an IP Command sent from a Super SIM, `payload_type` is always “binary”. + */ +export type IpCommandPayloadType = 'text'|'binary'; + +/** + * The delivery status of the IP Command. This is one of the following: “queued”, “sent”, “failed” or “received”. + */ +export type IpCommandStatus = 'queued'|'sent'|'received'|'failed'; + + + +/** + * Options to pass to create a IpCommandInstance + */ +export interface IpCommandListInstanceCreateOptions { + /** The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. */ + "sim": string; + /** The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. */ + "payload": string; + /** The device port to which the IP Command will be sent. */ + "devicePort": number; + /** */ + "payloadType"?: IpCommandPayloadType; + /** The URL we should call using the `callback_method` after we have sent the IP Command. */ + "callbackUrl"?: string; + /** The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. */ + "callbackMethod"?: string; +} + +/** + * Options to pass to each + */ +export interface IpCommandListInstanceEachOptions { + /** The SID or unique name of the Sim resource that IP Command was sent to or from. */ + "sim"?: string; + /** The ICCID of the Sim resource that IP Command was sent to or from. */ + "simIccid"?: string; + /** The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. */ + "status"?: IpCommandStatus; + /** The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. */ + "direction"?: IpCommandDirection; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: IpCommandInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface IpCommandListInstanceOptions { + /** The SID or unique name of the Sim resource that IP Command was sent to or from. */ + "sim"?: string; + /** The ICCID of the Sim resource that IP Command was sent to or from. */ + "simIccid"?: string; + /** The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. */ + "status"?: IpCommandStatus; + /** The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. */ + "direction"?: IpCommandDirection; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface IpCommandListInstancePageOptions { + /** The SID or unique name of the Sim resource that IP Command was sent to or from. */ + "sim"?: string; + /** The ICCID of the Sim resource that IP Command was sent to or from. */ + "simIccid"?: string; + /** The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. */ + "status"?: IpCommandStatus; + /** The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. */ + "direction"?: IpCommandDirection; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface IpCommandContext { + + /** + * Fetch a IpCommandInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpCommandInstance + */ + fetch(callback?: (error: Error | null, item?: IpCommandInstance) => any): Promise<IpCommandInstance> + + /** + * Fetch a IpCommandInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpCommandInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpCommandInstance>) => any): Promise<ApiResponse<IpCommandInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface IpCommandContextSolution { + "sid": string; +} + +export class IpCommandContextImpl implements IpCommandContext { + protected _solution: IpCommandContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/IpCommands/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: IpCommandInstance) => any): Promise<IpCommandInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new IpCommandInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpCommandInstance>) => any): Promise<ApiResponse<IpCommandInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<IpCommandResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<IpCommandInstance> => ({ + ...response, + body: new IpCommandInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface IpCommandPayload extends TwilioResponsePayload { + ip_commands: IpCommandResource[]; +} + +interface IpCommandResource { + sid: string; + account_sid: string; + sim_sid: string; + sim_iccid: string; + status: IpCommandStatus; + direction: IpCommandDirection; + device_ip: string; + device_port: number; + payload_type: IpCommandPayloadType; + payload: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class IpCommandInstance { + protected _solution: IpCommandContextSolution; + protected _context?: IpCommandContext; + + constructor(protected _version: V1, payload: IpCommandResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.simSid = (payload.sim_sid); + this.simIccid = (payload.sim_iccid); + this.status = payload.status; + this.direction = payload.direction; + this.deviceIp = (payload.device_ip); + this.devicePort = deserialize.integer(payload.device_port); + this.payloadType = payload.payload_type; + this.payload = (payload.payload); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the IP Command resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IP Command resource. + */ + accountSid: string; + /** + * The SID of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) that this IP Command was sent to or from. + */ + simSid: string; + /** + * The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) that this IP Command was sent to or from. + */ + simIccid: string; + status: IpCommandStatus; + direction: IpCommandDirection; + /** + * The IP address of the device that the IP Command was sent to or received from. For an IP Command sent to a Super SIM, `device_ip` starts out as `null`, and once the IP Command is “sent”, the `device_ip` will be filled out. An IP Command sent from a Super SIM have its `device_ip` always set. + */ + deviceIp: string; + /** + * For an IP Command sent to a Super SIM, it would be the destination port of the IP message. For an IP Command sent from a Super SIM, it would be the source port of the IP message. + */ + devicePort: number; + payloadType: IpCommandPayloadType; + /** + * The payload that is carried in the IP/UDP message. The payload can be encoded in either text or binary format. For text payload, UTF-8 encoding must be used. For an IP Command sent to a Super SIM, the payload is appended to the IP/UDP message “as is”. The payload should not exceed 1300 bytes. For an IP Command sent from a Super SIM, the payload from the received IP/UDP message is extracted and sent in binary encoding. For an IP Command sent from a Super SIM, the payload should not exceed 1300 bytes. If it is larger than 1300 bytes, there might be fragmentation on the upstream and the message may appear truncated. + */ + payload: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the IP Command resource. + */ + url: string; + + private get _proxy(): IpCommandContext { + this._context = this._context || new IpCommandContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a IpCommandInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpCommandInstance + */ + fetch(callback?: (error: Error | null, item?: IpCommandInstance) => any): Promise<IpCommandInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a IpCommandInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpCommandInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpCommandInstance>) => any): Promise<ApiResponse<IpCommandInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + simSid: this.simSid, + simIccid: this.simIccid, + status: this.status, + direction: this.direction, + deviceIp: this.deviceIp, + devicePort: this.devicePort, + payloadType: this.payloadType, + payload: this.payload, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface IpCommandSolution { +} + +export interface IpCommandListInstance { + _version: V1; + _solution: IpCommandSolution; + _uri: string; + + (sid: string, ): IpCommandContext; + get(sid: string, ): IpCommandContext; + + + + + /** + * Create a IpCommandInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpCommandInstance + */ + create(params: IpCommandListInstanceCreateOptions, callback?: (error: Error | null, item?: IpCommandInstance) => any): Promise<IpCommandInstance>; + + /** + * Create a IpCommandInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpCommandInstance with HTTP metadata + */ + createWithHttpInfo(params: IpCommandListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<IpCommandInstance>) => any): Promise<ApiResponse<IpCommandInstance>>; + + + + + /** + * Streams IpCommandInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpCommandListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: IpCommandInstance, done: (err?: Error) => void) => void): void; + each(params: IpCommandListInstanceEachOptions, callback?: (item: IpCommandInstance, done: (err?: Error) => void) => void): void; + /** + * Streams IpCommandInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpCommandListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: IpCommandInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: IpCommandListInstanceEachOptions, callback?: (item: IpCommandInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of IpCommandInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: IpCommandPage) => any): Promise<IpCommandPage>; + /** + * Retrieve a single target page of IpCommandInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<IpCommandPage>) => any): Promise<ApiResponse<IpCommandPage>>; + /** + * Lists IpCommandInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpCommandListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: IpCommandInstance[]) => any): Promise<IpCommandInstance[]>; + list(params: IpCommandListInstanceOptions, callback?: (error: Error | null, items: IpCommandInstance[]) => any): Promise<IpCommandInstance[]>; + /** + * Lists IpCommandInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpCommandListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<IpCommandInstance[]>) => any): Promise<ApiResponse<IpCommandInstance[]>>; + listWithHttpInfo(params: IpCommandListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<IpCommandInstance[]>) => any): Promise<ApiResponse<IpCommandInstance[]>>; + /** + * Retrieve a single page of IpCommandInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpCommandListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: IpCommandPage) => any): Promise<IpCommandPage>; + page(params: IpCommandListInstancePageOptions, callback?: (error: Error | null, items: IpCommandPage) => any): Promise<IpCommandPage>; + /** + * Retrieve a single page of IpCommandInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpCommandListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<IpCommandPage>) => any): Promise<ApiResponse<IpCommandPage>>; + pageWithHttpInfo(params: IpCommandListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<IpCommandPage>) => any): Promise<ApiResponse<IpCommandPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function IpCommandListInstance(version: V1): IpCommandListInstance { + const instance = ((sid, ) => instance.get(sid, )) as IpCommandListInstance; + + instance.get = function get(sid, ): IpCommandContext { + return new IpCommandContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/IpCommands`; + + instance.create = function create(params: IpCommandListInstanceCreateOptions, callback?: (error: Error | null, items: IpCommandInstance) => any): Promise<IpCommandInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["sim"] === null || params["sim"] === undefined) { + throw new Error('Required parameter "params[\'sim\']" missing.'); + } + + if (params["payload"] === null || params["payload"] === undefined) { + throw new Error('Required parameter "params[\'payload\']" missing.'); + } + + if (params["devicePort"] === null || params["devicePort"] === undefined) { + throw new Error('Required parameter "params[\'devicePort\']" missing.'); + } + + let data: any = {}; + + + + data["Sim"] = params["sim"]; + + data["Payload"] = params["payload"]; + + data["DevicePort"] = params["devicePort"]; + if (params["payloadType"] !== undefined) + data["PayloadType"] = params["payloadType"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IpCommandInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: IpCommandListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<IpCommandInstance>) => any): Promise<ApiResponse<IpCommandInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["sim"] === null || params["sim"] === undefined) { + throw new Error('Required parameter "params[\'sim\']" missing.'); + } + + if (params["payload"] === null || params["payload"] === undefined) { + throw new Error('Required parameter "params[\'payload\']" missing.'); + } + + if (params["devicePort"] === null || params["devicePort"] === undefined) { + throw new Error('Required parameter "params[\'devicePort\']" missing.'); + } + + let data: any = {}; + + + + data["Sim"] = params["sim"]; + + data["Payload"] = params["payload"]; + + data["DevicePort"] = params["devicePort"]; + if (params["payloadType"] !== undefined) + data["PayloadType"] = params["payloadType"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<IpCommandResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<IpCommandInstance> => ({ + ...response, + body: new IpCommandInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: IpCommandListInstancePageOptions | ((error: Error | null, items: IpCommandPage) => any), callback?: (error: Error | null, items: IpCommandPage) => any): Promise<IpCommandPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["simIccid"] !== undefined) + data["SimIccid"] = params["simIccid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new IpCommandPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: IpCommandPage) => any): Promise<IpCommandPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new IpCommandPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: IpCommandListInstancePageOptions | ((error: Error | null, items: ApiResponse<IpCommandPage>) => any), callback?: (error: Error | null, items: ApiResponse<IpCommandPage>) => any): Promise<ApiResponse<IpCommandPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["simIccid"] !== undefined) + data["SimIccid"] = params["simIccid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<IpCommandPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpCommandPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<IpCommandPage>) => any): Promise<ApiResponse<IpCommandPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<IpCommandPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpCommandPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class IpCommandPage extends Page<V1, IpCommandPayload, IpCommandResource, IpCommandInstance> { +/** +* Initialize the IpCommandPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: IpCommandSolution) { + super(version, response, solution); + } + + /** + * Build an instance of IpCommandInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: IpCommandResource): IpCommandInstance { + + return new IpCommandInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/network.ts b/rest/supersim/v1/network.ts new file mode 100644 index 000000000..0d139b556 --- /dev/null +++ b/rest/supersim/v1/network.ts @@ -0,0 +1,574 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface NetworkListInstanceEachOptions { + /** The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. */ + "isoCountry"?: string; + /** The \'mobile country code\' of a country. Network resources with this `mcc` in their `identifiers` will be read. */ + "mcc"?: string; + /** The \'mobile network code\' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. */ + "mnc"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: NetworkInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface NetworkListInstanceOptions { + /** The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. */ + "isoCountry"?: string; + /** The \'mobile country code\' of a country. Network resources with this `mcc` in their `identifiers` will be read. */ + "mcc"?: string; + /** The \'mobile network code\' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. */ + "mnc"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface NetworkListInstancePageOptions { + /** The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. */ + "isoCountry"?: string; + /** The \'mobile country code\' of a country. Network resources with this `mcc` in their `identifiers` will be read. */ + "mcc"?: string; + /** The \'mobile network code\' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. */ + "mnc"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface NetworkContext { + + /** + * Fetch a NetworkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkInstance + */ + fetch(callback?: (error: Error | null, item?: NetworkInstance) => any): Promise<NetworkInstance> + + /** + * Fetch a NetworkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkInstance>) => any): Promise<ApiResponse<NetworkInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface NetworkContextSolution { + "sid": string; +} + +export class NetworkContextImpl implements NetworkContext { + protected _solution: NetworkContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Networks/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: NetworkInstance) => any): Promise<NetworkInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new NetworkInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkInstance>) => any): Promise<ApiResponse<NetworkInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<NetworkResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<NetworkInstance> => ({ + ...response, + body: new NetworkInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface NetworkPayload extends TwilioResponsePayload { + networks: NetworkResource[]; +} + +interface NetworkResource { + sid: string; + friendly_name: string; + url: string; + iso_country: string; + identifiers: Array<any>; +} + +export class NetworkInstance { + protected _solution: NetworkContextSolution; + protected _context?: NetworkContext; + + constructor(protected _version: V1, payload: NetworkResource, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.url = (payload.url); + this.isoCountry = (payload.iso_country); + this.identifiers = (payload.identifiers); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Network resource. + */ + sid: string; + /** + * A human readable identifier of this resource. + */ + friendlyName: string; + /** + * The absolute URL of the Network resource. + */ + url: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resource. + */ + isoCountry: string; + /** + * Array of objects identifying the [MCC-MNCs](https://en.wikipedia.org/wiki/Mobile_country_code) that are included in the Network resource. + */ + identifiers: Array<any>; + + private get _proxy(): NetworkContext { + this._context = this._context || new NetworkContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a NetworkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkInstance + */ + fetch(callback?: (error: Error | null, item?: NetworkInstance) => any): Promise<NetworkInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a NetworkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkInstance>) => any): Promise<ApiResponse<NetworkInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + url: this.url, + isoCountry: this.isoCountry, + identifiers: this.identifiers, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface NetworkSolution { +} + +export interface NetworkListInstance { + _version: V1; + _solution: NetworkSolution; + _uri: string; + + (sid: string, ): NetworkContext; + get(sid: string, ): NetworkContext; + + + + + + /** + * Streams NetworkInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: NetworkInstance, done: (err?: Error) => void) => void): void; + each(params: NetworkListInstanceEachOptions, callback?: (item: NetworkInstance, done: (err?: Error) => void) => void): void; + /** + * Streams NetworkInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: NetworkInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: NetworkListInstanceEachOptions, callback?: (item: NetworkInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of NetworkInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: NetworkPage) => any): Promise<NetworkPage>; + /** + * Retrieve a single target page of NetworkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<NetworkPage>) => any): Promise<ApiResponse<NetworkPage>>; + /** + * Lists NetworkInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: NetworkInstance[]) => any): Promise<NetworkInstance[]>; + list(params: NetworkListInstanceOptions, callback?: (error: Error | null, items: NetworkInstance[]) => any): Promise<NetworkInstance[]>; + /** + * Lists NetworkInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<NetworkInstance[]>) => any): Promise<ApiResponse<NetworkInstance[]>>; + listWithHttpInfo(params: NetworkListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<NetworkInstance[]>) => any): Promise<ApiResponse<NetworkInstance[]>>; + /** + * Retrieve a single page of NetworkInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: NetworkPage) => any): Promise<NetworkPage>; + page(params: NetworkListInstancePageOptions, callback?: (error: Error | null, items: NetworkPage) => any): Promise<NetworkPage>; + /** + * Retrieve a single page of NetworkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<NetworkPage>) => any): Promise<ApiResponse<NetworkPage>>; + pageWithHttpInfo(params: NetworkListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<NetworkPage>) => any): Promise<ApiResponse<NetworkPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NetworkListInstance(version: V1): NetworkListInstance { + const instance = ((sid, ) => instance.get(sid, )) as NetworkListInstance; + + instance.get = function get(sid, ): NetworkContext { + return new NetworkContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Networks`; + + instance.page = function page(params?: NetworkListInstancePageOptions | ((error: Error | null, items: NetworkPage) => any), callback?: (error: Error | null, items: NetworkPage) => any): Promise<NetworkPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["mcc"] !== undefined) + data["Mcc"] = params["mcc"]; + if (params["mnc"] !== undefined) + data["Mnc"] = params["mnc"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new NetworkPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: NetworkPage) => any): Promise<NetworkPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new NetworkPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: NetworkListInstancePageOptions | ((error: Error | null, items: ApiResponse<NetworkPage>) => any), callback?: (error: Error | null, items: ApiResponse<NetworkPage>) => any): Promise<ApiResponse<NetworkPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["mcc"] !== undefined) + data["Mcc"] = params["mcc"]; + if (params["mnc"] !== undefined) + data["Mnc"] = params["mnc"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<NetworkPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NetworkPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<NetworkPage>) => any): Promise<ApiResponse<NetworkPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<NetworkPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NetworkPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class NetworkPage extends Page<V1, NetworkPayload, NetworkResource, NetworkInstance> { +/** +* Initialize the NetworkPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: NetworkSolution) { + super(version, response, solution); + } + + /** + * Build an instance of NetworkInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: NetworkResource): NetworkInstance { + + return new NetworkInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/networkAccessProfile.ts b/rest/supersim/v1/networkAccessProfile.ts new file mode 100644 index 000000000..8fd57f873 --- /dev/null +++ b/rest/supersim/v1/networkAccessProfile.ts @@ -0,0 +1,850 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { NetworkAccessProfileNetworkListInstance } from "./networkAccessProfile/networkAccessProfileNetwork"; + + + + +/** + * Options to pass to update a NetworkAccessProfileInstance + */ +export interface NetworkAccessProfileContextUpdateOptions { + /** The new unique name of the Network Access Profile. */ + "uniqueName"?: string; +} + +/** + * Options to pass to create a NetworkAccessProfileInstance + */ +export interface NetworkAccessProfileListInstanceCreateOptions { + /** An application-defined string that uniquely identifies the resource. It can be used in place of the resource\\\'s `sid` in the URL to address the resource. */ + "uniqueName"?: string; + /** List of Network SIDs that this Network Access Profile will allow connections to. */ + "networks"?: Array<string>; +} + +/** + * Options to pass to each + */ +export interface NetworkAccessProfileListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: NetworkAccessProfileInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface NetworkAccessProfileListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface NetworkAccessProfileListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface NetworkAccessProfileContext { + networks: NetworkAccessProfileNetworkListInstance; + + /** + * Fetch a NetworkAccessProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance + */ + fetch(callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance> + + /** + * Fetch a NetworkAccessProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>> + + /** + * Update a NetworkAccessProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance + */ + update(callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance>; + /** + * Update a NetworkAccessProfileInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance + */ + update(params: NetworkAccessProfileContextUpdateOptions, callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance>; + + /** + * Update a NetworkAccessProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>>; + /** + * Update a NetworkAccessProfileInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance with HTTP metadata + */ + updateWithHttpInfo(params: NetworkAccessProfileContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface NetworkAccessProfileContextSolution { + "sid": string; +} + +export class NetworkAccessProfileContextImpl implements NetworkAccessProfileContext { + protected _solution: NetworkAccessProfileContextSolution; + protected _uri: string; + + protected _networks?: NetworkAccessProfileNetworkListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/NetworkAccessProfiles/${sid}`; + } + + get networks(): NetworkAccessProfileNetworkListInstance { + this._networks = this._networks || NetworkAccessProfileNetworkListInstance(this._version, this._solution.sid); + return this._networks; + } + + fetch(callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new NetworkAccessProfileInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<NetworkAccessProfileResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<NetworkAccessProfileInstance> => ({ + ...response, + body: new NetworkAccessProfileInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: NetworkAccessProfileContextUpdateOptions | ((error: Error | null, item?: NetworkAccessProfileInstance) => any),callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NetworkAccessProfileInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: NetworkAccessProfileContextUpdateOptions | ((error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<NetworkAccessProfileResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<NetworkAccessProfileInstance> => ({ + ...response, + body: new NetworkAccessProfileInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface NetworkAccessProfilePayload extends TwilioResponsePayload { + network_access_profiles: NetworkAccessProfileResource[]; +} + +interface NetworkAccessProfileResource { + sid: string; + unique_name: string; + account_sid: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class NetworkAccessProfileInstance { + protected _solution: NetworkAccessProfileContextSolution; + protected _context?: NetworkAccessProfileContext; + + constructor(protected _version: V1, payload: NetworkAccessProfileResource, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that identifies the Network Access Profile resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. + */ + uniqueName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Network Access Profile belongs to. + */ + accountSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Network Access Profile resource. + */ + url: string; + links: Record<string, string>; + + private get _proxy(): NetworkAccessProfileContext { + this._context = this._context || new NetworkAccessProfileContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a NetworkAccessProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance + */ + fetch(callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a NetworkAccessProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a NetworkAccessProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance + */ + update(callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance>; + /** + * Update a NetworkAccessProfileInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance + */ + update(params: NetworkAccessProfileContextUpdateOptions, callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance>; + + update(params?: any, callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a NetworkAccessProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>>; + /** + * Update a NetworkAccessProfileInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance with HTTP metadata + */ + updateWithHttpInfo(params: NetworkAccessProfileContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the networks. + */ + networks(): NetworkAccessProfileNetworkListInstance { + return this._proxy.networks; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface NetworkAccessProfileSolution { +} + +export interface NetworkAccessProfileListInstance { + _version: V1; + _solution: NetworkAccessProfileSolution; + _uri: string; + + (sid: string, ): NetworkAccessProfileContext; + get(sid: string, ): NetworkAccessProfileContext; + + + + + + + /** + * Create a NetworkAccessProfileInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance + */ + create(callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance>; + /** + * Create a NetworkAccessProfileInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance + */ + create(params: NetworkAccessProfileListInstanceCreateOptions, callback?: (error: Error | null, item?: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance>; + + /** + * Create a NetworkAccessProfileInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>>; + /** + * Create a NetworkAccessProfileInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileInstance with HTTP metadata + */ + createWithHttpInfo(params: NetworkAccessProfileListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>>; + + + + + /** + * Streams NetworkAccessProfileInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: NetworkAccessProfileInstance, done: (err?: Error) => void) => void): void; + each(params: NetworkAccessProfileListInstanceEachOptions, callback?: (item: NetworkAccessProfileInstance, done: (err?: Error) => void) => void): void; + /** + * Streams NetworkAccessProfileInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: NetworkAccessProfileInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: NetworkAccessProfileListInstanceEachOptions, callback?: (item: NetworkAccessProfileInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of NetworkAccessProfileInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: NetworkAccessProfilePage) => any): Promise<NetworkAccessProfilePage>; + /** + * Retrieve a single target page of NetworkAccessProfileInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfilePage>) => any): Promise<ApiResponse<NetworkAccessProfilePage>>; + /** + * Lists NetworkAccessProfileInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: NetworkAccessProfileInstance[]) => any): Promise<NetworkAccessProfileInstance[]>; + list(params: NetworkAccessProfileListInstanceOptions, callback?: (error: Error | null, items: NetworkAccessProfileInstance[]) => any): Promise<NetworkAccessProfileInstance[]>; + /** + * Lists NetworkAccessProfileInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfileInstance[]>) => any): Promise<ApiResponse<NetworkAccessProfileInstance[]>>; + listWithHttpInfo(params: NetworkAccessProfileListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfileInstance[]>) => any): Promise<ApiResponse<NetworkAccessProfileInstance[]>>; + /** + * Retrieve a single page of NetworkAccessProfileInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: NetworkAccessProfilePage) => any): Promise<NetworkAccessProfilePage>; + page(params: NetworkAccessProfileListInstancePageOptions, callback?: (error: Error | null, items: NetworkAccessProfilePage) => any): Promise<NetworkAccessProfilePage>; + /** + * Retrieve a single page of NetworkAccessProfileInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfilePage>) => any): Promise<ApiResponse<NetworkAccessProfilePage>>; + pageWithHttpInfo(params: NetworkAccessProfileListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfilePage>) => any): Promise<ApiResponse<NetworkAccessProfilePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NetworkAccessProfileListInstance(version: V1): NetworkAccessProfileListInstance { + const instance = ((sid, ) => instance.get(sid, )) as NetworkAccessProfileListInstance; + + instance.get = function get(sid, ): NetworkAccessProfileContext { + return new NetworkAccessProfileContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/NetworkAccessProfiles`; + + instance.create = function create(params?: NetworkAccessProfileListInstanceCreateOptions | ((error: Error | null, items: NetworkAccessProfileInstance) => any), callback?: (error: Error | null, items: NetworkAccessProfileInstance) => any): Promise<NetworkAccessProfileInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["networks"] !== undefined) + data["Networks"] = serialize.map(params["networks"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NetworkAccessProfileInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: NetworkAccessProfileListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<NetworkAccessProfileInstance>) => any), callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfileInstance>) => any): Promise<ApiResponse<NetworkAccessProfileInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["networks"] !== undefined) + data["Networks"] = serialize.map(params["networks"], (e: string) => (e)); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<NetworkAccessProfileResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<NetworkAccessProfileInstance> => ({ + ...response, + body: new NetworkAccessProfileInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: NetworkAccessProfileListInstancePageOptions | ((error: Error | null, items: NetworkAccessProfilePage) => any), callback?: (error: Error | null, items: NetworkAccessProfilePage) => any): Promise<NetworkAccessProfilePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new NetworkAccessProfilePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: NetworkAccessProfilePage) => any): Promise<NetworkAccessProfilePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new NetworkAccessProfilePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: NetworkAccessProfileListInstancePageOptions | ((error: Error | null, items: ApiResponse<NetworkAccessProfilePage>) => any), callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfilePage>) => any): Promise<ApiResponse<NetworkAccessProfilePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<NetworkAccessProfilePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NetworkAccessProfilePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<NetworkAccessProfilePage>) => any): Promise<ApiResponse<NetworkAccessProfilePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<NetworkAccessProfilePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NetworkAccessProfilePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class NetworkAccessProfilePage extends Page<V1, NetworkAccessProfilePayload, NetworkAccessProfileResource, NetworkAccessProfileInstance> { +/** +* Initialize the NetworkAccessProfilePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: NetworkAccessProfileSolution) { + super(version, response, solution); + } + + /** + * Build an instance of NetworkAccessProfileInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: NetworkAccessProfileResource): NetworkAccessProfileInstance { + + return new NetworkAccessProfileInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/networkAccessProfile/networkAccessProfileNetwork.ts b/rest/supersim/v1/networkAccessProfile/networkAccessProfileNetwork.ts new file mode 100644 index 000000000..768d5b49c --- /dev/null +++ b/rest/supersim/v1/networkAccessProfile/networkAccessProfileNetwork.ts @@ -0,0 +1,739 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a NetworkAccessProfileNetworkInstance + */ +export interface NetworkAccessProfileNetworkListInstanceCreateOptions { + /** The SID of the Network resource to be added to the Network Access Profile resource. */ + "network": string; +} + +/** + * Options to pass to each + */ +export interface NetworkAccessProfileNetworkListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: NetworkAccessProfileNetworkInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface NetworkAccessProfileNetworkListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface NetworkAccessProfileNetworkListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface NetworkAccessProfileNetworkContext { + + /** + * Remove a NetworkAccessProfileNetworkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a NetworkAccessProfileNetworkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a NetworkAccessProfileNetworkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileNetworkInstance + */ + fetch(callback?: (error: Error | null, item?: NetworkAccessProfileNetworkInstance) => any): Promise<NetworkAccessProfileNetworkInstance> + + /** + * Fetch a NetworkAccessProfileNetworkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileNetworkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileNetworkInstance>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface NetworkAccessProfileNetworkContextSolution { + "networkAccessProfileSid": string; + "sid": string; +} + +export class NetworkAccessProfileNetworkContextImpl implements NetworkAccessProfileNetworkContext { + protected _solution: NetworkAccessProfileNetworkContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, networkAccessProfileSid: string, sid: string) { + if (!isValidPathParam(networkAccessProfileSid)) { + throw new Error('Parameter \'networkAccessProfileSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { networkAccessProfileSid, sid, }; + this._uri = `/NetworkAccessProfiles/${networkAccessProfileSid}/Networks/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: NetworkAccessProfileNetworkInstance) => any): Promise<NetworkAccessProfileNetworkInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new NetworkAccessProfileNetworkInstance(operationVersion, payload, instance._solution.networkAccessProfileSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileNetworkInstance>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<NetworkAccessProfileNetworkResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<NetworkAccessProfileNetworkInstance> => ({ + ...response, + body: new NetworkAccessProfileNetworkInstance(operationVersion, response.body, instance._solution.networkAccessProfileSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface NetworkAccessProfileNetworkPayload extends TwilioResponsePayload { + networks: NetworkAccessProfileNetworkResource[]; +} + +interface NetworkAccessProfileNetworkResource { + sid: string; + network_access_profile_sid: string; + friendly_name: string; + iso_country: string; + identifiers: Array<any>; + url: string; +} + +export class NetworkAccessProfileNetworkInstance { + protected _solution: NetworkAccessProfileNetworkContextSolution; + protected _context?: NetworkAccessProfileNetworkContext; + + constructor(protected _version: V1, payload: NetworkAccessProfileNetworkResource, networkAccessProfileSid: string, sid?: string) { + + this.sid = (payload.sid); + this.networkAccessProfileSid = (payload.network_access_profile_sid); + this.friendlyName = (payload.friendly_name); + this.isoCountry = (payload.iso_country); + this.identifiers = (payload.identifiers); + this.url = (payload.url); + + this._solution = { networkAccessProfileSid, sid: sid, }; + } + + /** + * The unique string that identifies the Network resource. + */ + sid: string; + /** + * The unique string that identifies the Network resource\'s Network Access Profile resource. + */ + networkAccessProfileSid: string; + /** + * A human readable identifier of the Network this resource refers to. + */ + friendlyName: string; + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resource. + */ + isoCountry: string; + /** + * Array of objects identifying the [MCC-MNCs](https://en.wikipedia.org/wiki/Mobile_country_code) that are included in the Network resource. + */ + identifiers: Array<any>; + /** + * The absolute URL of the Network resource. + */ + url: string; + + private get _proxy(): NetworkAccessProfileNetworkContext { + this._context = this._context || new NetworkAccessProfileNetworkContextImpl(this._version, this._solution.networkAccessProfileSid, this._solution.sid); + return this._context; + } + + /** + * Remove a NetworkAccessProfileNetworkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a NetworkAccessProfileNetworkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a NetworkAccessProfileNetworkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileNetworkInstance + */ + fetch(callback?: (error: Error | null, item?: NetworkAccessProfileNetworkInstance) => any): Promise<NetworkAccessProfileNetworkInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a NetworkAccessProfileNetworkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileNetworkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileNetworkInstance>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + networkAccessProfileSid: this.networkAccessProfileSid, + friendlyName: this.friendlyName, + isoCountry: this.isoCountry, + identifiers: this.identifiers, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface NetworkAccessProfileNetworkSolution { + networkAccessProfileSid: string; +} + +export interface NetworkAccessProfileNetworkListInstance { + _version: V1; + _solution: NetworkAccessProfileNetworkSolution; + _uri: string; + + (sid: string, ): NetworkAccessProfileNetworkContext; + get(sid: string, ): NetworkAccessProfileNetworkContext; + + + + + + + /** + * Create a NetworkAccessProfileNetworkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileNetworkInstance + */ + create(params: NetworkAccessProfileNetworkListInstanceCreateOptions, callback?: (error: Error | null, item?: NetworkAccessProfileNetworkInstance) => any): Promise<NetworkAccessProfileNetworkInstance>; + + /** + * Create a NetworkAccessProfileNetworkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NetworkAccessProfileNetworkInstance with HTTP metadata + */ + createWithHttpInfo(params: NetworkAccessProfileNetworkListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<NetworkAccessProfileNetworkInstance>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkInstance>>; + + + + + /** + * Streams NetworkAccessProfileNetworkInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileNetworkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: NetworkAccessProfileNetworkInstance, done: (err?: Error) => void) => void): void; + each(params: NetworkAccessProfileNetworkListInstanceEachOptions, callback?: (item: NetworkAccessProfileNetworkInstance, done: (err?: Error) => void) => void): void; + /** + * Streams NetworkAccessProfileNetworkInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileNetworkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: NetworkAccessProfileNetworkInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: NetworkAccessProfileNetworkListInstanceEachOptions, callback?: (item: NetworkAccessProfileNetworkInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of NetworkAccessProfileNetworkInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: NetworkAccessProfileNetworkPage) => any): Promise<NetworkAccessProfileNetworkPage>; + /** + * Retrieve a single target page of NetworkAccessProfileNetworkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfileNetworkPage>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkPage>>; + /** + * Lists NetworkAccessProfileNetworkInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileNetworkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: NetworkAccessProfileNetworkInstance[]) => any): Promise<NetworkAccessProfileNetworkInstance[]>; + list(params: NetworkAccessProfileNetworkListInstanceOptions, callback?: (error: Error | null, items: NetworkAccessProfileNetworkInstance[]) => any): Promise<NetworkAccessProfileNetworkInstance[]>; + /** + * Lists NetworkAccessProfileNetworkInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileNetworkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfileNetworkInstance[]>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkInstance[]>>; + listWithHttpInfo(params: NetworkAccessProfileNetworkListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfileNetworkInstance[]>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkInstance[]>>; + /** + * Retrieve a single page of NetworkAccessProfileNetworkInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileNetworkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: NetworkAccessProfileNetworkPage) => any): Promise<NetworkAccessProfileNetworkPage>; + page(params: NetworkAccessProfileNetworkListInstancePageOptions, callback?: (error: Error | null, items: NetworkAccessProfileNetworkPage) => any): Promise<NetworkAccessProfileNetworkPage>; + /** + * Retrieve a single page of NetworkAccessProfileNetworkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { NetworkAccessProfileNetworkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfileNetworkPage>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkPage>>; + pageWithHttpInfo(params: NetworkAccessProfileNetworkListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfileNetworkPage>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NetworkAccessProfileNetworkListInstance(version: V1, networkAccessProfileSid: string): NetworkAccessProfileNetworkListInstance { + if (!isValidPathParam(networkAccessProfileSid)) { + throw new Error('Parameter \'networkAccessProfileSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as NetworkAccessProfileNetworkListInstance; + + instance.get = function get(sid, ): NetworkAccessProfileNetworkContext { + return new NetworkAccessProfileNetworkContextImpl(version, networkAccessProfileSid, sid); + } + + instance._version = version; + instance._solution = { networkAccessProfileSid, }; + instance._uri = `/NetworkAccessProfiles/${networkAccessProfileSid}/Networks`; + + instance.create = function create(params: NetworkAccessProfileNetworkListInstanceCreateOptions, callback?: (error: Error | null, items: NetworkAccessProfileNetworkInstance) => any): Promise<NetworkAccessProfileNetworkInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["network"] === null || params["network"] === undefined) { + throw new Error('Required parameter "params[\'network\']" missing.'); + } + + let data: any = {}; + + + + data["Network"] = params["network"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NetworkAccessProfileNetworkInstance(operationVersion, payload, instance._solution.networkAccessProfileSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: NetworkAccessProfileNetworkListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfileNetworkInstance>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["network"] === null || params["network"] === undefined) { + throw new Error('Required parameter "params[\'network\']" missing.'); + } + + let data: any = {}; + + + + data["Network"] = params["network"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<NetworkAccessProfileNetworkResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<NetworkAccessProfileNetworkInstance> => ({ + ...response, + body: new NetworkAccessProfileNetworkInstance(operationVersion, response.body, instance._solution.networkAccessProfileSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: NetworkAccessProfileNetworkListInstancePageOptions | ((error: Error | null, items: NetworkAccessProfileNetworkPage) => any), callback?: (error: Error | null, items: NetworkAccessProfileNetworkPage) => any): Promise<NetworkAccessProfileNetworkPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new NetworkAccessProfileNetworkPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: NetworkAccessProfileNetworkPage) => any): Promise<NetworkAccessProfileNetworkPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new NetworkAccessProfileNetworkPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: NetworkAccessProfileNetworkListInstancePageOptions | ((error: Error | null, items: ApiResponse<NetworkAccessProfileNetworkPage>) => any), callback?: (error: Error | null, items: ApiResponse<NetworkAccessProfileNetworkPage>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<NetworkAccessProfileNetworkPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NetworkAccessProfileNetworkPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<NetworkAccessProfileNetworkPage>) => any): Promise<ApiResponse<NetworkAccessProfileNetworkPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<NetworkAccessProfileNetworkPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new NetworkAccessProfileNetworkPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class NetworkAccessProfileNetworkPage extends Page<V1, NetworkAccessProfileNetworkPayload, NetworkAccessProfileNetworkResource, NetworkAccessProfileNetworkInstance> { +/** +* Initialize the NetworkAccessProfileNetworkPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: NetworkAccessProfileNetworkSolution) { + super(version, response, solution); + } + + /** + * Build an instance of NetworkAccessProfileNetworkInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: NetworkAccessProfileNetworkResource): NetworkAccessProfileNetworkInstance { + + return new NetworkAccessProfileNetworkInstance( + this._version, + payload, + this._solution.networkAccessProfileSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/settingsUpdate.ts b/rest/supersim/v1/settingsUpdate.ts new file mode 100644 index 000000000..4996f04c0 --- /dev/null +++ b/rest/supersim/v1/settingsUpdate.ts @@ -0,0 +1,449 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The Status of this Settings Update. One of `scheduled`, `in-progress`, `successful` or `failed`. + */ +export type SettingsUpdateStatus = 'scheduled'|'in-progress'|'successful'|'failed'; + + +/** + * Options to pass to each + */ +export interface SettingsUpdateListInstanceEachOptions { + /** Filter the Settings Updates by a Super SIM\'s SID or UniqueName. */ + "sim"?: string; + /** Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. */ + "status"?: SettingsUpdateStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SettingsUpdateInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SettingsUpdateListInstanceOptions { + /** Filter the Settings Updates by a Super SIM\'s SID or UniqueName. */ + "sim"?: string; + /** Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. */ + "status"?: SettingsUpdateStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SettingsUpdateListInstancePageOptions { + /** Filter the Settings Updates by a Super SIM\'s SID or UniqueName. */ + "sim"?: string; + /** Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. */ + "status"?: SettingsUpdateStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface SettingsUpdateSolution { +} + +export interface SettingsUpdateListInstance { + _version: V1; + _solution: SettingsUpdateSolution; + _uri: string; + + + + + /** + * Streams SettingsUpdateInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SettingsUpdateListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SettingsUpdateInstance, done: (err?: Error) => void) => void): void; + each(params: SettingsUpdateListInstanceEachOptions, callback?: (item: SettingsUpdateInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SettingsUpdateInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SettingsUpdateListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SettingsUpdateInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SettingsUpdateListInstanceEachOptions, callback?: (item: SettingsUpdateInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SettingsUpdateInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SettingsUpdatePage) => any): Promise<SettingsUpdatePage>; + /** + * Retrieve a single target page of SettingsUpdateInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SettingsUpdatePage>) => any): Promise<ApiResponse<SettingsUpdatePage>>; + /** + * Lists SettingsUpdateInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SettingsUpdateListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SettingsUpdateInstance[]) => any): Promise<SettingsUpdateInstance[]>; + list(params: SettingsUpdateListInstanceOptions, callback?: (error: Error | null, items: SettingsUpdateInstance[]) => any): Promise<SettingsUpdateInstance[]>; + /** + * Lists SettingsUpdateInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SettingsUpdateListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SettingsUpdateInstance[]>) => any): Promise<ApiResponse<SettingsUpdateInstance[]>>; + listWithHttpInfo(params: SettingsUpdateListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SettingsUpdateInstance[]>) => any): Promise<ApiResponse<SettingsUpdateInstance[]>>; + /** + * Retrieve a single page of SettingsUpdateInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SettingsUpdateListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SettingsUpdatePage) => any): Promise<SettingsUpdatePage>; + page(params: SettingsUpdateListInstancePageOptions, callback?: (error: Error | null, items: SettingsUpdatePage) => any): Promise<SettingsUpdatePage>; + /** + * Retrieve a single page of SettingsUpdateInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SettingsUpdateListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SettingsUpdatePage>) => any): Promise<ApiResponse<SettingsUpdatePage>>; + pageWithHttpInfo(params: SettingsUpdateListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SettingsUpdatePage>) => any): Promise<ApiResponse<SettingsUpdatePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SettingsUpdateListInstance(version: V1): SettingsUpdateListInstance { + const instance = {} as SettingsUpdateListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/SettingsUpdates`; + + instance.page = function page(params?: SettingsUpdateListInstancePageOptions | ((error: Error | null, items: SettingsUpdatePage) => any), callback?: (error: Error | null, items: SettingsUpdatePage) => any): Promise<SettingsUpdatePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SettingsUpdatePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SettingsUpdatePage) => any): Promise<SettingsUpdatePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SettingsUpdatePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SettingsUpdateListInstancePageOptions | ((error: Error | null, items: ApiResponse<SettingsUpdatePage>) => any), callback?: (error: Error | null, items: ApiResponse<SettingsUpdatePage>) => any): Promise<ApiResponse<SettingsUpdatePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SettingsUpdatePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SettingsUpdatePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SettingsUpdatePage>) => any): Promise<ApiResponse<SettingsUpdatePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SettingsUpdatePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SettingsUpdatePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface SettingsUpdatePayload extends TwilioResponsePayload { + settings_updates: SettingsUpdateResource[]; +} + +interface SettingsUpdateResource { + sid: string; + iccid: string; + sim_sid: string; + status: SettingsUpdateStatus; + packages: Array<any>; + date_completed: Date; + date_created: Date; + date_updated: Date; +} + +export class SettingsUpdateInstance { + + constructor(protected _version: V1, payload: SettingsUpdateResource) { + + this.sid = (payload.sid); + this.iccid = (payload.iccid); + this.simSid = (payload.sim_sid); + this.status = payload.status; + this.packages = (payload.packages); + this.dateCompleted = deserialize.iso8601DateTime(payload.date_completed); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The unique identifier of this Settings Update. + */ + sid: string; + /** + * The [ICCID](https://en.wikipedia.org/wiki/SIM_card#ICCID) associated with the SIM. + */ + iccid: string; + /** + * The SID of the Super SIM to which this Settings Update was applied. + */ + simSid: string; + status: SettingsUpdateStatus; + /** + * Array containing the different Settings Packages that will be applied to the SIM after the update completes. Each object within the array indicates the name and the version of the Settings Package that will be on the SIM if the update is successful. + */ + packages: Array<any>; + /** + * The time, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, when the update successfully completed and the new settings were applied to the SIM. + */ + dateCompleted: Date; + /** + * The date that this Settings Update was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date that this Settings Update was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + iccid: this.iccid, + simSid: this.simSid, + status: this.status, + packages: this.packages, + dateCompleted: this.dateCompleted, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class SettingsUpdatePage extends Page<V1, SettingsUpdatePayload, SettingsUpdateResource, SettingsUpdateInstance> { +/** +* Initialize the SettingsUpdatePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SettingsUpdateSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SettingsUpdateInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SettingsUpdateResource): SettingsUpdateInstance { + + return new SettingsUpdateInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/sim.ts b/rest/supersim/v1/sim.ts new file mode 100644 index 000000000..658f9f363 --- /dev/null +++ b/rest/supersim/v1/sim.ts @@ -0,0 +1,944 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { BillingPeriodListInstance } from "./sim/billingPeriod"; +import { SimIpAddressListInstance } from "./sim/simIpAddress"; + + +/** + * The status of the Super SIM. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. See the [Super SIM Status Values](https://www.twilio.com/docs/iot/supersim/api/sim-resource#status-values) for a description of each. + */ +export type SimStatus = 'new'|'ready'|'active'|'inactive'|'scheduled'; + +export type SimStatusUpdate = 'ready'|'active'|'inactive'; + + + +/** + * Options to pass to update a SimInstance + */ +export interface SimContextUpdateOptions { + /** An application-defined string that uniquely identifies the resource. It can be used in place of the resource\\\'s `sid` in the URL to address the resource. */ + "uniqueName"?: string; + /** */ + "status"?: SimStatusUpdate; + /** The SID or unique name of the Fleet to which the SIM resource should be assigned. */ + "fleet"?: string; + /** The URL we should call using the `callback_method` after an asynchronous update has finished. */ + "callbackUrl"?: string; + /** The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. */ + "callbackMethod"?: string; + /** The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource\\\'s status is new. */ + "accountSid"?: string; +} + +/** + * Options to pass to create a SimInstance + */ +export interface SimListInstanceCreateOptions { + /** The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. */ + "iccid": string; + /** The 10-digit code required to claim the Super SIM for your Account. */ + "registrationCode": string; +} + +/** + * Options to pass to each + */ +export interface SimListInstanceEachOptions { + /** The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. */ + "status"?: SimStatus; + /** The SID or unique name of the Fleet to which a list of Sims are assigned. */ + "fleet"?: string; + /** The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. */ + "iccid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SimInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SimListInstanceOptions { + /** The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. */ + "status"?: SimStatus; + /** The SID or unique name of the Fleet to which a list of Sims are assigned. */ + "fleet"?: string; + /** The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. */ + "iccid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SimListInstancePageOptions { + /** The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. */ + "status"?: SimStatus; + /** The SID or unique name of the Fleet to which a list of Sims are assigned. */ + "fleet"?: string; + /** The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. */ + "iccid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SimContext { + billingPeriods: BillingPeriodListInstance; + simIpAddresses: SimIpAddressListInstance; + + /** + * Fetch a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + fetch(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> + + /** + * Fetch a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> + + /** + * Update a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + /** + * Update a SimInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + + /** + * Update a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + /** + * Update a SimInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SimContextSolution { + "sid": string; +} + +export class SimContextImpl implements SimContext { + protected _solution: SimContextSolution; + protected _uri: string; + + protected _billingPeriods?: BillingPeriodListInstance; + protected _simIpAddresses?: SimIpAddressListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Sims/${sid}`; + } + + get billingPeriods(): BillingPeriodListInstance { + this._billingPeriods = this._billingPeriods || BillingPeriodListInstance(this._version, this._solution.sid); + return this._billingPeriods; + } + + get simIpAddresses(): SimIpAddressListInstance { + this._simIpAddresses = this._simIpAddresses || SimIpAddressListInstance(this._version, this._solution.sid); + return this._simIpAddresses; + } + + fetch(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SimInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SimResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SimInstance> => ({ + ...response, + body: new SimInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SimContextUpdateOptions | ((error: Error | null, item?: SimInstance) => any),callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["fleet"] !== undefined) + data["Fleet"] = params["fleet"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SimInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SimContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SimInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["fleet"] !== undefined) + data["Fleet"] = params["fleet"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SimResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SimInstance> => ({ + ...response, + body: new SimInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SimPayload extends TwilioResponsePayload { + sims: SimResource[]; +} + +interface SimResource { + sid: string; + unique_name: string; + account_sid: string; + iccid: string; + status: SimStatus; + fleet_sid: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class SimInstance { + protected _solution: SimContextSolution; + protected _context?: SimContext; + + constructor(protected _version: V1, payload: SimResource, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.iccid = (payload.iccid); + this.status = payload.status; + this.fleetSid = (payload.fleet_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that identifies the Sim resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. + */ + uniqueName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Super SIM belongs to. + */ + accountSid: string; + /** + * The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with the SIM. + */ + iccid: string; + status: SimStatus; + /** + * The unique ID of the Fleet configured for this SIM. + */ + fleetSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Sim Resource. + */ + url: string; + links: Record<string, string>; + + private get _proxy(): SimContext { + this._context = this._context || new SimContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + fetch(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + /** + * Update a SimInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + /** + * Update a SimInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the billingPeriods. + */ + billingPeriods(): BillingPeriodListInstance { + return this._proxy.billingPeriods; + } + + /** + * Access the simIpAddresses. + */ + simIpAddresses(): SimIpAddressListInstance { + return this._proxy.simIpAddresses; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + iccid: this.iccid, + status: this.status, + fleetSid: this.fleetSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SimSolution { +} + +export interface SimListInstance { + _version: V1; + _solution: SimSolution; + _uri: string; + + (sid: string, ): SimContext; + get(sid: string, ): SimContext; + + + + + + + /** + * Create a SimInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + create(params: SimListInstanceCreateOptions, callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + + /** + * Create a SimInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + createWithHttpInfo(params: SimListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + + + + + /** + * Streams SimInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + each(params: SimListInstanceEachOptions, callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SimInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SimListInstanceEachOptions, callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SimInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage>; + /** + * Retrieve a single target page of SimInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>>; + /** + * Lists SimInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SimInstance[]) => any): Promise<SimInstance[]>; + list(params: SimListInstanceOptions, callback?: (error: Error | null, items: SimInstance[]) => any): Promise<SimInstance[]>; + /** + * Lists SimInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SimInstance[]>) => any): Promise<ApiResponse<SimInstance[]>>; + listWithHttpInfo(params: SimListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SimInstance[]>) => any): Promise<ApiResponse<SimInstance[]>>; + /** + * Retrieve a single page of SimInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage>; + page(params: SimListInstancePageOptions, callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage>; + /** + * Retrieve a single page of SimInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>>; + pageWithHttpInfo(params: SimListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SimListInstance(version: V1): SimListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SimListInstance; + + instance.get = function get(sid, ): SimContext { + return new SimContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Sims`; + + instance.create = function create(params: SimListInstanceCreateOptions, callback?: (error: Error | null, items: SimInstance) => any): Promise<SimInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["iccid"] === null || params["iccid"] === undefined) { + throw new Error('Required parameter "params[\'iccid\']" missing.'); + } + + if (params["registrationCode"] === null || params["registrationCode"] === undefined) { + throw new Error('Required parameter "params[\'registrationCode\']" missing.'); + } + + let data: any = {}; + + + + data["Iccid"] = params["iccid"]; + + data["RegistrationCode"] = params["registrationCode"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SimInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SimListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["iccid"] === null || params["iccid"] === undefined) { + throw new Error('Required parameter "params[\'iccid\']" missing.'); + } + + if (params["registrationCode"] === null || params["registrationCode"] === undefined) { + throw new Error('Required parameter "params[\'registrationCode\']" missing.'); + } + + let data: any = {}; + + + + data["Iccid"] = params["iccid"]; + + data["RegistrationCode"] = params["registrationCode"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SimResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SimInstance> => ({ + ...response, + body: new SimInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SimListInstancePageOptions | ((error: Error | null, items: SimPage) => any), callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["fleet"] !== undefined) + data["Fleet"] = params["fleet"]; + if (params["iccid"] !== undefined) + data["Iccid"] = params["iccid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SimPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SimPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SimListInstancePageOptions | ((error: Error | null, items: ApiResponse<SimPage>) => any), callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["fleet"] !== undefined) + data["Fleet"] = params["fleet"]; + if (params["iccid"] !== undefined) + data["Iccid"] = params["iccid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SimPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SimPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SimPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SimPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SimPage extends Page<V1, SimPayload, SimResource, SimInstance> { +/** +* Initialize the SimPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SimSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SimInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SimResource): SimInstance { + + return new SimInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/sim/billingPeriod.ts b/rest/supersim/v1/sim/billingPeriod.ts new file mode 100644 index 000000000..44f08f572 --- /dev/null +++ b/rest/supersim/v1/sim/billingPeriod.ts @@ -0,0 +1,435 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The type of Billing Period. Can be `ready` or `active`. + */ +export type BillingPeriodBpType = 'ready'|'active'; + + +/** + * Options to pass to each + */ +export interface BillingPeriodListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BillingPeriodInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BillingPeriodListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BillingPeriodListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface BillingPeriodSolution { + simSid: string; +} + +export interface BillingPeriodListInstance { + _version: V1; + _solution: BillingPeriodSolution; + _uri: string; + + + + + /** + * Streams BillingPeriodInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BillingPeriodListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BillingPeriodInstance, done: (err?: Error) => void) => void): void; + each(params: BillingPeriodListInstanceEachOptions, callback?: (item: BillingPeriodInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BillingPeriodInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BillingPeriodListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BillingPeriodInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BillingPeriodListInstanceEachOptions, callback?: (item: BillingPeriodInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BillingPeriodInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BillingPeriodPage) => any): Promise<BillingPeriodPage>; + /** + * Retrieve a single target page of BillingPeriodInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<BillingPeriodPage>) => any): Promise<ApiResponse<BillingPeriodPage>>; + /** + * Lists BillingPeriodInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BillingPeriodListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BillingPeriodInstance[]) => any): Promise<BillingPeriodInstance[]>; + list(params: BillingPeriodListInstanceOptions, callback?: (error: Error | null, items: BillingPeriodInstance[]) => any): Promise<BillingPeriodInstance[]>; + /** + * Lists BillingPeriodInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BillingPeriodListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BillingPeriodInstance[]>) => any): Promise<ApiResponse<BillingPeriodInstance[]>>; + listWithHttpInfo(params: BillingPeriodListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<BillingPeriodInstance[]>) => any): Promise<ApiResponse<BillingPeriodInstance[]>>; + /** + * Retrieve a single page of BillingPeriodInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BillingPeriodListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BillingPeriodPage) => any): Promise<BillingPeriodPage>; + page(params: BillingPeriodListInstancePageOptions, callback?: (error: Error | null, items: BillingPeriodPage) => any): Promise<BillingPeriodPage>; + /** + * Retrieve a single page of BillingPeriodInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BillingPeriodListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BillingPeriodPage>) => any): Promise<ApiResponse<BillingPeriodPage>>; + pageWithHttpInfo(params: BillingPeriodListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<BillingPeriodPage>) => any): Promise<ApiResponse<BillingPeriodPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BillingPeriodListInstance(version: V1, simSid: string): BillingPeriodListInstance { + if (!isValidPathParam(simSid)) { + throw new Error('Parameter \'simSid\' is not valid.'); + } + + const instance = {} as BillingPeriodListInstance; + + instance._version = version; + instance._solution = { simSid, }; + instance._uri = `/Sims/${simSid}/BillingPeriods`; + + instance.page = function page(params?: BillingPeriodListInstancePageOptions | ((error: Error | null, items: BillingPeriodPage) => any), callback?: (error: Error | null, items: BillingPeriodPage) => any): Promise<BillingPeriodPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BillingPeriodPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BillingPeriodPage) => any): Promise<BillingPeriodPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BillingPeriodPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BillingPeriodListInstancePageOptions | ((error: Error | null, items: ApiResponse<BillingPeriodPage>) => any), callback?: (error: Error | null, items: ApiResponse<BillingPeriodPage>) => any): Promise<ApiResponse<BillingPeriodPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<BillingPeriodPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BillingPeriodPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<BillingPeriodPage>) => any): Promise<ApiResponse<BillingPeriodPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<BillingPeriodPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BillingPeriodPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface BillingPeriodPayload extends TwilioResponsePayload { + billing_periods: BillingPeriodResource[]; +} + +interface BillingPeriodResource { + sid: string; + account_sid: string; + sim_sid: string; + start_time: Date; + end_time: Date; + period_type: BillingPeriodBpType; + date_created: Date; + date_updated: Date; +} + +export class BillingPeriodInstance { + + constructor(protected _version: V1, payload: BillingPeriodResource, simSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.simSid = (payload.sim_sid); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.periodType = payload.period_type; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The SID of the Billing Period. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) the Super SIM belongs to. + */ + accountSid: string; + /** + * The SID of the Super SIM the Billing Period belongs to. + */ + simSid: string; + /** + * The start time of the Billing Period specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + startTime: Date; + /** + * The end time of the Billing Period specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + endTime: Date; + periodType: BillingPeriodBpType; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + simSid: this.simSid, + startTime: this.startTime, + endTime: this.endTime, + periodType: this.periodType, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class BillingPeriodPage extends Page<V1, BillingPeriodPayload, BillingPeriodResource, BillingPeriodInstance> { +/** +* Initialize the BillingPeriodPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: BillingPeriodSolution) { + super(version, response, solution); + } + + /** + * Build an instance of BillingPeriodInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BillingPeriodResource): BillingPeriodInstance { + + return new BillingPeriodInstance( + this._version, + payload, + this._solution.simSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/sim/simIpAddress.ts b/rest/supersim/v1/sim/simIpAddress.ts new file mode 100644 index 000000000..ac975d4cf --- /dev/null +++ b/rest/supersim/v1/sim/simIpAddress.ts @@ -0,0 +1,393 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * IP address version of the corresponding IP address + */ +export type SimIpAddressIpAddressVersion = 'IPv4'|'IPv6'; + + +/** + * Options to pass to each + */ +export interface SimIpAddressListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SimIpAddressInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SimIpAddressListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SimIpAddressListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface SimIpAddressSolution { + simSid: string; +} + +export interface SimIpAddressListInstance { + _version: V1; + _solution: SimIpAddressSolution; + _uri: string; + + + + + /** + * Streams SimIpAddressInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimIpAddressListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SimIpAddressInstance, done: (err?: Error) => void) => void): void; + each(params: SimIpAddressListInstanceEachOptions, callback?: (item: SimIpAddressInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SimIpAddressInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimIpAddressListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SimIpAddressInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SimIpAddressListInstanceEachOptions, callback?: (item: SimIpAddressInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SimIpAddressInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SimIpAddressPage) => any): Promise<SimIpAddressPage>; + /** + * Retrieve a single target page of SimIpAddressInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SimIpAddressPage>) => any): Promise<ApiResponse<SimIpAddressPage>>; + /** + * Lists SimIpAddressInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimIpAddressListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SimIpAddressInstance[]) => any): Promise<SimIpAddressInstance[]>; + list(params: SimIpAddressListInstanceOptions, callback?: (error: Error | null, items: SimIpAddressInstance[]) => any): Promise<SimIpAddressInstance[]>; + /** + * Lists SimIpAddressInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimIpAddressListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SimIpAddressInstance[]>) => any): Promise<ApiResponse<SimIpAddressInstance[]>>; + listWithHttpInfo(params: SimIpAddressListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SimIpAddressInstance[]>) => any): Promise<ApiResponse<SimIpAddressInstance[]>>; + /** + * Retrieve a single page of SimIpAddressInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimIpAddressListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SimIpAddressPage) => any): Promise<SimIpAddressPage>; + page(params: SimIpAddressListInstancePageOptions, callback?: (error: Error | null, items: SimIpAddressPage) => any): Promise<SimIpAddressPage>; + /** + * Retrieve a single page of SimIpAddressInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimIpAddressListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SimIpAddressPage>) => any): Promise<ApiResponse<SimIpAddressPage>>; + pageWithHttpInfo(params: SimIpAddressListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SimIpAddressPage>) => any): Promise<ApiResponse<SimIpAddressPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SimIpAddressListInstance(version: V1, simSid: string): SimIpAddressListInstance { + if (!isValidPathParam(simSid)) { + throw new Error('Parameter \'simSid\' is not valid.'); + } + + const instance = {} as SimIpAddressListInstance; + + instance._version = version; + instance._solution = { simSid, }; + instance._uri = `/Sims/${simSid}/IpAddresses`; + + instance.page = function page(params?: SimIpAddressListInstancePageOptions | ((error: Error | null, items: SimIpAddressPage) => any), callback?: (error: Error | null, items: SimIpAddressPage) => any): Promise<SimIpAddressPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SimIpAddressPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SimIpAddressPage) => any): Promise<SimIpAddressPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SimIpAddressPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SimIpAddressListInstancePageOptions | ((error: Error | null, items: ApiResponse<SimIpAddressPage>) => any), callback?: (error: Error | null, items: ApiResponse<SimIpAddressPage>) => any): Promise<ApiResponse<SimIpAddressPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SimIpAddressPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SimIpAddressPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SimIpAddressPage>) => any): Promise<ApiResponse<SimIpAddressPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SimIpAddressPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SimIpAddressPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface SimIpAddressPayload extends TwilioResponsePayload { + ip_addresses: SimIpAddressResource[]; +} + +interface SimIpAddressResource { + ip_address: string; + ip_address_version: SimIpAddressIpAddressVersion; +} + +export class SimIpAddressInstance { + + constructor(protected _version: V1, payload: SimIpAddressResource, simSid: string) { + + this.ipAddress = (payload.ip_address); + this.ipAddressVersion = payload.ip_address_version; + + } + + /** + * IP address assigned to the given Super SIM + */ + ipAddress: string; + ipAddressVersion: SimIpAddressIpAddressVersion; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + ipAddress: this.ipAddress, + ipAddressVersion: this.ipAddressVersion, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class SimIpAddressPage extends Page<V1, SimIpAddressPayload, SimIpAddressResource, SimIpAddressInstance> { +/** +* Initialize the SimIpAddressPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SimIpAddressSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SimIpAddressInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SimIpAddressResource): SimIpAddressInstance { + + return new SimIpAddressInstance( + this._version, + payload, + this._solution.simSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/smsCommand.ts b/rest/supersim/v1/smsCommand.ts new file mode 100644 index 000000000..fc98f793c --- /dev/null +++ b/rest/supersim/v1/smsCommand.ts @@ -0,0 +1,731 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + */ +export type SmsCommandDirection = 'to_sim'|'from_sim'; + +/** + * The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + */ +export type SmsCommandStatus = 'queued'|'sent'|'delivered'|'received'|'failed'; + + + +/** + * Options to pass to create a SmsCommandInstance + */ +export interface SmsCommandListInstanceCreateOptions { + /** The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. */ + "sim": string; + /** The message body of the SMS Command. */ + "payload": string; + /** The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. */ + "callbackMethod"?: string; + /** The URL we should call using the `callback_method` after we have sent the command. */ + "callbackUrl"?: string; +} + +/** + * Options to pass to each + */ +export interface SmsCommandListInstanceEachOptions { + /** The SID or unique name of the Sim resource that SMS Command was sent to or from. */ + "sim"?: string; + /** The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. */ + "status"?: SmsCommandStatus; + /** The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. */ + "direction"?: SmsCommandDirection; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SmsCommandInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SmsCommandListInstanceOptions { + /** The SID or unique name of the Sim resource that SMS Command was sent to or from. */ + "sim"?: string; + /** The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. */ + "status"?: SmsCommandStatus; + /** The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. */ + "direction"?: SmsCommandDirection; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SmsCommandListInstancePageOptions { + /** The SID or unique name of the Sim resource that SMS Command was sent to or from. */ + "sim"?: string; + /** The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. */ + "status"?: SmsCommandStatus; + /** The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. */ + "direction"?: SmsCommandDirection; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SmsCommandContext { + + /** + * Fetch a SmsCommandInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SmsCommandInstance + */ + fetch(callback?: (error: Error | null, item?: SmsCommandInstance) => any): Promise<SmsCommandInstance> + + /** + * Fetch a SmsCommandInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SmsCommandInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SmsCommandInstance>) => any): Promise<ApiResponse<SmsCommandInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SmsCommandContextSolution { + "sid": string; +} + +export class SmsCommandContextImpl implements SmsCommandContext { + protected _solution: SmsCommandContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/SmsCommands/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: SmsCommandInstance) => any): Promise<SmsCommandInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SmsCommandInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SmsCommandInstance>) => any): Promise<ApiResponse<SmsCommandInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SmsCommandResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SmsCommandInstance> => ({ + ...response, + body: new SmsCommandInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SmsCommandPayload extends TwilioResponsePayload { + sms_commands: SmsCommandResource[]; +} + +interface SmsCommandResource { + sid: string; + account_sid: string; + sim_sid: string; + payload: string; + status: SmsCommandStatus; + direction: SmsCommandDirection; + date_created: Date; + date_updated: Date; + url: string; +} + +export class SmsCommandInstance { + protected _solution: SmsCommandContextSolution; + protected _context?: SmsCommandContext; + + constructor(protected _version: V1, payload: SmsCommandResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.simSid = (payload.sim_sid); + this.payload = (payload.payload); + this.status = payload.status; + this.direction = payload.direction; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the SMS Command resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SMS Command resource. + */ + accountSid: string; + /** + * The SID of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) that this SMS Command was sent to or from. + */ + simSid: string; + /** + * The message body of the SMS Command sent to or from the SIM. For text mode messages, this can be up to 160 characters. + */ + payload: string; + status: SmsCommandStatus; + direction: SmsCommandDirection; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the SMS Command resource. + */ + url: string; + + private get _proxy(): SmsCommandContext { + this._context = this._context || new SmsCommandContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a SmsCommandInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SmsCommandInstance + */ + fetch(callback?: (error: Error | null, item?: SmsCommandInstance) => any): Promise<SmsCommandInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SmsCommandInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SmsCommandInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SmsCommandInstance>) => any): Promise<ApiResponse<SmsCommandInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + simSid: this.simSid, + payload: this.payload, + status: this.status, + direction: this.direction, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SmsCommandSolution { +} + +export interface SmsCommandListInstance { + _version: V1; + _solution: SmsCommandSolution; + _uri: string; + + (sid: string, ): SmsCommandContext; + get(sid: string, ): SmsCommandContext; + + + + + /** + * Create a SmsCommandInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SmsCommandInstance + */ + create(params: SmsCommandListInstanceCreateOptions, callback?: (error: Error | null, item?: SmsCommandInstance) => any): Promise<SmsCommandInstance>; + + /** + * Create a SmsCommandInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SmsCommandInstance with HTTP metadata + */ + createWithHttpInfo(params: SmsCommandListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SmsCommandInstance>) => any): Promise<ApiResponse<SmsCommandInstance>>; + + + + + /** + * Streams SmsCommandInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SmsCommandListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SmsCommandInstance, done: (err?: Error) => void) => void): void; + each(params: SmsCommandListInstanceEachOptions, callback?: (item: SmsCommandInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SmsCommandInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SmsCommandListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SmsCommandInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SmsCommandListInstanceEachOptions, callback?: (item: SmsCommandInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SmsCommandInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SmsCommandPage) => any): Promise<SmsCommandPage>; + /** + * Retrieve a single target page of SmsCommandInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SmsCommandPage>) => any): Promise<ApiResponse<SmsCommandPage>>; + /** + * Lists SmsCommandInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SmsCommandListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SmsCommandInstance[]) => any): Promise<SmsCommandInstance[]>; + list(params: SmsCommandListInstanceOptions, callback?: (error: Error | null, items: SmsCommandInstance[]) => any): Promise<SmsCommandInstance[]>; + /** + * Lists SmsCommandInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SmsCommandListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SmsCommandInstance[]>) => any): Promise<ApiResponse<SmsCommandInstance[]>>; + listWithHttpInfo(params: SmsCommandListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SmsCommandInstance[]>) => any): Promise<ApiResponse<SmsCommandInstance[]>>; + /** + * Retrieve a single page of SmsCommandInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SmsCommandListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SmsCommandPage) => any): Promise<SmsCommandPage>; + page(params: SmsCommandListInstancePageOptions, callback?: (error: Error | null, items: SmsCommandPage) => any): Promise<SmsCommandPage>; + /** + * Retrieve a single page of SmsCommandInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SmsCommandListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SmsCommandPage>) => any): Promise<ApiResponse<SmsCommandPage>>; + pageWithHttpInfo(params: SmsCommandListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SmsCommandPage>) => any): Promise<ApiResponse<SmsCommandPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SmsCommandListInstance(version: V1): SmsCommandListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SmsCommandListInstance; + + instance.get = function get(sid, ): SmsCommandContext { + return new SmsCommandContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/SmsCommands`; + + instance.create = function create(params: SmsCommandListInstanceCreateOptions, callback?: (error: Error | null, items: SmsCommandInstance) => any): Promise<SmsCommandInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["sim"] === null || params["sim"] === undefined) { + throw new Error('Required parameter "params[\'sim\']" missing.'); + } + + if (params["payload"] === null || params["payload"] === undefined) { + throw new Error('Required parameter "params[\'payload\']" missing.'); + } + + let data: any = {}; + + + + data["Sim"] = params["sim"]; + + data["Payload"] = params["payload"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SmsCommandInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SmsCommandListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<SmsCommandInstance>) => any): Promise<ApiResponse<SmsCommandInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["sim"] === null || params["sim"] === undefined) { + throw new Error('Required parameter "params[\'sim\']" missing.'); + } + + if (params["payload"] === null || params["payload"] === undefined) { + throw new Error('Required parameter "params[\'payload\']" missing.'); + } + + let data: any = {}; + + + + data["Sim"] = params["sim"]; + + data["Payload"] = params["payload"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SmsCommandResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SmsCommandInstance> => ({ + ...response, + body: new SmsCommandInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SmsCommandListInstancePageOptions | ((error: Error | null, items: SmsCommandPage) => any), callback?: (error: Error | null, items: SmsCommandPage) => any): Promise<SmsCommandPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SmsCommandPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SmsCommandPage) => any): Promise<SmsCommandPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SmsCommandPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SmsCommandListInstancePageOptions | ((error: Error | null, items: ApiResponse<SmsCommandPage>) => any), callback?: (error: Error | null, items: ApiResponse<SmsCommandPage>) => any): Promise<ApiResponse<SmsCommandPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SmsCommandPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SmsCommandPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SmsCommandPage>) => any): Promise<ApiResponse<SmsCommandPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SmsCommandPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SmsCommandPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SmsCommandPage extends Page<V1, SmsCommandPayload, SmsCommandResource, SmsCommandInstance> { +/** +* Initialize the SmsCommandPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SmsCommandSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SmsCommandInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SmsCommandResource): SmsCommandInstance { + + return new SmsCommandInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/supersim/v1/usageRecord.ts b/rest/supersim/v1/usageRecord.ts new file mode 100644 index 000000000..538dc19d0 --- /dev/null +++ b/rest/supersim/v1/usageRecord.ts @@ -0,0 +1,538 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Supersim + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + */ +export type UsageRecordGranularity = 'hour'|'day'|'all'; + +/** + * Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + */ +export type UsageRecordGroup = 'sim'|'fleet'|'network'|'isoCountry'; + + +/** + * Options to pass to each + */ +export interface UsageRecordListInstanceEachOptions { + /** SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. */ + "sim"?: string; + /** SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. */ + "fleet"?: string; + /** SID of a Network resource. Only show UsageRecords representing usage on this network. */ + "network"?: string; + /** Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. */ + "isoCountry"?: string; + /** Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. */ + "group"?: UsageRecordGroup; + /** Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. */ + "granularity"?: UsageRecordGranularity; + /** Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. */ + "startTime"?: Date; + /** Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. */ + "endTime"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UsageRecordListInstanceOptions { + /** SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. */ + "sim"?: string; + /** SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. */ + "fleet"?: string; + /** SID of a Network resource. Only show UsageRecords representing usage on this network. */ + "network"?: string; + /** Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. */ + "isoCountry"?: string; + /** Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. */ + "group"?: UsageRecordGroup; + /** Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. */ + "granularity"?: UsageRecordGranularity; + /** Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. */ + "startTime"?: Date; + /** Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. */ + "endTime"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UsageRecordListInstancePageOptions { + /** SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. */ + "sim"?: string; + /** SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. */ + "fleet"?: string; + /** SID of a Network resource. Only show UsageRecords representing usage on this network. */ + "network"?: string; + /** Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. */ + "isoCountry"?: string; + /** Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. */ + "group"?: UsageRecordGroup; + /** Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. */ + "granularity"?: UsageRecordGranularity; + /** Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. */ + "startTime"?: Date; + /** Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. */ + "endTime"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface UsageRecordSolution { +} + +export interface UsageRecordListInstance { + _version: V1; + _solution: UsageRecordSolution; + _uri: string; + + + + + /** + * Streams UsageRecordInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + each(params: UsageRecordListInstanceEachOptions, callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UsageRecordInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UsageRecordListInstanceEachOptions, callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UsageRecordInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage>; + /** + * Retrieve a single target page of UsageRecordInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>>; + /** + * Lists UsageRecordInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UsageRecordInstance[]) => any): Promise<UsageRecordInstance[]>; + list(params: UsageRecordListInstanceOptions, callback?: (error: Error | null, items: UsageRecordInstance[]) => any): Promise<UsageRecordInstance[]>; + /** + * Lists UsageRecordInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UsageRecordInstance[]>) => any): Promise<ApiResponse<UsageRecordInstance[]>>; + listWithHttpInfo(params: UsageRecordListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<UsageRecordInstance[]>) => any): Promise<ApiResponse<UsageRecordInstance[]>>; + /** + * Retrieve a single page of UsageRecordInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage>; + page(params: UsageRecordListInstancePageOptions, callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage>; + /** + * Retrieve a single page of UsageRecordInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>>; + pageWithHttpInfo(params: UsageRecordListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UsageRecordListInstance(version: V1): UsageRecordListInstance { + const instance = {} as UsageRecordListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/UsageRecords`; + + instance.page = function page(params?: UsageRecordListInstancePageOptions | ((error: Error | null, items: UsageRecordPage) => any), callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["fleet"] !== undefined) + data["Fleet"] = params["fleet"]; + if (params["network"] !== undefined) + data["Network"] = params["network"]; + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["group"] !== undefined) + data["Group"] = params["group"]; + if (params["granularity"] !== undefined) + data["Granularity"] = params["granularity"]; + if (params["startTime"] !== undefined) + data["StartTime"] = serialize.iso8601DateTime(params["startTime"]); + if (params["endTime"] !== undefined) + data["EndTime"] = serialize.iso8601DateTime(params["endTime"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UsageRecordPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UsageRecordPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UsageRecordListInstancePageOptions | ((error: Error | null, items: ApiResponse<UsageRecordPage>) => any), callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["fleet"] !== undefined) + data["Fleet"] = params["fleet"]; + if (params["network"] !== undefined) + data["Network"] = params["network"]; + if (params["isoCountry"] !== undefined) + data["IsoCountry"] = params["isoCountry"]; + if (params["group"] !== undefined) + data["Group"] = params["group"]; + if (params["granularity"] !== undefined) + data["Granularity"] = params["granularity"]; + if (params["startTime"] !== undefined) + data["StartTime"] = serialize.iso8601DateTime(params["startTime"]); + if (params["endTime"] !== undefined) + data["EndTime"] = serialize.iso8601DateTime(params["endTime"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<UsageRecordPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UsageRecordPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<UsageRecordPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UsageRecordPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface UsageRecordPayload extends TwilioResponsePayload { + usage_records: UsageRecordResource[]; +} + +interface UsageRecordResource { + account_sid: string; + sim_sid: string; + network_sid: string; + fleet_sid: string; + iso_country: string; + period: any; + data_upload: number; + data_download: number; + data_total: number; + data_total_billed: number; + billed_unit: string; +} + +export class UsageRecordInstance { + + constructor(protected _version: V1, payload: UsageRecordResource) { + + this.accountSid = (payload.account_sid); + this.simSid = (payload.sim_sid); + this.networkSid = (payload.network_sid); + this.fleetSid = (payload.fleet_sid); + this.isoCountry = (payload.iso_country); + this.period = (payload.period); + this.dataUpload = (payload.data_upload); + this.dataDownload = (payload.data_download); + this.dataTotal = (payload.data_total); + this.dataTotalBilled = (payload.data_total_billed); + this.billedUnit = (payload.billed_unit); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that incurred the usage. + */ + accountSid: string; + /** + * SID of a Sim resource to which the UsageRecord belongs. Value will only be present when either a value for the `Sim` query parameter is provided or when UsageRecords are grouped by `sim`. Otherwise, the value will be `null`. + */ + simSid: string; + /** + * SID of the Network resource the usage occurred on. Value will only be present when either a value for the `Network` query parameter is provided or when UsageRecords are grouped by `network`. Otherwise, the value will be `null`. + */ + networkSid: string; + /** + * SID of the Fleet resource the usage occurred on. Value will only be present when either a value for the `Fleet` query parameter is provided or when UsageRecords are grouped by `fleet`. Otherwise, the value will be `null`. + */ + fleetSid: string; + /** + * Alpha-2 ISO Country Code that the usage occurred in. Value will only be present when either a value for the `IsoCountry` query parameter is provided or when UsageRecords are grouped by `isoCountry`. Otherwise, the value will be `null`. + */ + isoCountry: string; + /** + * The time period for which the usage is reported. The period is represented as a pair of `start_time` and `end_time` timestamps specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + period: any; + /** + * Total data uploaded in bytes, aggregated by the query parameters. + */ + dataUpload: number; + /** + * Total data downloaded in bytes, aggregated by the query parameters. + */ + dataDownload: number; + /** + * Total of data_upload and data_download. + */ + dataTotal: number; + /** + * Total amount in the `billed_unit` that was charged for the data uploaded or downloaded. Will return 0 for usage prior to February 1, 2022. Value may be 0 despite `data_total` being greater than 0 if the data usage is still being processed by Twilio\'s billing system. Refer to [Data Usage Processing](https://www.twilio.com/docs/iot/supersim/api/usage-record-resource#data-usage-processing) for more details. + */ + dataTotalBilled: number; + /** + * The currency in which the billed amounts are measured, specified in the 3 letter ISO 4127 format (e.g. `USD`, `EUR`, `JPY`). This can be null when data_toal_billed is 0 and we do not yet have billing information for the corresponding data usage. Refer to [Data Usage Processing](https://www.twilio.com/docs/iot/supersim/api/usage-record-resource#data-usage-processing) for more details. + */ + billedUnit: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + simSid: this.simSid, + networkSid: this.networkSid, + fleetSid: this.fleetSid, + isoCountry: this.isoCountry, + period: this.period, + dataUpload: this.dataUpload, + dataDownload: this.dataDownload, + dataTotal: this.dataTotal, + dataTotalBilled: this.dataTotalBilled, + billedUnit: this.billedUnit, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class UsageRecordPage extends Page<V1, UsageRecordPayload, UsageRecordResource, UsageRecordInstance> { +/** +* Initialize the UsageRecordPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: UsageRecordSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UsageRecordInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UsageRecordResource): UsageRecordInstance { + + return new UsageRecordInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/V1.ts b/rest/sync/V1.ts new file mode 100644 index 000000000..6cc2a05a2 --- /dev/null +++ b/rest/sync/V1.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import SyncBase from "../SyncBase"; +import Version from "../../base/Version"; +import { ServiceListInstance } from "./v1/service"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Sync + * + * @param domain - The Twilio (Twilio.Sync) domain + */ + constructor(domain: SyncBase) { + super(domain, "v1"); + } + + /** services - { Twilio.Sync.V1.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + +} diff --git a/rest/sync/v1/service.ts b/rest/sync/v1/service.ts new file mode 100644 index 000000000..75ce1994e --- /dev/null +++ b/rest/sync/v1/service.ts @@ -0,0 +1,1091 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { DocumentListInstance } from "./service/document"; +import { SyncListListInstance } from "./service/syncList"; +import { SyncMapListInstance } from "./service/syncMap"; +import { SyncStreamListInstance } from "./service/syncStream"; + + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** The URL we should call when Sync objects are manipulated. */ + "webhookUrl"?: string; + /** A string that you assign to describe the resource. */ + "friendlyName"?: string; + /** Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. */ + "reachabilityWebhooksEnabled"?: boolean; + /** Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. */ + "aclEnabled"?: boolean; + /** Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. */ + "reachabilityDebouncingEnabled"?: boolean; + /** The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. */ + "reachabilityDebouncingWindow"?: number; + /** Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. */ + "webhooksFromRestEnabled"?: boolean; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** A string that you assign to describe the resource. */ + "friendlyName"?: string; + /** The URL we should call when Sync objects are manipulated. */ + "webhookUrl"?: string; + /** Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. */ + "reachabilityWebhooksEnabled"?: boolean; + /** Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. */ + "aclEnabled"?: boolean; + /** Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. */ + "reachabilityDebouncingEnabled"?: boolean; + /** The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. */ + "reachabilityDebouncingWindow"?: number; + /** Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. */ + "webhooksFromRestEnabled"?: boolean; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + documents: DocumentListInstance; + syncLists: SyncListListInstance; + syncMaps: SyncMapListInstance; + syncStreams: SyncStreamListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _documents?: DocumentListInstance; + protected _syncLists?: SyncListListInstance; + protected _syncMaps?: SyncMapListInstance; + protected _syncStreams?: SyncStreamListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get documents(): DocumentListInstance { + this._documents = this._documents || DocumentListInstance(this._version, this._solution.sid); + return this._documents; + } + + get syncLists(): SyncListListInstance { + this._syncLists = this._syncLists || SyncListListInstance(this._version, this._solution.sid); + return this._syncLists; + } + + get syncMaps(): SyncMapListInstance { + this._syncMaps = this._syncMaps || SyncMapListInstance(this._version, this._solution.sid); + return this._syncMaps; + } + + get syncStreams(): SyncStreamListInstance { + this._syncStreams = this._syncStreams || SyncStreamListInstance(this._version, this._solution.sid); + return this._syncStreams; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["reachabilityWebhooksEnabled"] !== undefined) + data["ReachabilityWebhooksEnabled"] = serialize.bool(params["reachabilityWebhooksEnabled"]); + if (params["aclEnabled"] !== undefined) + data["AclEnabled"] = serialize.bool(params["aclEnabled"]); + if (params["reachabilityDebouncingEnabled"] !== undefined) + data["ReachabilityDebouncingEnabled"] = serialize.bool(params["reachabilityDebouncingEnabled"]); + if (params["reachabilityDebouncingWindow"] !== undefined) + data["ReachabilityDebouncingWindow"] = params["reachabilityDebouncingWindow"]; + if (params["webhooksFromRestEnabled"] !== undefined) + data["WebhooksFromRestEnabled"] = serialize.bool(params["webhooksFromRestEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ServiceInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["reachabilityWebhooksEnabled"] !== undefined) + data["ReachabilityWebhooksEnabled"] = serialize.bool(params["reachabilityWebhooksEnabled"]); + if (params["aclEnabled"] !== undefined) + data["AclEnabled"] = serialize.bool(params["aclEnabled"]); + if (params["reachabilityDebouncingEnabled"] !== undefined) + data["ReachabilityDebouncingEnabled"] = serialize.bool(params["reachabilityDebouncingEnabled"]); + if (params["reachabilityDebouncingWindow"] !== undefined) + data["ReachabilityDebouncingWindow"] = params["reachabilityDebouncingWindow"]; + if (params["webhooksFromRestEnabled"] !== undefined) + data["WebhooksFromRestEnabled"] = serialize.bool(params["webhooksFromRestEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + sid: string; + unique_name: string; + account_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + url: string; + webhook_url: string; + webhooks_from_rest_enabled: boolean; + reachability_webhooks_enabled: boolean; + acl_enabled: boolean; + reachability_debouncing_enabled: boolean; + reachability_debouncing_window: number; + links: Record<string, string>; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V1, payload: ServiceResource, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.webhookUrl = (payload.webhook_url); + this.webhooksFromRestEnabled = (payload.webhooks_from_rest_enabled); + this.reachabilityWebhooksEnabled = (payload.reachability_webhooks_enabled); + this.aclEnabled = (payload.acl_enabled); + this.reachabilityDebouncingEnabled = (payload.reachability_debouncing_enabled); + this.reachabilityDebouncingWindow = deserialize.integer(payload.reachability_debouncing_window); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Service resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. It is a read-only property, it cannot be assigned using REST API. + */ + uniqueName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Service resource. + */ + url: string; + /** + * The URL we call when Sync objects are manipulated. + */ + webhookUrl: string; + /** + * Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + */ + webhooksFromRestEnabled: boolean; + /** + * Whether the service instance calls `webhook_url` when client endpoints connect to Sync. The default is `false`. + */ + reachabilityWebhooksEnabled: boolean; + /** + * Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. It is disabled (false) by default. + */ + aclEnabled: boolean; + /** + * Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + */ + reachabilityDebouncingEnabled: boolean; + /** + * The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before `webhook_url` is called, if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the reachability event from occurring. + */ + reachabilityDebouncingWindow: number; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the documents. + */ + documents(): DocumentListInstance { + return this._proxy.documents; + } + + /** + * Access the syncLists. + */ + syncLists(): SyncListListInstance { + return this._proxy.syncLists; + } + + /** + * Access the syncMaps. + */ + syncMaps(): SyncMapListInstance { + return this._proxy.syncMaps; + } + + /** + * Access the syncStreams. + */ + syncStreams(): SyncStreamListInstance { + return this._proxy.syncStreams; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + webhookUrl: this.webhookUrl, + webhooksFromRestEnabled: this.webhooksFromRestEnabled, + reachabilityWebhooksEnabled: this.reachabilityWebhooksEnabled, + aclEnabled: this.aclEnabled, + reachabilityDebouncingEnabled: this.reachabilityDebouncingEnabled, + reachabilityDebouncingWindow: this.reachabilityDebouncingWindow, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V1; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V1): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params?: ServiceListInstanceCreateOptions | ((error: Error | null, items: ServiceInstance) => any), callback?: (error: Error | null, items: ServiceInstance) => any): Promise<ServiceInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["reachabilityWebhooksEnabled"] !== undefined) + data["ReachabilityWebhooksEnabled"] = serialize.bool(params["reachabilityWebhooksEnabled"]); + if (params["aclEnabled"] !== undefined) + data["AclEnabled"] = serialize.bool(params["aclEnabled"]); + if (params["reachabilityDebouncingEnabled"] !== undefined) + data["ReachabilityDebouncingEnabled"] = serialize.bool(params["reachabilityDebouncingEnabled"]); + if (params["reachabilityDebouncingWindow"] !== undefined) + data["ReachabilityDebouncingWindow"] = params["reachabilityDebouncingWindow"]; + if (params["webhooksFromRestEnabled"] !== undefined) + data["WebhooksFromRestEnabled"] = serialize.bool(params["webhooksFromRestEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ServiceListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<ServiceInstance>) => any), callback?: (error: Error | null, items: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["reachabilityWebhooksEnabled"] !== undefined) + data["ReachabilityWebhooksEnabled"] = serialize.bool(params["reachabilityWebhooksEnabled"]); + if (params["aclEnabled"] !== undefined) + data["AclEnabled"] = serialize.bool(params["aclEnabled"]); + if (params["reachabilityDebouncingEnabled"] !== undefined) + data["ReachabilityDebouncingEnabled"] = serialize.bool(params["reachabilityDebouncingEnabled"]); + if (params["reachabilityDebouncingWindow"] !== undefined) + data["ReachabilityDebouncingWindow"] = params["reachabilityDebouncingWindow"]; + if (params["webhooksFromRestEnabled"] !== undefined) + data["WebhooksFromRestEnabled"] = serialize.bool(params["webhooksFromRestEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse<ServicePage>) => any), callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page<V1, ServicePayload, ServiceResource, ServiceInstance> { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/v1/service/document.ts b/rest/sync/v1/service/document.ts new file mode 100644 index 000000000..9eb68f907 --- /dev/null +++ b/rest/sync/v1/service/document.ts @@ -0,0 +1,993 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { DocumentPermissionListInstance } from "./document/documentPermission"; + + + + + +/** + * Options to pass to update a DocumentInstance + */ +export interface DocumentContextUpdateOptions { + /** The If-Match HTTP request header */ + "ifMatch"?: string; + /** A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. */ + "data"?: any; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). */ + "ttl"?: number; +} + +/** + * Options to pass to create a DocumentInstance + */ +export interface DocumentListInstanceCreateOptions { + /** An application-defined string that uniquely identifies the Sync Document */ + "uniqueName"?: string; + /** A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. */ + "data"?: any; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document\\\'s time-to-live). */ + "ttl"?: number; +} + +/** + * Options to pass to each + */ +export interface DocumentListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DocumentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DocumentListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DocumentListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface DocumentContext { + documentPermissions: DocumentPermissionListInstance; + + /** + * Remove a DocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a DocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a DocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance + */ + fetch(callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance> + + /** + * Fetch a DocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>> + + /** + * Update a DocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance + */ + update(callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance>; + /** + * Update a DocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance + */ + update(params: DocumentContextUpdateOptions, callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance>; + + /** + * Update a DocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>>; + /** + * Update a DocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance with HTTP metadata + */ + updateWithHttpInfo(params: DocumentContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DocumentContextSolution { + "serviceSid": string; + "sid": string; +} + +export class DocumentContextImpl implements DocumentContext { + protected _solution: DocumentContextSolution; + protected _uri: string; + + protected _documentPermissions?: DocumentPermissionListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Documents/${sid}`; + } + + get documentPermissions(): DocumentPermissionListInstance { + this._documentPermissions = this._documentPermissions || DocumentPermissionListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._documentPermissions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DocumentInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DocumentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DocumentInstance> => ({ + ...response, + body: new DocumentInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: DocumentContextUpdateOptions | ((error: Error | null, item?: DocumentInstance) => any),callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["data"] !== undefined) + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DocumentInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: DocumentContextUpdateOptions | ((error: Error | null, item?: ApiResponse<DocumentInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["data"] !== undefined) + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<DocumentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<DocumentInstance> => ({ + ...response, + body: new DocumentInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DocumentPayload extends TwilioResponsePayload { + documents: DocumentResource[]; +} + +interface DocumentResource { + sid: string; + unique_name: string; + account_sid: string; + service_sid: string; + url: string; + links: Record<string, string>; + revision: string; + data: any; + date_expires: Date; + date_created: Date; + date_updated: Date; + created_by: string; +} + +export class DocumentInstance { + protected _solution: DocumentContextSolution; + protected _context?: DocumentContext; + + constructor(protected _version: V1, payload: DocumentResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.url = (payload.url); + this.links = (payload.links); + this.revision = (payload.revision); + this.data = (payload.data); + this.dateExpires = deserialize.iso8601DateTime(payload.date_expires); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Document resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource and can be up to 320 characters long. + */ + uniqueName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document resource. + */ + accountSid: string; + /** + * The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The absolute URL of the Document resource. + */ + url: string; + /** + * The URLs of resources related to the Sync Document. + */ + links: Record<string, string>; + /** + * The current revision of the Sync Document, represented as a string. The `revision` property is used with conditional updates to ensure data consistency. + */ + revision: string; + /** + * An arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + */ + data: any; + /** + * The date and time in GMT when the Sync Document expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Sync Document does not expire, this value is `null`. The Document resource might not be deleted immediately after it expires. + */ + dateExpires: Date; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The identity of the Sync Document\'s creator. If the Sync Document is created from the client SDK, the value matches the Access Token\'s `identity` field. If the Sync Document was created from the REST API, the value is `system`. + */ + createdBy: string; + + private get _proxy(): DocumentContext { + this._context = this._context || new DocumentContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a DocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a DocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a DocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance + */ + fetch(callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a DocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance + */ + update(callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance>; + /** + * Update a DocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance + */ + update(params: DocumentContextUpdateOptions, callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance>; + + update(params?: any, callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a DocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>>; + /** + * Update a DocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance with HTTP metadata + */ + updateWithHttpInfo(params: DocumentContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the documentPermissions. + */ + documentPermissions(): DocumentPermissionListInstance { + return this._proxy.documentPermissions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + url: this.url, + links: this.links, + revision: this.revision, + data: this.data, + dateExpires: this.dateExpires, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DocumentSolution { + serviceSid: string; +} + +export interface DocumentListInstance { + _version: V1; + _solution: DocumentSolution; + _uri: string; + + (sid: string, ): DocumentContext; + get(sid: string, ): DocumentContext; + + + + + + + + + /** + * Create a DocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance + */ + create(callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance>; + /** + * Create a DocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance + */ + create(params: DocumentListInstanceCreateOptions, callback?: (error: Error | null, item?: DocumentInstance) => any): Promise<DocumentInstance>; + + /** + * Create a DocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>>; + /** + * Create a DocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentInstance with HTTP metadata + */ + createWithHttpInfo(params: DocumentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>>; + + + + + /** + * Streams DocumentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DocumentInstance, done: (err?: Error) => void) => void): void; + each(params: DocumentListInstanceEachOptions, callback?: (item: DocumentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DocumentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DocumentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DocumentListInstanceEachOptions, callback?: (item: DocumentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DocumentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DocumentPage) => any): Promise<DocumentPage>; + /** + * Retrieve a single target page of DocumentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<DocumentPage>) => any): Promise<ApiResponse<DocumentPage>>; + /** + * Lists DocumentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DocumentInstance[]) => any): Promise<DocumentInstance[]>; + list(params: DocumentListInstanceOptions, callback?: (error: Error | null, items: DocumentInstance[]) => any): Promise<DocumentInstance[]>; + /** + * Lists DocumentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DocumentInstance[]>) => any): Promise<ApiResponse<DocumentInstance[]>>; + listWithHttpInfo(params: DocumentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<DocumentInstance[]>) => any): Promise<ApiResponse<DocumentInstance[]>>; + /** + * Retrieve a single page of DocumentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DocumentPage) => any): Promise<DocumentPage>; + page(params: DocumentListInstancePageOptions, callback?: (error: Error | null, items: DocumentPage) => any): Promise<DocumentPage>; + /** + * Retrieve a single page of DocumentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DocumentPage>) => any): Promise<ApiResponse<DocumentPage>>; + pageWithHttpInfo(params: DocumentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<DocumentPage>) => any): Promise<ApiResponse<DocumentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DocumentListInstance(version: V1, serviceSid: string): DocumentListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as DocumentListInstance; + + instance.get = function get(sid, ): DocumentContext { + return new DocumentContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Documents`; + + instance.create = function create(params?: DocumentListInstanceCreateOptions | ((error: Error | null, items: DocumentInstance) => any), callback?: (error: Error | null, items: DocumentInstance) => any): Promise<DocumentInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["data"] !== undefined) + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DocumentInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: DocumentListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<DocumentInstance>) => any), callback?: (error: Error | null, items: ApiResponse<DocumentInstance>) => any): Promise<ApiResponse<DocumentInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["data"] !== undefined) + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<DocumentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<DocumentInstance> => ({ + ...response, + body: new DocumentInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: DocumentListInstancePageOptions | ((error: Error | null, items: DocumentPage) => any), callback?: (error: Error | null, items: DocumentPage) => any): Promise<DocumentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DocumentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DocumentPage) => any): Promise<DocumentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DocumentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DocumentListInstancePageOptions | ((error: Error | null, items: ApiResponse<DocumentPage>) => any), callback?: (error: Error | null, items: ApiResponse<DocumentPage>) => any): Promise<ApiResponse<DocumentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<DocumentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DocumentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<DocumentPage>) => any): Promise<ApiResponse<DocumentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<DocumentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DocumentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class DocumentPage extends Page<V1, DocumentPayload, DocumentResource, DocumentInstance> { +/** +* Initialize the DocumentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: DocumentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DocumentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DocumentResource): DocumentInstance { + + return new DocumentInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/v1/service/document/documentPermission.ts b/rest/sync/v1/service/document/documentPermission.ts new file mode 100644 index 000000000..11d2f985a --- /dev/null +++ b/rest/sync/v1/service/document/documentPermission.ts @@ -0,0 +1,824 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a DocumentPermissionInstance + */ +export interface DocumentPermissionContextUpdateOptions { + /** Whether the identity can read the Sync Document. Default value is `false`. */ + "read": boolean; + /** Whether the identity can update the Sync Document. Default value is `false`. */ + "write": boolean; + /** Whether the identity can delete the Sync Document. Default value is `false`. */ + "manage": boolean; +} + +/** + * Options to pass to each + */ +export interface DocumentPermissionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DocumentPermissionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DocumentPermissionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DocumentPermissionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface DocumentPermissionContext { + + /** + * Remove a DocumentPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a DocumentPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a DocumentPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentPermissionInstance + */ + fetch(callback?: (error: Error | null, item?: DocumentPermissionInstance) => any): Promise<DocumentPermissionInstance> + + /** + * Fetch a DocumentPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentPermissionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DocumentPermissionInstance>) => any): Promise<ApiResponse<DocumentPermissionInstance>> + + /** + * Update a DocumentPermissionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentPermissionInstance + */ + update(params: DocumentPermissionContextUpdateOptions, callback?: (error: Error | null, item?: DocumentPermissionInstance) => any): Promise<DocumentPermissionInstance>; + + /** + * Update a DocumentPermissionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentPermissionInstance with HTTP metadata + */ + updateWithHttpInfo(params: DocumentPermissionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<DocumentPermissionInstance>) => any): Promise<ApiResponse<DocumentPermissionInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface DocumentPermissionContextSolution { + "serviceSid": string; + "documentSid": string; + "identity": string; +} + +export class DocumentPermissionContextImpl implements DocumentPermissionContext { + protected _solution: DocumentPermissionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, documentSid: string, identity: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(documentSid)) { + throw new Error('Parameter \'documentSid\' is not valid.'); + } + + if (!isValidPathParam(identity)) { + throw new Error('Parameter \'identity\' is not valid.'); + } + + this._solution = { serviceSid, documentSid, identity, }; + this._uri = `/Services/${serviceSid}/Documents/${documentSid}/Permissions/${identity}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: DocumentPermissionInstance) => any): Promise<DocumentPermissionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DocumentPermissionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.documentSid, instance._solution.identity)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DocumentPermissionInstance>) => any): Promise<ApiResponse<DocumentPermissionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DocumentPermissionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DocumentPermissionInstance> => ({ + ...response, + body: new DocumentPermissionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.documentSid, instance._solution.identity) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: DocumentPermissionContextUpdateOptions,callback?: (error: Error | null, item?: DocumentPermissionInstance) => any): Promise<DocumentPermissionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["read"] === null || params["read"] === undefined) { + throw new Error('Required parameter "params[\'read\']" missing.'); + } + + if (params["write"] === null || params["write"] === undefined) { + throw new Error('Required parameter "params[\'write\']" missing.'); + } + + if (params["manage"] === null || params["manage"] === undefined) { + throw new Error('Required parameter "params[\'manage\']" missing.'); + } + + let data: any = {}; + + + + data["Read"] = serialize.bool(params["read"]); + + data["Write"] = serialize.bool(params["write"]); + + data["Manage"] = serialize.bool(params["manage"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DocumentPermissionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.documentSid, instance._solution.identity)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: DocumentPermissionContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<DocumentPermissionInstance>) => any): Promise<ApiResponse<DocumentPermissionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["read"] === null || params["read"] === undefined) { + throw new Error('Required parameter "params[\'read\']" missing.'); + } + + if (params["write"] === null || params["write"] === undefined) { + throw new Error('Required parameter "params[\'write\']" missing.'); + } + + if (params["manage"] === null || params["manage"] === undefined) { + throw new Error('Required parameter "params[\'manage\']" missing.'); + } + + let data: any = {}; + + + + data["Read"] = serialize.bool(params["read"]); + + data["Write"] = serialize.bool(params["write"]); + + data["Manage"] = serialize.bool(params["manage"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<DocumentPermissionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<DocumentPermissionInstance> => ({ + ...response, + body: new DocumentPermissionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.documentSid, instance._solution.identity) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface DocumentPermissionPayload extends TwilioResponsePayload { + permissions: DocumentPermissionResource[]; +} + +interface DocumentPermissionResource { + account_sid: string; + service_sid: string; + document_sid: string; + identity: string; + read: boolean; + write: boolean; + manage: boolean; + url: string; +} + +export class DocumentPermissionInstance { + protected _solution: DocumentPermissionContextSolution; + protected _context?: DocumentPermissionContext; + + constructor(protected _version: V1, payload: DocumentPermissionResource, serviceSid: string, documentSid: string, identity?: string) { + + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.documentSid = (payload.document_sid); + this.identity = (payload.identity); + this.read = (payload.read); + this.write = (payload.write); + this.manage = (payload.manage); + this.url = (payload.url); + + this._solution = { serviceSid, documentSid, identity: identity, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document Permission resource. + */ + accountSid: string; + /** + * The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the Sync Document to which the Document Permission applies. + */ + documentSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s User within the Service to an FPA token. + */ + identity: string; + /** + * Whether the identity can read the Sync Document. + */ + read: boolean; + /** + * Whether the identity can update the Sync Document. + */ + write: boolean; + /** + * Whether the identity can delete the Sync Document. + */ + manage: boolean; + /** + * The absolute URL of the Sync Document Permission resource. + */ + url: string; + + private get _proxy(): DocumentPermissionContext { + this._context = this._context || new DocumentPermissionContextImpl(this._version, this._solution.serviceSid, this._solution.documentSid, this._solution.identity); + return this._context; + } + + /** + * Remove a DocumentPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a DocumentPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a DocumentPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentPermissionInstance + */ + fetch(callback?: (error: Error | null, item?: DocumentPermissionInstance) => any): Promise<DocumentPermissionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a DocumentPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentPermissionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DocumentPermissionInstance>) => any): Promise<ApiResponse<DocumentPermissionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a DocumentPermissionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentPermissionInstance + */ + update(params: DocumentPermissionContextUpdateOptions, callback?: (error: Error | null, item?: DocumentPermissionInstance) => any): Promise<DocumentPermissionInstance>; + + update(params?: any, callback?: (error: Error | null, item?: DocumentPermissionInstance) => any): Promise<DocumentPermissionInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a DocumentPermissionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DocumentPermissionInstance with HTTP metadata + */ + updateWithHttpInfo(params: DocumentPermissionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<DocumentPermissionInstance>) => any): Promise<ApiResponse<DocumentPermissionInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<DocumentPermissionInstance>) => any): Promise<ApiResponse<DocumentPermissionInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + serviceSid: this.serviceSid, + documentSid: this.documentSid, + identity: this.identity, + read: this.read, + write: this.write, + manage: this.manage, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface DocumentPermissionSolution { + serviceSid: string; + documentSid: string; +} + +export interface DocumentPermissionListInstance { + _version: V1; + _solution: DocumentPermissionSolution; + _uri: string; + + (identity: string, ): DocumentPermissionContext; + get(identity: string, ): DocumentPermissionContext; + + + + + + + + + + /** + * Streams DocumentPermissionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentPermissionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DocumentPermissionInstance, done: (err?: Error) => void) => void): void; + each(params: DocumentPermissionListInstanceEachOptions, callback?: (item: DocumentPermissionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DocumentPermissionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentPermissionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DocumentPermissionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DocumentPermissionListInstanceEachOptions, callback?: (item: DocumentPermissionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DocumentPermissionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DocumentPermissionPage) => any): Promise<DocumentPermissionPage>; + /** + * Retrieve a single target page of DocumentPermissionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<DocumentPermissionPage>) => any): Promise<ApiResponse<DocumentPermissionPage>>; + /** + * Lists DocumentPermissionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentPermissionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DocumentPermissionInstance[]) => any): Promise<DocumentPermissionInstance[]>; + list(params: DocumentPermissionListInstanceOptions, callback?: (error: Error | null, items: DocumentPermissionInstance[]) => any): Promise<DocumentPermissionInstance[]>; + /** + * Lists DocumentPermissionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentPermissionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DocumentPermissionInstance[]>) => any): Promise<ApiResponse<DocumentPermissionInstance[]>>; + listWithHttpInfo(params: DocumentPermissionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<DocumentPermissionInstance[]>) => any): Promise<ApiResponse<DocumentPermissionInstance[]>>; + /** + * Retrieve a single page of DocumentPermissionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentPermissionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DocumentPermissionPage) => any): Promise<DocumentPermissionPage>; + page(params: DocumentPermissionListInstancePageOptions, callback?: (error: Error | null, items: DocumentPermissionPage) => any): Promise<DocumentPermissionPage>; + /** + * Retrieve a single page of DocumentPermissionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DocumentPermissionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DocumentPermissionPage>) => any): Promise<ApiResponse<DocumentPermissionPage>>; + pageWithHttpInfo(params: DocumentPermissionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<DocumentPermissionPage>) => any): Promise<ApiResponse<DocumentPermissionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DocumentPermissionListInstance(version: V1, serviceSid: string, documentSid: string): DocumentPermissionListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(documentSid)) { + throw new Error('Parameter \'documentSid\' is not valid.'); + } + + const instance = ((identity, ) => instance.get(identity, )) as DocumentPermissionListInstance; + + instance.get = function get(identity, ): DocumentPermissionContext { + return new DocumentPermissionContextImpl(version, serviceSid, documentSid, identity); + } + + instance._version = version; + instance._solution = { serviceSid, documentSid, }; + instance._uri = `/Services/${serviceSid}/Documents/${documentSid}/Permissions`; + + instance.page = function page(params?: DocumentPermissionListInstancePageOptions | ((error: Error | null, items: DocumentPermissionPage) => any), callback?: (error: Error | null, items: DocumentPermissionPage) => any): Promise<DocumentPermissionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DocumentPermissionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DocumentPermissionPage) => any): Promise<DocumentPermissionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DocumentPermissionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DocumentPermissionListInstancePageOptions | ((error: Error | null, items: ApiResponse<DocumentPermissionPage>) => any), callback?: (error: Error | null, items: ApiResponse<DocumentPermissionPage>) => any): Promise<ApiResponse<DocumentPermissionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<DocumentPermissionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DocumentPermissionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<DocumentPermissionPage>) => any): Promise<ApiResponse<DocumentPermissionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<DocumentPermissionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DocumentPermissionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class DocumentPermissionPage extends Page<V1, DocumentPermissionPayload, DocumentPermissionResource, DocumentPermissionInstance> { +/** +* Initialize the DocumentPermissionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: DocumentPermissionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DocumentPermissionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DocumentPermissionResource): DocumentPermissionInstance { + + return new DocumentPermissionInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.documentSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/v1/service/syncList.ts b/rest/sync/v1/service/syncList.ts new file mode 100644 index 000000000..8102de63b --- /dev/null +++ b/rest/sync/v1/service/syncList.ts @@ -0,0 +1,997 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { SyncListItemListInstance } from "./syncList/syncListItem"; +import { SyncListPermissionListInstance } from "./syncList/syncListPermission"; + + + + + +/** + * Options to pass to update a SyncListInstance + */ +export interface SyncListContextUpdateOptions { + /** An alias for `collection_ttl`. If both are provided, this value is ignored. */ + "ttl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. */ + "collectionTtl"?: number; +} + +/** + * Options to pass to create a SyncListInstance + */ +export interface SyncListListInstanceCreateOptions { + /** An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. */ + "uniqueName"?: string; + /** Alias for collection_ttl. If both are provided, this value is ignored. */ + "ttl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. */ + "collectionTtl"?: number; +} + +/** + * Options to pass to each + */ +export interface SyncListListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SyncListInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SyncListListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SyncListListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SyncListContext { + syncListItems: SyncListItemListInstance; + syncListPermissions: SyncListPermissionListInstance; + + /** + * Remove a SyncListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SyncListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SyncListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance + */ + fetch(callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance> + + /** + * Fetch a SyncListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>> + + /** + * Update a SyncListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance + */ + update(callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance>; + /** + * Update a SyncListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance + */ + update(params: SyncListContextUpdateOptions, callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance>; + + /** + * Update a SyncListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>>; + /** + * Update a SyncListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncListContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SyncListContextSolution { + "serviceSid": string; + "sid": string; +} + +export class SyncListContextImpl implements SyncListContext { + protected _solution: SyncListContextSolution; + protected _uri: string; + + protected _syncListItems?: SyncListItemListInstance; + protected _syncListPermissions?: SyncListPermissionListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Lists/${sid}`; + } + + get syncListItems(): SyncListItemListInstance { + this._syncListItems = this._syncListItems || SyncListItemListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._syncListItems; + } + + get syncListPermissions(): SyncListPermissionListInstance { + this._syncListPermissions = this._syncListPermissions || SyncListPermissionListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._syncListPermissions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SyncListInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SyncListResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SyncListInstance> => ({ + ...response, + body: new SyncListInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SyncListContextUpdateOptions | ((error: Error | null, item?: SyncListInstance) => any),callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncListInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SyncListContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SyncListInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SyncListResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncListInstance> => ({ + ...response, + body: new SyncListInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SyncListPayload extends TwilioResponsePayload { + lists: SyncListResource[]; +} + +interface SyncListResource { + sid: string; + unique_name: string; + account_sid: string; + service_sid: string; + url: string; + links: Record<string, string>; + revision: string; + date_expires: Date; + date_created: Date; + date_updated: Date; + created_by: string; +} + +export class SyncListInstance { + protected _solution: SyncListContextSolution; + protected _context?: SyncListContext; + + constructor(protected _version: V1, payload: SyncListResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.url = (payload.url); + this.links = (payload.links); + this.revision = (payload.revision); + this.dateExpires = deserialize.iso8601DateTime(payload.date_expires); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Sync List resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. + */ + uniqueName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync List resource. + */ + accountSid: string; + /** + * The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The absolute URL of the Sync List resource. + */ + url: string; + /** + * The URLs of the Sync List\'s nested resources. + */ + links: Record<string, string>; + /** + * The current revision of the Sync List, represented as a string. + */ + revision: string; + /** + * The date and time in GMT when the Sync List expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Sync List does not expire, this value is `null`. The Sync List might not be deleted immediately after it expires. + */ + dateExpires: Date; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The identity of the Sync List\'s creator. If the Sync List is created from the client SDK, the value matches the Access Token\'s `identity` field. If the Sync List was created from the REST API, the value is `system`. + */ + createdBy: string; + + private get _proxy(): SyncListContext { + this._context = this._context || new SyncListContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a SyncListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SyncListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SyncListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance + */ + fetch(callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SyncListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SyncListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance + */ + update(callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance>; + /** + * Update a SyncListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance + */ + update(params: SyncListContextUpdateOptions, callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SyncListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>>; + /** + * Update a SyncListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncListContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the syncListItems. + */ + syncListItems(): SyncListItemListInstance { + return this._proxy.syncListItems; + } + + /** + * Access the syncListPermissions. + */ + syncListPermissions(): SyncListPermissionListInstance { + return this._proxy.syncListPermissions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + url: this.url, + links: this.links, + revision: this.revision, + dateExpires: this.dateExpires, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SyncListSolution { + serviceSid: string; +} + +export interface SyncListListInstance { + _version: V1; + _solution: SyncListSolution; + _uri: string; + + (sid: string, ): SyncListContext; + get(sid: string, ): SyncListContext; + + + + + + + + + /** + * Create a SyncListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance + */ + create(callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance>; + /** + * Create a SyncListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance + */ + create(params: SyncListListInstanceCreateOptions, callback?: (error: Error | null, item?: SyncListInstance) => any): Promise<SyncListInstance>; + + /** + * Create a SyncListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>>; + /** + * Create a SyncListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListInstance with HTTP metadata + */ + createWithHttpInfo(params: SyncListListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>>; + + + + + /** + * Streams SyncListInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SyncListInstance, done: (err?: Error) => void) => void): void; + each(params: SyncListListInstanceEachOptions, callback?: (item: SyncListInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SyncListInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SyncListInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SyncListListInstanceEachOptions, callback?: (item: SyncListInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SyncListInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SyncListPage) => any): Promise<SyncListPage>; + /** + * Retrieve a single target page of SyncListInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SyncListPage>) => any): Promise<ApiResponse<SyncListPage>>; + /** + * Lists SyncListInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SyncListInstance[]) => any): Promise<SyncListInstance[]>; + list(params: SyncListListInstanceOptions, callback?: (error: Error | null, items: SyncListInstance[]) => any): Promise<SyncListInstance[]>; + /** + * Lists SyncListInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncListInstance[]>) => any): Promise<ApiResponse<SyncListInstance[]>>; + listWithHttpInfo(params: SyncListListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SyncListInstance[]>) => any): Promise<ApiResponse<SyncListInstance[]>>; + /** + * Retrieve a single page of SyncListInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SyncListPage) => any): Promise<SyncListPage>; + page(params: SyncListListInstancePageOptions, callback?: (error: Error | null, items: SyncListPage) => any): Promise<SyncListPage>; + /** + * Retrieve a single page of SyncListInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncListPage>) => any): Promise<ApiResponse<SyncListPage>>; + pageWithHttpInfo(params: SyncListListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SyncListPage>) => any): Promise<ApiResponse<SyncListPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SyncListListInstance(version: V1, serviceSid: string): SyncListListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as SyncListListInstance; + + instance.get = function get(sid, ): SyncListContext { + return new SyncListContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Lists`; + + instance.create = function create(params?: SyncListListInstanceCreateOptions | ((error: Error | null, items: SyncListInstance) => any), callback?: (error: Error | null, items: SyncListInstance) => any): Promise<SyncListInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncListInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: SyncListListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<SyncListInstance>) => any), callback?: (error: Error | null, items: ApiResponse<SyncListInstance>) => any): Promise<ApiResponse<SyncListInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SyncListResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncListInstance> => ({ + ...response, + body: new SyncListInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SyncListListInstancePageOptions | ((error: Error | null, items: SyncListPage) => any), callback?: (error: Error | null, items: SyncListPage) => any): Promise<SyncListPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SyncListPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SyncListPage) => any): Promise<SyncListPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SyncListPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SyncListListInstancePageOptions | ((error: Error | null, items: ApiResponse<SyncListPage>) => any), callback?: (error: Error | null, items: ApiResponse<SyncListPage>) => any): Promise<ApiResponse<SyncListPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SyncListPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncListPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SyncListPage>) => any): Promise<ApiResponse<SyncListPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SyncListPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncListPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SyncListPage extends Page<V1, SyncListPayload, SyncListResource, SyncListInstance> { +/** +* Initialize the SyncListPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SyncListSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SyncListInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SyncListResource): SyncListInstance { + + return new SyncListInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/v1/service/syncList/syncListItem.ts b/rest/sync/v1/service/syncList/syncListItem.ts new file mode 100644 index 000000000..0292dd0f4 --- /dev/null +++ b/rest/sync/v1/service/syncList/syncListItem.ts @@ -0,0 +1,1095 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type SyncListItemQueryFromBoundType = 'inclusive'|'exclusive'; + +export type SyncListItemQueryResultOrder = 'asc'|'desc'; + + +/** + * Options to pass to remove a SyncListItemInstance + */ +export interface SyncListItemContextRemoveOptions { + /** If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). */ + "ifMatch"?: string; +} + + +/** + * Options to pass to update a SyncListItemInstance + */ +export interface SyncListItemContextUpdateOptions { + /** If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). */ + "ifMatch"?: string; + /** A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. */ + "data"?: any; + /** An alias for `item_ttl`. If both parameters are provided, this value is ignored. */ + "ttl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. */ + "itemTtl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item\\\'s parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item\\\'s `data` or `ttl` is updated in the same request. */ + "collectionTtl"?: number; +} + +/** + * Options to pass to create a SyncListItemInstance + */ +export interface SyncListItemListInstanceCreateOptions { + /** A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. */ + "data": any; + /** An alias for `item_ttl`. If both parameters are provided, this value is ignored. */ + "ttl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. */ + "itemTtl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item\\\'s parent Sync List expires (time-to-live) and is deleted. */ + "collectionTtl"?: number; +} + +/** + * Options to pass to each + */ +export interface SyncListItemListInstanceEachOptions { + /** How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. */ + "order"?: SyncListItemQueryResultOrder; + /** The `index` of the first Sync List Item resource to read. See also `bounds`. */ + "from"?: string; + /** Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. */ + "bounds"?: SyncListItemQueryFromBoundType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SyncListItemInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SyncListItemListInstanceOptions { + /** How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. */ + "order"?: SyncListItemQueryResultOrder; + /** The `index` of the first Sync List Item resource to read. See also `bounds`. */ + "from"?: string; + /** Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. */ + "bounds"?: SyncListItemQueryFromBoundType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SyncListItemListInstancePageOptions { + /** How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. */ + "order"?: SyncListItemQueryResultOrder; + /** The `index` of the first Sync List Item resource to read. See also `bounds`. */ + "from"?: string; + /** Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. */ + "bounds"?: SyncListItemQueryFromBoundType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SyncListItemContext { + + /** + * Remove a SyncListItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + /** + * Remove a SyncListItemInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance + */ + remove(params: SyncListItemContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + + /** + * Remove a SyncListItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + /** + * Remove a SyncListItemInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance with HTTP metadata + */ + removeWithHttpInfo(params: SyncListItemContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + + /** + * Fetch a SyncListItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance + */ + fetch(callback?: (error: Error | null, item?: SyncListItemInstance) => any): Promise<SyncListItemInstance> + + /** + * Fetch a SyncListItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>> + + /** + * Update a SyncListItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance + */ + update(callback?: (error: Error | null, item?: SyncListItemInstance) => any): Promise<SyncListItemInstance>; + /** + * Update a SyncListItemInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance + */ + update(params: SyncListItemContextUpdateOptions, callback?: (error: Error | null, item?: SyncListItemInstance) => any): Promise<SyncListItemInstance>; + + /** + * Update a SyncListItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>>; + /** + * Update a SyncListItemInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncListItemContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SyncListItemContextSolution { + "serviceSid": string; + "listSid": string; + "index": number; +} + +export class SyncListItemContextImpl implements SyncListItemContext { + protected _solution: SyncListItemContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, listSid: string, index: number) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(listSid)) { + throw new Error('Parameter \'listSid\' is not valid.'); + } + + if (!isValidPathParam(index)) { + throw new Error('Parameter \'index\' is not valid.'); + } + + this._solution = { serviceSid, listSid, index, }; + this._uri = `/Services/${serviceSid}/Lists/${listSid}/Items/${index}`; + } + + remove(params?: SyncListItemContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: SyncListItemContextRemoveOptions | ((error: Error | null, item?: ApiResponse<boolean>) => any),callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SyncListItemInstance) => any): Promise<SyncListItemInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SyncListItemInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.listSid, instance._solution.index)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SyncListItemResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SyncListItemInstance> => ({ + ...response, + body: new SyncListItemInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.listSid, instance._solution.index) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SyncListItemContextUpdateOptions | ((error: Error | null, item?: SyncListItemInstance) => any),callback?: (error: Error | null, item?: SyncListItemInstance) => any): Promise<SyncListItemInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["data"] !== undefined) + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["itemTtl"] !== undefined) + data["ItemTtl"] = params["itemTtl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncListItemInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.listSid, instance._solution.index)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SyncListItemContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["data"] !== undefined) + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["itemTtl"] !== undefined) + data["ItemTtl"] = params["itemTtl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SyncListItemResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncListItemInstance> => ({ + ...response, + body: new SyncListItemInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.listSid, instance._solution.index) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SyncListItemPayload extends TwilioResponsePayload { + items: SyncListItemResource[]; +} + +interface SyncListItemResource { + index: number; + account_sid: string; + service_sid: string; + list_sid: string; + url: string; + revision: string; + data: any; + date_expires: Date; + date_created: Date; + date_updated: Date; + created_by: string; +} + +export class SyncListItemInstance { + protected _solution: SyncListItemContextSolution; + protected _context?: SyncListItemContext; + + constructor(protected _version: V1, payload: SyncListItemResource, serviceSid: string, listSid: string, index?: number) { + + this.index = deserialize.integer(payload.index); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.listSid = (payload.list_sid); + this.url = (payload.url); + this.revision = (payload.revision); + this.data = (payload.data); + this.dateExpires = deserialize.iso8601DateTime(payload.date_expires); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + + this._solution = { serviceSid, listSid, index: index, }; + } + + /** + * The automatically generated index of the List Item. The `index` values of the List Items in a Sync List can have gaps in their sequence. + */ + index: number; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the List Item resource. + */ + accountSid: string; + /** + * The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the Sync List that contains the List Item. + */ + listSid: string; + /** + * The absolute URL of the List Item resource. + */ + url: string; + /** + * The current revision of the item, represented as a string. + */ + revision: string; + /** + * An arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + */ + data: any; + /** + * The date and time in GMT when the List Item expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the List Item does not expire, this value is `null`. The List Item resource might not be deleted immediately after it expires. + */ + dateExpires: Date; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The identity of the List Item\'s creator. If the item is created from the client SDK, the value matches the Access Token\'s `identity` field. If the item was created from the REST API, the value is `system`. + */ + createdBy: string; + + private get _proxy(): SyncListItemContext { + this._context = this._context || new SyncListItemContextImpl(this._version, this._solution.serviceSid, this._solution.listSid, this._solution.index); + return this._context; + } + + /** + * Remove a SyncListItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + /** + * Remove a SyncListItemInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance + */ + remove(params: SyncListItemContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a SyncListItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + /** + * Remove a SyncListItemInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance with HTTP metadata + */ + removeWithHttpInfo(params: SyncListItemContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a SyncListItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance + */ + fetch(callback?: (error: Error | null, item?: SyncListItemInstance) => any): Promise<SyncListItemInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SyncListItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SyncListItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance + */ + update(callback?: (error: Error | null, item?: SyncListItemInstance) => any): Promise<SyncListItemInstance>; + /** + * Update a SyncListItemInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance + */ + update(params: SyncListItemContextUpdateOptions, callback?: (error: Error | null, item?: SyncListItemInstance) => any): Promise<SyncListItemInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SyncListItemInstance) => any): Promise<SyncListItemInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SyncListItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>>; + /** + * Update a SyncListItemInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncListItemContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + index: this.index, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + listSid: this.listSid, + url: this.url, + revision: this.revision, + data: this.data, + dateExpires: this.dateExpires, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SyncListItemSolution { + serviceSid: string; + listSid: string; +} + +export interface SyncListItemListInstance { + _version: V1; + _solution: SyncListItemSolution; + _uri: string; + + (index: number, ): SyncListItemContext; + get(index: number, ): SyncListItemContext; + + + + + + + + + /** + * Create a SyncListItemInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance + */ + create(params: SyncListItemListInstanceCreateOptions, callback?: (error: Error | null, item?: SyncListItemInstance) => any): Promise<SyncListItemInstance>; + + /** + * Create a SyncListItemInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListItemInstance with HTTP metadata + */ + createWithHttpInfo(params: SyncListItemListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>>; + + + + + /** + * Streams SyncListItemInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListItemListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SyncListItemInstance, done: (err?: Error) => void) => void): void; + each(params: SyncListItemListInstanceEachOptions, callback?: (item: SyncListItemInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SyncListItemInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListItemListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SyncListItemInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SyncListItemListInstanceEachOptions, callback?: (item: SyncListItemInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SyncListItemInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SyncListItemPage) => any): Promise<SyncListItemPage>; + /** + * Retrieve a single target page of SyncListItemInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SyncListItemPage>) => any): Promise<ApiResponse<SyncListItemPage>>; + /** + * Lists SyncListItemInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListItemListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SyncListItemInstance[]) => any): Promise<SyncListItemInstance[]>; + list(params: SyncListItemListInstanceOptions, callback?: (error: Error | null, items: SyncListItemInstance[]) => any): Promise<SyncListItemInstance[]>; + /** + * Lists SyncListItemInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListItemListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncListItemInstance[]>) => any): Promise<ApiResponse<SyncListItemInstance[]>>; + listWithHttpInfo(params: SyncListItemListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SyncListItemInstance[]>) => any): Promise<ApiResponse<SyncListItemInstance[]>>; + /** + * Retrieve a single page of SyncListItemInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListItemListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SyncListItemPage) => any): Promise<SyncListItemPage>; + page(params: SyncListItemListInstancePageOptions, callback?: (error: Error | null, items: SyncListItemPage) => any): Promise<SyncListItemPage>; + /** + * Retrieve a single page of SyncListItemInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListItemListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncListItemPage>) => any): Promise<ApiResponse<SyncListItemPage>>; + pageWithHttpInfo(params: SyncListItemListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SyncListItemPage>) => any): Promise<ApiResponse<SyncListItemPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SyncListItemListInstance(version: V1, serviceSid: string, listSid: string): SyncListItemListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(listSid)) { + throw new Error('Parameter \'listSid\' is not valid.'); + } + + const instance = ((index, ) => instance.get(index, )) as SyncListItemListInstance; + + instance.get = function get(index, ): SyncListItemContext { + return new SyncListItemContextImpl(version, serviceSid, listSid, index); + } + + instance._version = version; + instance._solution = { serviceSid, listSid, }; + instance._uri = `/Services/${serviceSid}/Lists/${listSid}/Items`; + + instance.create = function create(params: SyncListItemListInstanceCreateOptions, callback?: (error: Error | null, items: SyncListItemInstance) => any): Promise<SyncListItemInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["data"] === null || params["data"] === undefined) { + throw new Error('Required parameter "params[\'data\']" missing.'); + } + + let data: any = {}; + + + + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["itemTtl"] !== undefined) + data["ItemTtl"] = params["itemTtl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncListItemInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.listSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SyncListItemListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<SyncListItemInstance>) => any): Promise<ApiResponse<SyncListItemInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["data"] === null || params["data"] === undefined) { + throw new Error('Required parameter "params[\'data\']" missing.'); + } + + let data: any = {}; + + + + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["itemTtl"] !== undefined) + data["ItemTtl"] = params["itemTtl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SyncListItemResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncListItemInstance> => ({ + ...response, + body: new SyncListItemInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.listSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SyncListItemListInstancePageOptions | ((error: Error | null, items: SyncListItemPage) => any), callback?: (error: Error | null, items: SyncListItemPage) => any): Promise<SyncListItemPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["bounds"] !== undefined) + data["Bounds"] = params["bounds"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SyncListItemPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SyncListItemPage) => any): Promise<SyncListItemPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SyncListItemPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SyncListItemListInstancePageOptions | ((error: Error | null, items: ApiResponse<SyncListItemPage>) => any), callback?: (error: Error | null, items: ApiResponse<SyncListItemPage>) => any): Promise<ApiResponse<SyncListItemPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["bounds"] !== undefined) + data["Bounds"] = params["bounds"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SyncListItemPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncListItemPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SyncListItemPage>) => any): Promise<ApiResponse<SyncListItemPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SyncListItemPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncListItemPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SyncListItemPage extends Page<V1, SyncListItemPayload, SyncListItemResource, SyncListItemInstance> { +/** +* Initialize the SyncListItemPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SyncListItemSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SyncListItemInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SyncListItemResource): SyncListItemInstance { + + return new SyncListItemInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.listSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/v1/service/syncList/syncListPermission.ts b/rest/sync/v1/service/syncList/syncListPermission.ts new file mode 100644 index 000000000..bcc766370 --- /dev/null +++ b/rest/sync/v1/service/syncList/syncListPermission.ts @@ -0,0 +1,824 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a SyncListPermissionInstance + */ +export interface SyncListPermissionContextUpdateOptions { + /** Whether the identity can read the Sync List and its Items. Default value is `false`. */ + "read": boolean; + /** Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. */ + "write": boolean; + /** Whether the identity can delete the Sync List. Default value is `false`. */ + "manage": boolean; +} + +/** + * Options to pass to each + */ +export interface SyncListPermissionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SyncListPermissionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SyncListPermissionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SyncListPermissionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SyncListPermissionContext { + + /** + * Remove a SyncListPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SyncListPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SyncListPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListPermissionInstance + */ + fetch(callback?: (error: Error | null, item?: SyncListPermissionInstance) => any): Promise<SyncListPermissionInstance> + + /** + * Fetch a SyncListPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListPermissionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListPermissionInstance>) => any): Promise<ApiResponse<SyncListPermissionInstance>> + + /** + * Update a SyncListPermissionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListPermissionInstance + */ + update(params: SyncListPermissionContextUpdateOptions, callback?: (error: Error | null, item?: SyncListPermissionInstance) => any): Promise<SyncListPermissionInstance>; + + /** + * Update a SyncListPermissionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListPermissionInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncListPermissionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncListPermissionInstance>) => any): Promise<ApiResponse<SyncListPermissionInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SyncListPermissionContextSolution { + "serviceSid": string; + "listSid": string; + "identity": string; +} + +export class SyncListPermissionContextImpl implements SyncListPermissionContext { + protected _solution: SyncListPermissionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, listSid: string, identity: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(listSid)) { + throw new Error('Parameter \'listSid\' is not valid.'); + } + + if (!isValidPathParam(identity)) { + throw new Error('Parameter \'identity\' is not valid.'); + } + + this._solution = { serviceSid, listSid, identity, }; + this._uri = `/Services/${serviceSid}/Lists/${listSid}/Permissions/${identity}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SyncListPermissionInstance) => any): Promise<SyncListPermissionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SyncListPermissionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.listSid, instance._solution.identity)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListPermissionInstance>) => any): Promise<ApiResponse<SyncListPermissionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SyncListPermissionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SyncListPermissionInstance> => ({ + ...response, + body: new SyncListPermissionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.listSid, instance._solution.identity) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: SyncListPermissionContextUpdateOptions,callback?: (error: Error | null, item?: SyncListPermissionInstance) => any): Promise<SyncListPermissionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["read"] === null || params["read"] === undefined) { + throw new Error('Required parameter "params[\'read\']" missing.'); + } + + if (params["write"] === null || params["write"] === undefined) { + throw new Error('Required parameter "params[\'write\']" missing.'); + } + + if (params["manage"] === null || params["manage"] === undefined) { + throw new Error('Required parameter "params[\'manage\']" missing.'); + } + + let data: any = {}; + + + + data["Read"] = serialize.bool(params["read"]); + + data["Write"] = serialize.bool(params["write"]); + + data["Manage"] = serialize.bool(params["manage"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncListPermissionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.listSid, instance._solution.identity)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: SyncListPermissionContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<SyncListPermissionInstance>) => any): Promise<ApiResponse<SyncListPermissionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["read"] === null || params["read"] === undefined) { + throw new Error('Required parameter "params[\'read\']" missing.'); + } + + if (params["write"] === null || params["write"] === undefined) { + throw new Error('Required parameter "params[\'write\']" missing.'); + } + + if (params["manage"] === null || params["manage"] === undefined) { + throw new Error('Required parameter "params[\'manage\']" missing.'); + } + + let data: any = {}; + + + + data["Read"] = serialize.bool(params["read"]); + + data["Write"] = serialize.bool(params["write"]); + + data["Manage"] = serialize.bool(params["manage"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SyncListPermissionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncListPermissionInstance> => ({ + ...response, + body: new SyncListPermissionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.listSid, instance._solution.identity) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SyncListPermissionPayload extends TwilioResponsePayload { + permissions: SyncListPermissionResource[]; +} + +interface SyncListPermissionResource { + account_sid: string; + service_sid: string; + list_sid: string; + identity: string; + read: boolean; + write: boolean; + manage: boolean; + url: string; +} + +export class SyncListPermissionInstance { + protected _solution: SyncListPermissionContextSolution; + protected _context?: SyncListPermissionContext; + + constructor(protected _version: V1, payload: SyncListPermissionResource, serviceSid: string, listSid: string, identity?: string) { + + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.listSid = (payload.list_sid); + this.identity = (payload.identity); + this.read = (payload.read); + this.write = (payload.write); + this.manage = (payload.manage); + this.url = (payload.url); + + this._solution = { serviceSid, listSid, identity: identity, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync List Permission resource. + */ + accountSid: string; + /** + * The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the Sync List to which the Permission applies. + */ + listSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s User within the Service to an FPA token. + */ + identity: string; + /** + * Whether the identity can read the Sync List and its Items. + */ + read: boolean; + /** + * Whether the identity can create, update, and delete Items in the Sync List. + */ + write: boolean; + /** + * Whether the identity can delete the Sync List. + */ + manage: boolean; + /** + * The absolute URL of the Sync List Permission resource. + */ + url: string; + + private get _proxy(): SyncListPermissionContext { + this._context = this._context || new SyncListPermissionContextImpl(this._version, this._solution.serviceSid, this._solution.listSid, this._solution.identity); + return this._context; + } + + /** + * Remove a SyncListPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SyncListPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SyncListPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListPermissionInstance + */ + fetch(callback?: (error: Error | null, item?: SyncListPermissionInstance) => any): Promise<SyncListPermissionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SyncListPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListPermissionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncListPermissionInstance>) => any): Promise<ApiResponse<SyncListPermissionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SyncListPermissionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListPermissionInstance + */ + update(params: SyncListPermissionContextUpdateOptions, callback?: (error: Error | null, item?: SyncListPermissionInstance) => any): Promise<SyncListPermissionInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SyncListPermissionInstance) => any): Promise<SyncListPermissionInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SyncListPermissionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncListPermissionInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncListPermissionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncListPermissionInstance>) => any): Promise<ApiResponse<SyncListPermissionInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SyncListPermissionInstance>) => any): Promise<ApiResponse<SyncListPermissionInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + serviceSid: this.serviceSid, + listSid: this.listSid, + identity: this.identity, + read: this.read, + write: this.write, + manage: this.manage, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SyncListPermissionSolution { + serviceSid: string; + listSid: string; +} + +export interface SyncListPermissionListInstance { + _version: V1; + _solution: SyncListPermissionSolution; + _uri: string; + + (identity: string, ): SyncListPermissionContext; + get(identity: string, ): SyncListPermissionContext; + + + + + + + + + + /** + * Streams SyncListPermissionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListPermissionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SyncListPermissionInstance, done: (err?: Error) => void) => void): void; + each(params: SyncListPermissionListInstanceEachOptions, callback?: (item: SyncListPermissionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SyncListPermissionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListPermissionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SyncListPermissionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SyncListPermissionListInstanceEachOptions, callback?: (item: SyncListPermissionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SyncListPermissionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SyncListPermissionPage) => any): Promise<SyncListPermissionPage>; + /** + * Retrieve a single target page of SyncListPermissionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SyncListPermissionPage>) => any): Promise<ApiResponse<SyncListPermissionPage>>; + /** + * Lists SyncListPermissionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListPermissionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SyncListPermissionInstance[]) => any): Promise<SyncListPermissionInstance[]>; + list(params: SyncListPermissionListInstanceOptions, callback?: (error: Error | null, items: SyncListPermissionInstance[]) => any): Promise<SyncListPermissionInstance[]>; + /** + * Lists SyncListPermissionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListPermissionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncListPermissionInstance[]>) => any): Promise<ApiResponse<SyncListPermissionInstance[]>>; + listWithHttpInfo(params: SyncListPermissionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SyncListPermissionInstance[]>) => any): Promise<ApiResponse<SyncListPermissionInstance[]>>; + /** + * Retrieve a single page of SyncListPermissionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListPermissionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SyncListPermissionPage) => any): Promise<SyncListPermissionPage>; + page(params: SyncListPermissionListInstancePageOptions, callback?: (error: Error | null, items: SyncListPermissionPage) => any): Promise<SyncListPermissionPage>; + /** + * Retrieve a single page of SyncListPermissionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncListPermissionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncListPermissionPage>) => any): Promise<ApiResponse<SyncListPermissionPage>>; + pageWithHttpInfo(params: SyncListPermissionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SyncListPermissionPage>) => any): Promise<ApiResponse<SyncListPermissionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SyncListPermissionListInstance(version: V1, serviceSid: string, listSid: string): SyncListPermissionListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(listSid)) { + throw new Error('Parameter \'listSid\' is not valid.'); + } + + const instance = ((identity, ) => instance.get(identity, )) as SyncListPermissionListInstance; + + instance.get = function get(identity, ): SyncListPermissionContext { + return new SyncListPermissionContextImpl(version, serviceSid, listSid, identity); + } + + instance._version = version; + instance._solution = { serviceSid, listSid, }; + instance._uri = `/Services/${serviceSid}/Lists/${listSid}/Permissions`; + + instance.page = function page(params?: SyncListPermissionListInstancePageOptions | ((error: Error | null, items: SyncListPermissionPage) => any), callback?: (error: Error | null, items: SyncListPermissionPage) => any): Promise<SyncListPermissionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SyncListPermissionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SyncListPermissionPage) => any): Promise<SyncListPermissionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SyncListPermissionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SyncListPermissionListInstancePageOptions | ((error: Error | null, items: ApiResponse<SyncListPermissionPage>) => any), callback?: (error: Error | null, items: ApiResponse<SyncListPermissionPage>) => any): Promise<ApiResponse<SyncListPermissionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SyncListPermissionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncListPermissionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SyncListPermissionPage>) => any): Promise<ApiResponse<SyncListPermissionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SyncListPermissionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncListPermissionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SyncListPermissionPage extends Page<V1, SyncListPermissionPayload, SyncListPermissionResource, SyncListPermissionInstance> { +/** +* Initialize the SyncListPermissionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SyncListPermissionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SyncListPermissionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SyncListPermissionResource): SyncListPermissionInstance { + + return new SyncListPermissionInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.listSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/v1/service/syncMap.ts b/rest/sync/v1/service/syncMap.ts new file mode 100644 index 000000000..d0dd67cf0 --- /dev/null +++ b/rest/sync/v1/service/syncMap.ts @@ -0,0 +1,997 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { SyncMapItemListInstance } from "./syncMap/syncMapItem"; +import { SyncMapPermissionListInstance } from "./syncMap/syncMapPermission"; + + + + + +/** + * Options to pass to update a SyncMapInstance + */ +export interface SyncMapContextUpdateOptions { + /** An alias for `collection_ttl`. If both parameters are provided, this value is ignored. */ + "ttl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. */ + "collectionTtl"?: number; +} + +/** + * Options to pass to create a SyncMapInstance + */ +export interface SyncMapListInstanceCreateOptions { + /** An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. */ + "uniqueName"?: string; + /** An alias for `collection_ttl`. If both parameters are provided, this value is ignored. */ + "ttl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. */ + "collectionTtl"?: number; +} + +/** + * Options to pass to each + */ +export interface SyncMapListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SyncMapInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SyncMapListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SyncMapListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SyncMapContext { + syncMapItems: SyncMapItemListInstance; + syncMapPermissions: SyncMapPermissionListInstance; + + /** + * Remove a SyncMapInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SyncMapInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SyncMapInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance + */ + fetch(callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance> + + /** + * Fetch a SyncMapInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>> + + /** + * Update a SyncMapInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance + */ + update(callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance>; + /** + * Update a SyncMapInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance + */ + update(params: SyncMapContextUpdateOptions, callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance>; + + /** + * Update a SyncMapInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>>; + /** + * Update a SyncMapInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncMapContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SyncMapContextSolution { + "serviceSid": string; + "sid": string; +} + +export class SyncMapContextImpl implements SyncMapContext { + protected _solution: SyncMapContextSolution; + protected _uri: string; + + protected _syncMapItems?: SyncMapItemListInstance; + protected _syncMapPermissions?: SyncMapPermissionListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Maps/${sid}`; + } + + get syncMapItems(): SyncMapItemListInstance { + this._syncMapItems = this._syncMapItems || SyncMapItemListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._syncMapItems; + } + + get syncMapPermissions(): SyncMapPermissionListInstance { + this._syncMapPermissions = this._syncMapPermissions || SyncMapPermissionListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._syncMapPermissions; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SyncMapInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SyncMapResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SyncMapInstance> => ({ + ...response, + body: new SyncMapInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SyncMapContextUpdateOptions | ((error: Error | null, item?: SyncMapInstance) => any),callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncMapInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SyncMapContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SyncMapInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SyncMapResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncMapInstance> => ({ + ...response, + body: new SyncMapInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SyncMapPayload extends TwilioResponsePayload { + maps: SyncMapResource[]; +} + +interface SyncMapResource { + sid: string; + unique_name: string; + account_sid: string; + service_sid: string; + url: string; + links: Record<string, string>; + revision: string; + date_expires: Date; + date_created: Date; + date_updated: Date; + created_by: string; +} + +export class SyncMapInstance { + protected _solution: SyncMapContextSolution; + protected _context?: SyncMapContext; + + constructor(protected _version: V1, payload: SyncMapResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.url = (payload.url); + this.links = (payload.links); + this.revision = (payload.revision); + this.dateExpires = deserialize.iso8601DateTime(payload.date_expires); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Sync Map resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. + */ + uniqueName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Map resource. + */ + accountSid: string; + /** + * The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The absolute URL of the Sync Map resource. + */ + url: string; + /** + * The URLs of the Sync Map\'s nested resources. + */ + links: Record<string, string>; + /** + * The current revision of the Sync Map, represented as a string. + */ + revision: string; + /** + * The date and time in GMT when the Sync Map expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Sync Map does not expire, this value is `null`. The Sync Map might not be deleted immediately after it expires. + */ + dateExpires: Date; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The identity of the Sync Map\'s creator. If the Sync Map is created from the client SDK, the value matches the Access Token\'s `identity` field. If the Sync Map was created from the REST API, the value is `system`. + */ + createdBy: string; + + private get _proxy(): SyncMapContext { + this._context = this._context || new SyncMapContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a SyncMapInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SyncMapInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SyncMapInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance + */ + fetch(callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SyncMapInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SyncMapInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance + */ + update(callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance>; + /** + * Update a SyncMapInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance + */ + update(params: SyncMapContextUpdateOptions, callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SyncMapInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>>; + /** + * Update a SyncMapInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncMapContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the syncMapItems. + */ + syncMapItems(): SyncMapItemListInstance { + return this._proxy.syncMapItems; + } + + /** + * Access the syncMapPermissions. + */ + syncMapPermissions(): SyncMapPermissionListInstance { + return this._proxy.syncMapPermissions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + url: this.url, + links: this.links, + revision: this.revision, + dateExpires: this.dateExpires, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SyncMapSolution { + serviceSid: string; +} + +export interface SyncMapListInstance { + _version: V1; + _solution: SyncMapSolution; + _uri: string; + + (sid: string, ): SyncMapContext; + get(sid: string, ): SyncMapContext; + + + + + + + + + /** + * Create a SyncMapInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance + */ + create(callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance>; + /** + * Create a SyncMapInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance + */ + create(params: SyncMapListInstanceCreateOptions, callback?: (error: Error | null, item?: SyncMapInstance) => any): Promise<SyncMapInstance>; + + /** + * Create a SyncMapInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>>; + /** + * Create a SyncMapInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapInstance with HTTP metadata + */ + createWithHttpInfo(params: SyncMapListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>>; + + + + + /** + * Streams SyncMapInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SyncMapInstance, done: (err?: Error) => void) => void): void; + each(params: SyncMapListInstanceEachOptions, callback?: (item: SyncMapInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SyncMapInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SyncMapInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SyncMapListInstanceEachOptions, callback?: (item: SyncMapInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SyncMapInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SyncMapPage) => any): Promise<SyncMapPage>; + /** + * Retrieve a single target page of SyncMapInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SyncMapPage>) => any): Promise<ApiResponse<SyncMapPage>>; + /** + * Lists SyncMapInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SyncMapInstance[]) => any): Promise<SyncMapInstance[]>; + list(params: SyncMapListInstanceOptions, callback?: (error: Error | null, items: SyncMapInstance[]) => any): Promise<SyncMapInstance[]>; + /** + * Lists SyncMapInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncMapInstance[]>) => any): Promise<ApiResponse<SyncMapInstance[]>>; + listWithHttpInfo(params: SyncMapListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SyncMapInstance[]>) => any): Promise<ApiResponse<SyncMapInstance[]>>; + /** + * Retrieve a single page of SyncMapInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SyncMapPage) => any): Promise<SyncMapPage>; + page(params: SyncMapListInstancePageOptions, callback?: (error: Error | null, items: SyncMapPage) => any): Promise<SyncMapPage>; + /** + * Retrieve a single page of SyncMapInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncMapPage>) => any): Promise<ApiResponse<SyncMapPage>>; + pageWithHttpInfo(params: SyncMapListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SyncMapPage>) => any): Promise<ApiResponse<SyncMapPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SyncMapListInstance(version: V1, serviceSid: string): SyncMapListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as SyncMapListInstance; + + instance.get = function get(sid, ): SyncMapContext { + return new SyncMapContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Maps`; + + instance.create = function create(params?: SyncMapListInstanceCreateOptions | ((error: Error | null, items: SyncMapInstance) => any), callback?: (error: Error | null, items: SyncMapInstance) => any): Promise<SyncMapInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncMapInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: SyncMapListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<SyncMapInstance>) => any), callback?: (error: Error | null, items: ApiResponse<SyncMapInstance>) => any): Promise<ApiResponse<SyncMapInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SyncMapResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncMapInstance> => ({ + ...response, + body: new SyncMapInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SyncMapListInstancePageOptions | ((error: Error | null, items: SyncMapPage) => any), callback?: (error: Error | null, items: SyncMapPage) => any): Promise<SyncMapPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SyncMapPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SyncMapPage) => any): Promise<SyncMapPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SyncMapPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SyncMapListInstancePageOptions | ((error: Error | null, items: ApiResponse<SyncMapPage>) => any), callback?: (error: Error | null, items: ApiResponse<SyncMapPage>) => any): Promise<ApiResponse<SyncMapPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SyncMapPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncMapPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SyncMapPage>) => any): Promise<ApiResponse<SyncMapPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SyncMapPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncMapPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SyncMapPage extends Page<V1, SyncMapPayload, SyncMapResource, SyncMapInstance> { +/** +* Initialize the SyncMapPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SyncMapSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SyncMapInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SyncMapResource): SyncMapInstance { + + return new SyncMapInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/v1/service/syncMap/syncMapItem.ts b/rest/sync/v1/service/syncMap/syncMapItem.ts new file mode 100644 index 000000000..ac492c72a --- /dev/null +++ b/rest/sync/v1/service/syncMap/syncMapItem.ts @@ -0,0 +1,1109 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type SyncMapItemQueryFromBoundType = 'inclusive'|'exclusive'; + +export type SyncMapItemQueryResultOrder = 'asc'|'desc'; + + +/** + * Options to pass to remove a SyncMapItemInstance + */ +export interface SyncMapItemContextRemoveOptions { + /** If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). */ + "ifMatch"?: string; +} + + +/** + * Options to pass to update a SyncMapItemInstance + */ +export interface SyncMapItemContextUpdateOptions { + /** If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). */ + "ifMatch"?: string; + /** A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. */ + "data"?: any; + /** An alias for `item_ttl`. If both parameters are provided, this value is ignored. */ + "ttl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. */ + "itemTtl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item\\\'s parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item\\\'s `data` or `ttl` is updated in the same request. */ + "collectionTtl"?: number; +} + +/** + * Options to pass to create a SyncMapItemInstance + */ +export interface SyncMapItemListInstanceCreateOptions { + /** The unique, user-defined key for the Map Item. Can be up to 320 characters long. */ + "key": string; + /** A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. */ + "data": any; + /** An alias for `item_ttl`. If both parameters are provided, this value is ignored. */ + "ttl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. */ + "itemTtl"?: number; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item\\\'s parent Sync Map expires (time-to-live) and is deleted. */ + "collectionTtl"?: number; +} + +/** + * Options to pass to each + */ +export interface SyncMapItemListInstanceEachOptions { + /** How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. */ + "order"?: SyncMapItemQueryResultOrder; + /** The `key` of the first Sync Map Item resource to read. See also `bounds`. */ + "from"?: string; + /** Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. */ + "bounds"?: SyncMapItemQueryFromBoundType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SyncMapItemInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SyncMapItemListInstanceOptions { + /** How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. */ + "order"?: SyncMapItemQueryResultOrder; + /** The `key` of the first Sync Map Item resource to read. See also `bounds`. */ + "from"?: string; + /** Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. */ + "bounds"?: SyncMapItemQueryFromBoundType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SyncMapItemListInstancePageOptions { + /** How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. */ + "order"?: SyncMapItemQueryResultOrder; + /** The `key` of the first Sync Map Item resource to read. See also `bounds`. */ + "from"?: string; + /** Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. */ + "bounds"?: SyncMapItemQueryFromBoundType; + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SyncMapItemContext { + + /** + * Remove a SyncMapItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + /** + * Remove a SyncMapItemInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance + */ + remove(params: SyncMapItemContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + + /** + * Remove a SyncMapItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + /** + * Remove a SyncMapItemInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance with HTTP metadata + */ + removeWithHttpInfo(params: SyncMapItemContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + + /** + * Fetch a SyncMapItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance + */ + fetch(callback?: (error: Error | null, item?: SyncMapItemInstance) => any): Promise<SyncMapItemInstance> + + /** + * Fetch a SyncMapItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>> + + /** + * Update a SyncMapItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance + */ + update(callback?: (error: Error | null, item?: SyncMapItemInstance) => any): Promise<SyncMapItemInstance>; + /** + * Update a SyncMapItemInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance + */ + update(params: SyncMapItemContextUpdateOptions, callback?: (error: Error | null, item?: SyncMapItemInstance) => any): Promise<SyncMapItemInstance>; + + /** + * Update a SyncMapItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>>; + /** + * Update a SyncMapItemInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncMapItemContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SyncMapItemContextSolution { + "serviceSid": string; + "mapSid": string; + "key": string; +} + +export class SyncMapItemContextImpl implements SyncMapItemContext { + protected _solution: SyncMapItemContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, mapSid: string, key: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(mapSid)) { + throw new Error('Parameter \'mapSid\' is not valid.'); + } + + if (!isValidPathParam(key)) { + throw new Error('Parameter \'key\' is not valid.'); + } + + this._solution = { serviceSid, mapSid, key, }; + this._uri = `/Services/${serviceSid}/Maps/${mapSid}/Items/${key}`; + } + + remove(params?: SyncMapItemContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: SyncMapItemContextRemoveOptions | ((error: Error | null, item?: ApiResponse<boolean>) => any),callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SyncMapItemInstance) => any): Promise<SyncMapItemInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SyncMapItemInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.mapSid, instance._solution.key)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SyncMapItemResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SyncMapItemInstance> => ({ + ...response, + body: new SyncMapItemInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.mapSid, instance._solution.key) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SyncMapItemContextUpdateOptions | ((error: Error | null, item?: SyncMapItemInstance) => any),callback?: (error: Error | null, item?: SyncMapItemInstance) => any): Promise<SyncMapItemInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["data"] !== undefined) + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["itemTtl"] !== undefined) + data["ItemTtl"] = params["itemTtl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncMapItemInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.mapSid, instance._solution.key)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SyncMapItemContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["data"] !== undefined) + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["itemTtl"] !== undefined) + data["ItemTtl"] = params["itemTtl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SyncMapItemResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncMapItemInstance> => ({ + ...response, + body: new SyncMapItemInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.mapSid, instance._solution.key) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SyncMapItemPayload extends TwilioResponsePayload { + items: SyncMapItemResource[]; +} + +interface SyncMapItemResource { + key: string; + account_sid: string; + service_sid: string; + map_sid: string; + url: string; + revision: string; + data: any; + date_expires: Date; + date_created: Date; + date_updated: Date; + created_by: string; +} + +export class SyncMapItemInstance { + protected _solution: SyncMapItemContextSolution; + protected _context?: SyncMapItemContext; + + constructor(protected _version: V1, payload: SyncMapItemResource, serviceSid: string, mapSid: string, key?: string) { + + this.key = (payload.key); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.mapSid = (payload.map_sid); + this.url = (payload.url); + this.revision = (payload.revision); + this.data = (payload.data); + this.dateExpires = deserialize.iso8601DateTime(payload.date_expires); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + + this._solution = { serviceSid, mapSid, key: key, }; + } + + /** + * The unique, user-defined key for the Map Item. + */ + key: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Map Item resource. + */ + accountSid: string; + /** + * The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the Sync Map that contains the Map Item. + */ + mapSid: string; + /** + * The absolute URL of the Map Item resource. + */ + url: string; + /** + * The current revision of the Map Item, represented as a string. + */ + revision: string; + /** + * An arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + */ + data: any; + /** + * The date and time in GMT when the Map Item expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Map Item does not expire, this value is `null`. The Map Item might not be deleted immediately after it expires. + */ + dateExpires: Date; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The identity of the Map Item\'s creator. If the Map Item is created from the client SDK, the value matches the Access Token\'s `identity` field. If the Map Item was created from the REST API, the value is `system`. + */ + createdBy: string; + + private get _proxy(): SyncMapItemContext { + this._context = this._context || new SyncMapItemContextImpl(this._version, this._solution.serviceSid, this._solution.mapSid, this._solution.key); + return this._context; + } + + /** + * Remove a SyncMapItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + /** + * Remove a SyncMapItemInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance + */ + remove(params: SyncMapItemContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a SyncMapItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + /** + * Remove a SyncMapItemInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance with HTTP metadata + */ + removeWithHttpInfo(params: SyncMapItemContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a SyncMapItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance + */ + fetch(callback?: (error: Error | null, item?: SyncMapItemInstance) => any): Promise<SyncMapItemInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SyncMapItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SyncMapItemInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance + */ + update(callback?: (error: Error | null, item?: SyncMapItemInstance) => any): Promise<SyncMapItemInstance>; + /** + * Update a SyncMapItemInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance + */ + update(params: SyncMapItemContextUpdateOptions, callback?: (error: Error | null, item?: SyncMapItemInstance) => any): Promise<SyncMapItemInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SyncMapItemInstance) => any): Promise<SyncMapItemInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SyncMapItemInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>>; + /** + * Update a SyncMapItemInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncMapItemContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + key: this.key, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + mapSid: this.mapSid, + url: this.url, + revision: this.revision, + data: this.data, + dateExpires: this.dateExpires, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SyncMapItemSolution { + serviceSid: string; + mapSid: string; +} + +export interface SyncMapItemListInstance { + _version: V1; + _solution: SyncMapItemSolution; + _uri: string; + + (key: string, ): SyncMapItemContext; + get(key: string, ): SyncMapItemContext; + + + + + + + + + /** + * Create a SyncMapItemInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance + */ + create(params: SyncMapItemListInstanceCreateOptions, callback?: (error: Error | null, item?: SyncMapItemInstance) => any): Promise<SyncMapItemInstance>; + + /** + * Create a SyncMapItemInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapItemInstance with HTTP metadata + */ + createWithHttpInfo(params: SyncMapItemListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>>; + + + + + /** + * Streams SyncMapItemInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapItemListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SyncMapItemInstance, done: (err?: Error) => void) => void): void; + each(params: SyncMapItemListInstanceEachOptions, callback?: (item: SyncMapItemInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SyncMapItemInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapItemListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SyncMapItemInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SyncMapItemListInstanceEachOptions, callback?: (item: SyncMapItemInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SyncMapItemInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SyncMapItemPage) => any): Promise<SyncMapItemPage>; + /** + * Retrieve a single target page of SyncMapItemInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SyncMapItemPage>) => any): Promise<ApiResponse<SyncMapItemPage>>; + /** + * Lists SyncMapItemInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapItemListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SyncMapItemInstance[]) => any): Promise<SyncMapItemInstance[]>; + list(params: SyncMapItemListInstanceOptions, callback?: (error: Error | null, items: SyncMapItemInstance[]) => any): Promise<SyncMapItemInstance[]>; + /** + * Lists SyncMapItemInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapItemListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncMapItemInstance[]>) => any): Promise<ApiResponse<SyncMapItemInstance[]>>; + listWithHttpInfo(params: SyncMapItemListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SyncMapItemInstance[]>) => any): Promise<ApiResponse<SyncMapItemInstance[]>>; + /** + * Retrieve a single page of SyncMapItemInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapItemListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SyncMapItemPage) => any): Promise<SyncMapItemPage>; + page(params: SyncMapItemListInstancePageOptions, callback?: (error: Error | null, items: SyncMapItemPage) => any): Promise<SyncMapItemPage>; + /** + * Retrieve a single page of SyncMapItemInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapItemListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncMapItemPage>) => any): Promise<ApiResponse<SyncMapItemPage>>; + pageWithHttpInfo(params: SyncMapItemListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SyncMapItemPage>) => any): Promise<ApiResponse<SyncMapItemPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SyncMapItemListInstance(version: V1, serviceSid: string, mapSid: string): SyncMapItemListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(mapSid)) { + throw new Error('Parameter \'mapSid\' is not valid.'); + } + + const instance = ((key, ) => instance.get(key, )) as SyncMapItemListInstance; + + instance.get = function get(key, ): SyncMapItemContext { + return new SyncMapItemContextImpl(version, serviceSid, mapSid, key); + } + + instance._version = version; + instance._solution = { serviceSid, mapSid, }; + instance._uri = `/Services/${serviceSid}/Maps/${mapSid}/Items`; + + instance.create = function create(params: SyncMapItemListInstanceCreateOptions, callback?: (error: Error | null, items: SyncMapItemInstance) => any): Promise<SyncMapItemInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["key"] === null || params["key"] === undefined) { + throw new Error('Required parameter "params[\'key\']" missing.'); + } + + if (params["data"] === null || params["data"] === undefined) { + throw new Error('Required parameter "params[\'data\']" missing.'); + } + + let data: any = {}; + + + + data["Key"] = params["key"]; + + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["itemTtl"] !== undefined) + data["ItemTtl"] = params["itemTtl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncMapItemInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.mapSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SyncMapItemListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<SyncMapItemInstance>) => any): Promise<ApiResponse<SyncMapItemInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["key"] === null || params["key"] === undefined) { + throw new Error('Required parameter "params[\'key\']" missing.'); + } + + if (params["data"] === null || params["data"] === undefined) { + throw new Error('Required parameter "params[\'data\']" missing.'); + } + + let data: any = {}; + + + + data["Key"] = params["key"]; + + data["Data"] = serialize.object(params["data"]); + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + if (params["itemTtl"] !== undefined) + data["ItemTtl"] = params["itemTtl"]; + if (params["collectionTtl"] !== undefined) + data["CollectionTtl"] = params["collectionTtl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SyncMapItemResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncMapItemInstance> => ({ + ...response, + body: new SyncMapItemInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.mapSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SyncMapItemListInstancePageOptions | ((error: Error | null, items: SyncMapItemPage) => any), callback?: (error: Error | null, items: SyncMapItemPage) => any): Promise<SyncMapItemPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["bounds"] !== undefined) + data["Bounds"] = params["bounds"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SyncMapItemPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SyncMapItemPage) => any): Promise<SyncMapItemPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SyncMapItemPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SyncMapItemListInstancePageOptions | ((error: Error | null, items: ApiResponse<SyncMapItemPage>) => any), callback?: (error: Error | null, items: ApiResponse<SyncMapItemPage>) => any): Promise<ApiResponse<SyncMapItemPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["bounds"] !== undefined) + data["Bounds"] = params["bounds"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SyncMapItemPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncMapItemPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SyncMapItemPage>) => any): Promise<ApiResponse<SyncMapItemPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SyncMapItemPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncMapItemPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SyncMapItemPage extends Page<V1, SyncMapItemPayload, SyncMapItemResource, SyncMapItemInstance> { +/** +* Initialize the SyncMapItemPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SyncMapItemSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SyncMapItemInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SyncMapItemResource): SyncMapItemInstance { + + return new SyncMapItemInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.mapSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/v1/service/syncMap/syncMapPermission.ts b/rest/sync/v1/service/syncMap/syncMapPermission.ts new file mode 100644 index 000000000..7ac473891 --- /dev/null +++ b/rest/sync/v1/service/syncMap/syncMapPermission.ts @@ -0,0 +1,824 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a SyncMapPermissionInstance + */ +export interface SyncMapPermissionContextUpdateOptions { + /** Whether the identity can read the Sync Map and its Items. Default value is `false`. */ + "read": boolean; + /** Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. */ + "write": boolean; + /** Whether the identity can delete the Sync Map. Default value is `false`. */ + "manage": boolean; +} + +/** + * Options to pass to each + */ +export interface SyncMapPermissionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SyncMapPermissionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SyncMapPermissionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SyncMapPermissionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SyncMapPermissionContext { + + /** + * Remove a SyncMapPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SyncMapPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SyncMapPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapPermissionInstance + */ + fetch(callback?: (error: Error | null, item?: SyncMapPermissionInstance) => any): Promise<SyncMapPermissionInstance> + + /** + * Fetch a SyncMapPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapPermissionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapPermissionInstance>) => any): Promise<ApiResponse<SyncMapPermissionInstance>> + + /** + * Update a SyncMapPermissionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapPermissionInstance + */ + update(params: SyncMapPermissionContextUpdateOptions, callback?: (error: Error | null, item?: SyncMapPermissionInstance) => any): Promise<SyncMapPermissionInstance>; + + /** + * Update a SyncMapPermissionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapPermissionInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncMapPermissionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncMapPermissionInstance>) => any): Promise<ApiResponse<SyncMapPermissionInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SyncMapPermissionContextSolution { + "serviceSid": string; + "mapSid": string; + "identity": string; +} + +export class SyncMapPermissionContextImpl implements SyncMapPermissionContext { + protected _solution: SyncMapPermissionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, serviceSid: string, mapSid: string, identity: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(mapSid)) { + throw new Error('Parameter \'mapSid\' is not valid.'); + } + + if (!isValidPathParam(identity)) { + throw new Error('Parameter \'identity\' is not valid.'); + } + + this._solution = { serviceSid, mapSid, identity, }; + this._uri = `/Services/${serviceSid}/Maps/${mapSid}/Permissions/${identity}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SyncMapPermissionInstance) => any): Promise<SyncMapPermissionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SyncMapPermissionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.mapSid, instance._solution.identity)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapPermissionInstance>) => any): Promise<ApiResponse<SyncMapPermissionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SyncMapPermissionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SyncMapPermissionInstance> => ({ + ...response, + body: new SyncMapPermissionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.mapSid, instance._solution.identity) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: SyncMapPermissionContextUpdateOptions,callback?: (error: Error | null, item?: SyncMapPermissionInstance) => any): Promise<SyncMapPermissionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["read"] === null || params["read"] === undefined) { + throw new Error('Required parameter "params[\'read\']" missing.'); + } + + if (params["write"] === null || params["write"] === undefined) { + throw new Error('Required parameter "params[\'write\']" missing.'); + } + + if (params["manage"] === null || params["manage"] === undefined) { + throw new Error('Required parameter "params[\'manage\']" missing.'); + } + + let data: any = {}; + + + + data["Read"] = serialize.bool(params["read"]); + + data["Write"] = serialize.bool(params["write"]); + + data["Manage"] = serialize.bool(params["manage"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncMapPermissionInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.mapSid, instance._solution.identity)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: SyncMapPermissionContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<SyncMapPermissionInstance>) => any): Promise<ApiResponse<SyncMapPermissionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["read"] === null || params["read"] === undefined) { + throw new Error('Required parameter "params[\'read\']" missing.'); + } + + if (params["write"] === null || params["write"] === undefined) { + throw new Error('Required parameter "params[\'write\']" missing.'); + } + + if (params["manage"] === null || params["manage"] === undefined) { + throw new Error('Required parameter "params[\'manage\']" missing.'); + } + + let data: any = {}; + + + + data["Read"] = serialize.bool(params["read"]); + + data["Write"] = serialize.bool(params["write"]); + + data["Manage"] = serialize.bool(params["manage"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SyncMapPermissionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncMapPermissionInstance> => ({ + ...response, + body: new SyncMapPermissionInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.mapSid, instance._solution.identity) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SyncMapPermissionPayload extends TwilioResponsePayload { + permissions: SyncMapPermissionResource[]; +} + +interface SyncMapPermissionResource { + account_sid: string; + service_sid: string; + map_sid: string; + identity: string; + read: boolean; + write: boolean; + manage: boolean; + url: string; +} + +export class SyncMapPermissionInstance { + protected _solution: SyncMapPermissionContextSolution; + protected _context?: SyncMapPermissionContext; + + constructor(protected _version: V1, payload: SyncMapPermissionResource, serviceSid: string, mapSid: string, identity?: string) { + + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.mapSid = (payload.map_sid); + this.identity = (payload.identity); + this.read = (payload.read); + this.write = (payload.write); + this.manage = (payload.manage); + this.url = (payload.url); + + this._solution = { serviceSid, mapSid, identity: identity, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Map Permission resource. + */ + accountSid: string; + /** + * The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the Sync Map to which the Permission applies. + */ + mapSid: string; + /** + * The application-defined string that uniquely identifies the resource\'s User within the Service to an FPA token. + */ + identity: string; + /** + * Whether the identity can read the Sync Map and its Items. + */ + read: boolean; + /** + * Whether the identity can create, update, and delete Items in the Sync Map. + */ + write: boolean; + /** + * Whether the identity can delete the Sync Map. + */ + manage: boolean; + /** + * The absolute URL of the Sync Map Permission resource. + */ + url: string; + + private get _proxy(): SyncMapPermissionContext { + this._context = this._context || new SyncMapPermissionContextImpl(this._version, this._solution.serviceSid, this._solution.mapSid, this._solution.identity); + return this._context; + } + + /** + * Remove a SyncMapPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SyncMapPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SyncMapPermissionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapPermissionInstance + */ + fetch(callback?: (error: Error | null, item?: SyncMapPermissionInstance) => any): Promise<SyncMapPermissionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SyncMapPermissionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapPermissionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncMapPermissionInstance>) => any): Promise<ApiResponse<SyncMapPermissionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SyncMapPermissionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapPermissionInstance + */ + update(params: SyncMapPermissionContextUpdateOptions, callback?: (error: Error | null, item?: SyncMapPermissionInstance) => any): Promise<SyncMapPermissionInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SyncMapPermissionInstance) => any): Promise<SyncMapPermissionInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SyncMapPermissionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncMapPermissionInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncMapPermissionContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncMapPermissionInstance>) => any): Promise<ApiResponse<SyncMapPermissionInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SyncMapPermissionInstance>) => any): Promise<ApiResponse<SyncMapPermissionInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + serviceSid: this.serviceSid, + mapSid: this.mapSid, + identity: this.identity, + read: this.read, + write: this.write, + manage: this.manage, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SyncMapPermissionSolution { + serviceSid: string; + mapSid: string; +} + +export interface SyncMapPermissionListInstance { + _version: V1; + _solution: SyncMapPermissionSolution; + _uri: string; + + (identity: string, ): SyncMapPermissionContext; + get(identity: string, ): SyncMapPermissionContext; + + + + + + + + + + /** + * Streams SyncMapPermissionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapPermissionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SyncMapPermissionInstance, done: (err?: Error) => void) => void): void; + each(params: SyncMapPermissionListInstanceEachOptions, callback?: (item: SyncMapPermissionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SyncMapPermissionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapPermissionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SyncMapPermissionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SyncMapPermissionListInstanceEachOptions, callback?: (item: SyncMapPermissionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SyncMapPermissionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SyncMapPermissionPage) => any): Promise<SyncMapPermissionPage>; + /** + * Retrieve a single target page of SyncMapPermissionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SyncMapPermissionPage>) => any): Promise<ApiResponse<SyncMapPermissionPage>>; + /** + * Lists SyncMapPermissionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapPermissionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SyncMapPermissionInstance[]) => any): Promise<SyncMapPermissionInstance[]>; + list(params: SyncMapPermissionListInstanceOptions, callback?: (error: Error | null, items: SyncMapPermissionInstance[]) => any): Promise<SyncMapPermissionInstance[]>; + /** + * Lists SyncMapPermissionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapPermissionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncMapPermissionInstance[]>) => any): Promise<ApiResponse<SyncMapPermissionInstance[]>>; + listWithHttpInfo(params: SyncMapPermissionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SyncMapPermissionInstance[]>) => any): Promise<ApiResponse<SyncMapPermissionInstance[]>>; + /** + * Retrieve a single page of SyncMapPermissionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapPermissionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SyncMapPermissionPage) => any): Promise<SyncMapPermissionPage>; + page(params: SyncMapPermissionListInstancePageOptions, callback?: (error: Error | null, items: SyncMapPermissionPage) => any): Promise<SyncMapPermissionPage>; + /** + * Retrieve a single page of SyncMapPermissionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncMapPermissionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncMapPermissionPage>) => any): Promise<ApiResponse<SyncMapPermissionPage>>; + pageWithHttpInfo(params: SyncMapPermissionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SyncMapPermissionPage>) => any): Promise<ApiResponse<SyncMapPermissionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SyncMapPermissionListInstance(version: V1, serviceSid: string, mapSid: string): SyncMapPermissionListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(mapSid)) { + throw new Error('Parameter \'mapSid\' is not valid.'); + } + + const instance = ((identity, ) => instance.get(identity, )) as SyncMapPermissionListInstance; + + instance.get = function get(identity, ): SyncMapPermissionContext { + return new SyncMapPermissionContextImpl(version, serviceSid, mapSid, identity); + } + + instance._version = version; + instance._solution = { serviceSid, mapSid, }; + instance._uri = `/Services/${serviceSid}/Maps/${mapSid}/Permissions`; + + instance.page = function page(params?: SyncMapPermissionListInstancePageOptions | ((error: Error | null, items: SyncMapPermissionPage) => any), callback?: (error: Error | null, items: SyncMapPermissionPage) => any): Promise<SyncMapPermissionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SyncMapPermissionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SyncMapPermissionPage) => any): Promise<SyncMapPermissionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SyncMapPermissionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SyncMapPermissionListInstancePageOptions | ((error: Error | null, items: ApiResponse<SyncMapPermissionPage>) => any), callback?: (error: Error | null, items: ApiResponse<SyncMapPermissionPage>) => any): Promise<ApiResponse<SyncMapPermissionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SyncMapPermissionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncMapPermissionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SyncMapPermissionPage>) => any): Promise<ApiResponse<SyncMapPermissionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SyncMapPermissionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncMapPermissionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SyncMapPermissionPage extends Page<V1, SyncMapPermissionPayload, SyncMapPermissionResource, SyncMapPermissionInstance> { +/** +* Initialize the SyncMapPermissionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SyncMapPermissionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SyncMapPermissionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SyncMapPermissionResource): SyncMapPermissionInstance { + + return new SyncMapPermissionInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.mapSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/v1/service/syncStream.ts b/rest/sync/v1/service/syncStream.ts new file mode 100644 index 000000000..4c146ea92 --- /dev/null +++ b/rest/sync/v1/service/syncStream.ts @@ -0,0 +1,963 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { StreamMessageListInstance } from "./syncStream/streamMessage"; + + + + + +/** + * Options to pass to update a SyncStreamInstance + */ +export interface SyncStreamContextUpdateOptions { + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). */ + "ttl"?: number; +} + +/** + * Options to pass to create a SyncStreamInstance + */ +export interface SyncStreamListInstanceCreateOptions { + /** An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. */ + "uniqueName"?: string; + /** How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). */ + "ttl"?: number; +} + +/** + * Options to pass to each + */ +export interface SyncStreamListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SyncStreamInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SyncStreamListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SyncStreamListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 100. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SyncStreamContext { + streamMessages: StreamMessageListInstance; + + /** + * Remove a SyncStreamInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SyncStreamInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SyncStreamInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance + */ + fetch(callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance> + + /** + * Fetch a SyncStreamInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>> + + /** + * Update a SyncStreamInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance + */ + update(callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance>; + /** + * Update a SyncStreamInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance + */ + update(params: SyncStreamContextUpdateOptions, callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance>; + + /** + * Update a SyncStreamInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>>; + /** + * Update a SyncStreamInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncStreamContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SyncStreamContextSolution { + "serviceSid": string; + "sid": string; +} + +export class SyncStreamContextImpl implements SyncStreamContext { + protected _solution: SyncStreamContextSolution; + protected _uri: string; + + protected _streamMessages?: StreamMessageListInstance; + + constructor(protected _version: V1, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Streams/${sid}`; + } + + get streamMessages(): StreamMessageListInstance { + this._streamMessages = this._streamMessages || StreamMessageListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._streamMessages; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SyncStreamInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SyncStreamResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SyncStreamInstance> => ({ + ...response, + body: new SyncStreamInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SyncStreamContextUpdateOptions | ((error: Error | null, item?: SyncStreamInstance) => any),callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncStreamInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SyncStreamContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SyncStreamResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncStreamInstance> => ({ + ...response, + body: new SyncStreamInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SyncStreamPayload extends TwilioResponsePayload { + streams: SyncStreamResource[]; +} + +interface SyncStreamResource { + sid: string; + unique_name: string; + account_sid: string; + service_sid: string; + url: string; + links: Record<string, string>; + date_expires: Date; + date_created: Date; + date_updated: Date; + created_by: string; +} + +export class SyncStreamInstance { + protected _solution: SyncStreamContextSolution; + protected _context?: SyncStreamContext; + + constructor(protected _version: V1, payload: SyncStreamResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.url = (payload.url); + this.links = (payload.links); + this.dateExpires = deserialize.iso8601DateTime(payload.date_expires); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.createdBy = (payload.created_by); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Sync Stream resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. + */ + uniqueName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Stream resource. + */ + accountSid: string; + /** + * The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The absolute URL of the Message Stream resource. + */ + url: string; + /** + * The URLs of the Stream\'s nested resources. + */ + links: Record<string, string>; + /** + * The date and time in GMT when the Message Stream expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Message Stream does not expire, this value is `null`. The Stream might not be deleted immediately after it expires. + */ + dateExpires: Date; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The identity of the Stream\'s creator. If the Stream is created from the client SDK, the value matches the Access Token\'s `identity` field. If the Stream was created from the REST API, the value is \'system\'. + */ + createdBy: string; + + private get _proxy(): SyncStreamContext { + this._context = this._context || new SyncStreamContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a SyncStreamInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SyncStreamInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SyncStreamInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance + */ + fetch(callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SyncStreamInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SyncStreamInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance + */ + update(callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance>; + /** + * Update a SyncStreamInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance + */ + update(params: SyncStreamContextUpdateOptions, callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SyncStreamInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>>; + /** + * Update a SyncStreamInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance with HTTP metadata + */ + updateWithHttpInfo(params: SyncStreamContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the streamMessages. + */ + streamMessages(): StreamMessageListInstance { + return this._proxy.streamMessages; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + url: this.url, + links: this.links, + dateExpires: this.dateExpires, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + createdBy: this.createdBy, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SyncStreamSolution { + serviceSid: string; +} + +export interface SyncStreamListInstance { + _version: V1; + _solution: SyncStreamSolution; + _uri: string; + + (sid: string, ): SyncStreamContext; + get(sid: string, ): SyncStreamContext; + + + + + + + + + /** + * Create a SyncStreamInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance + */ + create(callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance>; + /** + * Create a SyncStreamInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance + */ + create(params: SyncStreamListInstanceCreateOptions, callback?: (error: Error | null, item?: SyncStreamInstance) => any): Promise<SyncStreamInstance>; + + /** + * Create a SyncStreamInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>>; + /** + * Create a SyncStreamInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SyncStreamInstance with HTTP metadata + */ + createWithHttpInfo(params: SyncStreamListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>>; + + + + + /** + * Streams SyncStreamInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncStreamListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SyncStreamInstance, done: (err?: Error) => void) => void): void; + each(params: SyncStreamListInstanceEachOptions, callback?: (item: SyncStreamInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SyncStreamInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncStreamListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SyncStreamInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SyncStreamListInstanceEachOptions, callback?: (item: SyncStreamInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SyncStreamInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SyncStreamPage) => any): Promise<SyncStreamPage>; + /** + * Retrieve a single target page of SyncStreamInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SyncStreamPage>) => any): Promise<ApiResponse<SyncStreamPage>>; + /** + * Lists SyncStreamInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncStreamListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SyncStreamInstance[]) => any): Promise<SyncStreamInstance[]>; + list(params: SyncStreamListInstanceOptions, callback?: (error: Error | null, items: SyncStreamInstance[]) => any): Promise<SyncStreamInstance[]>; + /** + * Lists SyncStreamInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncStreamListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncStreamInstance[]>) => any): Promise<ApiResponse<SyncStreamInstance[]>>; + listWithHttpInfo(params: SyncStreamListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SyncStreamInstance[]>) => any): Promise<ApiResponse<SyncStreamInstance[]>>; + /** + * Retrieve a single page of SyncStreamInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncStreamListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SyncStreamPage) => any): Promise<SyncStreamPage>; + page(params: SyncStreamListInstancePageOptions, callback?: (error: Error | null, items: SyncStreamPage) => any): Promise<SyncStreamPage>; + /** + * Retrieve a single page of SyncStreamInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SyncStreamListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SyncStreamPage>) => any): Promise<ApiResponse<SyncStreamPage>>; + pageWithHttpInfo(params: SyncStreamListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SyncStreamPage>) => any): Promise<ApiResponse<SyncStreamPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SyncStreamListInstance(version: V1, serviceSid: string): SyncStreamListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as SyncStreamListInstance; + + instance.get = function get(sid, ): SyncStreamContext { + return new SyncStreamContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Streams`; + + instance.create = function create(params?: SyncStreamListInstanceCreateOptions | ((error: Error | null, items: SyncStreamInstance) => any), callback?: (error: Error | null, items: SyncStreamInstance) => any): Promise<SyncStreamInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SyncStreamInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: SyncStreamListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<SyncStreamInstance>) => any), callback?: (error: Error | null, items: ApiResponse<SyncStreamInstance>) => any): Promise<ApiResponse<SyncStreamInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SyncStreamResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SyncStreamInstance> => ({ + ...response, + body: new SyncStreamInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SyncStreamListInstancePageOptions | ((error: Error | null, items: SyncStreamPage) => any), callback?: (error: Error | null, items: SyncStreamPage) => any): Promise<SyncStreamPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SyncStreamPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SyncStreamPage) => any): Promise<SyncStreamPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SyncStreamPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SyncStreamListInstancePageOptions | ((error: Error | null, items: ApiResponse<SyncStreamPage>) => any), callback?: (error: Error | null, items: ApiResponse<SyncStreamPage>) => any): Promise<ApiResponse<SyncStreamPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SyncStreamPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncStreamPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SyncStreamPage>) => any): Promise<ApiResponse<SyncStreamPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SyncStreamPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SyncStreamPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SyncStreamPage extends Page<V1, SyncStreamPayload, SyncStreamResource, SyncStreamInstance> { +/** +* Initialize the SyncStreamPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SyncStreamSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SyncStreamInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SyncStreamResource): SyncStreamInstance { + + return new SyncStreamInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/sync/v1/service/syncStream/streamMessage.ts b/rest/sync/v1/service/syncStream/streamMessage.ts new file mode 100644 index 000000000..0affc4de6 --- /dev/null +++ b/rest/sync/v1/service/syncStream/streamMessage.ts @@ -0,0 +1,212 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Sync + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to create a StreamMessageInstance + */ +export interface StreamMessageListInstanceCreateOptions { + /** A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. */ + "data": any; +} + + +export interface StreamMessageSolution { + serviceSid: string; + streamSid: string; +} + +export interface StreamMessageListInstance { + _version: V1; + _solution: StreamMessageSolution; + _uri: string; + + + + /** + * Create a StreamMessageInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StreamMessageInstance + */ + create(params: StreamMessageListInstanceCreateOptions, callback?: (error: Error | null, item?: StreamMessageInstance) => any): Promise<StreamMessageInstance>; + + /** + * Create a StreamMessageInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed StreamMessageInstance with HTTP metadata + */ + createWithHttpInfo(params: StreamMessageListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<StreamMessageInstance>) => any): Promise<ApiResponse<StreamMessageInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function StreamMessageListInstance(version: V1, serviceSid: string, streamSid: string): StreamMessageListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(streamSid)) { + throw new Error('Parameter \'streamSid\' is not valid.'); + } + + const instance = {} as StreamMessageListInstance; + + instance._version = version; + instance._solution = { serviceSid, streamSid, }; + instance._uri = `/Services/${serviceSid}/Streams/${streamSid}/Messages`; + + instance.create = function create(params: StreamMessageListInstanceCreateOptions, callback?: (error: Error | null, items: StreamMessageInstance) => any): Promise<StreamMessageInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["data"] === null || params["data"] === undefined) { + throw new Error('Required parameter "params[\'data\']" missing.'); + } + + let data: any = {}; + + + + data["Data"] = serialize.object(params["data"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new StreamMessageInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.streamSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: StreamMessageListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<StreamMessageInstance>) => any): Promise<ApiResponse<StreamMessageInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["data"] === null || params["data"] === undefined) { + throw new Error('Required parameter "params[\'data\']" missing.'); + } + + let data: any = {}; + + + + data["Data"] = serialize.object(params["data"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<StreamMessageResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<StreamMessageInstance> => ({ + ...response, + body: new StreamMessageInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.streamSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface StreamMessagePayload extends StreamMessageResource {} + +interface StreamMessageResource { + sid: string; + data: any; +} + +export class StreamMessageInstance { + + constructor(protected _version: V1, payload: StreamMessageResource, serviceSid: string, streamSid: string) { + + this.sid = (payload.sid); + this.data = (payload.data); + + } + + /** + * The unique string that we created to identify the Stream Message resource. + */ + sid: string; + /** + * An arbitrary, schema-less object that contains the Stream Message body. Can be up to 4 KiB in length. + */ + data: any; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + data: this.data, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/taskrouter/V1.ts b/rest/taskrouter/V1.ts new file mode 100644 index 000000000..060890559 --- /dev/null +++ b/rest/taskrouter/V1.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import TaskrouterBase from "../TaskrouterBase"; +import Version from "../../base/Version"; +import { WorkspaceListInstance } from "./v1/workspace"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Taskrouter + * + * @param domain - The Twilio (Twilio.Taskrouter) domain + */ + constructor(domain: TaskrouterBase) { + super(domain, "v1"); + } + + /** workspaces - { Twilio.Taskrouter.V1.WorkspaceListInstance } resource */ + protected _workspaces?: WorkspaceListInstance; + + /** Getter for workspaces resource */ + get workspaces(): WorkspaceListInstance { + this._workspaces = this._workspaces || WorkspaceListInstance(this); + return this._workspaces; + } + +} diff --git a/rest/taskrouter/v1/workspace.ts b/rest/taskrouter/v1/workspace.ts new file mode 100644 index 000000000..ae9a6d4e3 --- /dev/null +++ b/rest/taskrouter/v1/workspace.ts @@ -0,0 +1,1180 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ActivityListInstance } from "./workspace/activity"; +import { EventListInstance } from "./workspace/event"; +import { TaskListInstance } from "./workspace/task"; +import { TaskChannelListInstance } from "./workspace/taskChannel"; +import { TaskQueueListInstance } from "./workspace/taskQueue"; +import { WorkerListInstance } from "./workspace/worker"; +import { WorkflowListInstance } from "./workspace/workflow"; +import { WorkspaceCumulativeStatisticsListInstance } from "./workspace/workspaceCumulativeStatistics"; +import { WorkspaceRealTimeStatisticsListInstance } from "./workspace/workspaceRealTimeStatistics"; +import { WorkspaceStatisticsListInstance } from "./workspace/workspaceStatistics"; + + +/** + * The type of TaskQueue to prioritize when Workers are receiving Tasks from both types of TaskQueues. Can be: `LIFO` or `FIFO` and the default is `FIFO`. For more information, see [Queue Ordering](https://www.twilio.com/docs/taskrouter/queue-ordering-last-first-out-lifo). + */ +export type WorkspaceQueueOrder = 'FIFO'|'LIFO'; + + + + +/** + * Options to pass to update a WorkspaceInstance + */ +export interface WorkspaceContextUpdateOptions { + /** The SID of the Activity that will be used when new Workers are created in the Workspace. */ + "defaultActivitySid"?: string; + /** The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio\\\'s [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). */ + "eventCallbackUrl"?: string; + /** The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. */ + "eventsFilter"?: string; + /** A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. */ + "friendlyName"?: string; + /** Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can\\\'t be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). */ + "multiTaskEnabled"?: boolean; + /** The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. */ + "timeoutActivitySid"?: string; + /** */ + "prioritizeQueueOrder"?: WorkspaceQueueOrder; +} + +/** + * Options to pass to create a WorkspaceInstance + */ +export interface WorkspaceListInstanceCreateOptions { + /** A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. */ + "friendlyName": string; + /** The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio\\\'s [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). */ + "eventCallbackUrl"?: string; + /** The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. */ + "eventsFilter"?: string; + /** Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). */ + "multiTaskEnabled"?: boolean; + /** An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. */ + "template"?: string; + /** */ + "prioritizeQueueOrder"?: WorkspaceQueueOrder; +} + +/** + * Options to pass to each + */ +export interface WorkspaceListInstanceEachOptions { + /** The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: WorkspaceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface WorkspaceListInstanceOptions { + /** The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface WorkspaceListInstancePageOptions { + /** The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface WorkspaceContext { + activities: ActivityListInstance; + events: EventListInstance; + tasks: TaskListInstance; + taskChannels: TaskChannelListInstance; + taskQueues: TaskQueueListInstance; + workers: WorkerListInstance; + workflows: WorkflowListInstance; + cumulativeStatistics: WorkspaceCumulativeStatisticsListInstance; + realTimeStatistics: WorkspaceRealTimeStatisticsListInstance; + statistics: WorkspaceStatisticsListInstance; + + /** + * Remove a WorkspaceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a WorkspaceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a WorkspaceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance + */ + fetch(callback?: (error: Error | null, item?: WorkspaceInstance) => any): Promise<WorkspaceInstance> + + /** + * Fetch a WorkspaceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>> + + /** + * Update a WorkspaceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance + */ + update(callback?: (error: Error | null, item?: WorkspaceInstance) => any): Promise<WorkspaceInstance>; + /** + * Update a WorkspaceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance + */ + update(params: WorkspaceContextUpdateOptions, callback?: (error: Error | null, item?: WorkspaceInstance) => any): Promise<WorkspaceInstance>; + + /** + * Update a WorkspaceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>>; + /** + * Update a WorkspaceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance with HTTP metadata + */ + updateWithHttpInfo(params: WorkspaceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkspaceContextSolution { + "sid": string; +} + +export class WorkspaceContextImpl implements WorkspaceContext { + protected _solution: WorkspaceContextSolution; + protected _uri: string; + + protected _activities?: ActivityListInstance; + protected _events?: EventListInstance; + protected _tasks?: TaskListInstance; + protected _taskChannels?: TaskChannelListInstance; + protected _taskQueues?: TaskQueueListInstance; + protected _workers?: WorkerListInstance; + protected _workflows?: WorkflowListInstance; + protected _cumulativeStatistics?: WorkspaceCumulativeStatisticsListInstance; + protected _realTimeStatistics?: WorkspaceRealTimeStatisticsListInstance; + protected _statistics?: WorkspaceStatisticsListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Workspaces/${sid}`; + } + + get activities(): ActivityListInstance { + this._activities = this._activities || ActivityListInstance(this._version, this._solution.sid); + return this._activities; + } + + get events(): EventListInstance { + this._events = this._events || EventListInstance(this._version, this._solution.sid); + return this._events; + } + + get tasks(): TaskListInstance { + this._tasks = this._tasks || TaskListInstance(this._version, this._solution.sid); + return this._tasks; + } + + get taskChannels(): TaskChannelListInstance { + this._taskChannels = this._taskChannels || TaskChannelListInstance(this._version, this._solution.sid); + return this._taskChannels; + } + + get taskQueues(): TaskQueueListInstance { + this._taskQueues = this._taskQueues || TaskQueueListInstance(this._version, this._solution.sid); + return this._taskQueues; + } + + get workers(): WorkerListInstance { + this._workers = this._workers || WorkerListInstance(this._version, this._solution.sid); + return this._workers; + } + + get workflows(): WorkflowListInstance { + this._workflows = this._workflows || WorkflowListInstance(this._version, this._solution.sid); + return this._workflows; + } + + get cumulativeStatistics(): WorkspaceCumulativeStatisticsListInstance { + this._cumulativeStatistics = this._cumulativeStatistics || WorkspaceCumulativeStatisticsListInstance(this._version, this._solution.sid); + return this._cumulativeStatistics; + } + + get realTimeStatistics(): WorkspaceRealTimeStatisticsListInstance { + this._realTimeStatistics = this._realTimeStatistics || WorkspaceRealTimeStatisticsListInstance(this._version, this._solution.sid); + return this._realTimeStatistics; + } + + get statistics(): WorkspaceStatisticsListInstance { + this._statistics = this._statistics || WorkspaceStatisticsListInstance(this._version, this._solution.sid); + return this._statistics; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: WorkspaceInstance) => any): Promise<WorkspaceInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WorkspaceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkspaceResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<WorkspaceInstance> => ({ + ...response, + body: new WorkspaceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WorkspaceContextUpdateOptions | ((error: Error | null, item?: WorkspaceInstance) => any),callback?: (error: Error | null, item?: WorkspaceInstance) => any): Promise<WorkspaceInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["defaultActivitySid"] !== undefined) + data["DefaultActivitySid"] = params["defaultActivitySid"]; + if (params["eventCallbackUrl"] !== undefined) + data["EventCallbackUrl"] = params["eventCallbackUrl"]; + if (params["eventsFilter"] !== undefined) + data["EventsFilter"] = params["eventsFilter"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["multiTaskEnabled"] !== undefined) + data["MultiTaskEnabled"] = serialize.bool(params["multiTaskEnabled"]); + if (params["timeoutActivitySid"] !== undefined) + data["TimeoutActivitySid"] = params["timeoutActivitySid"]; + if (params["prioritizeQueueOrder"] !== undefined) + data["PrioritizeQueueOrder"] = params["prioritizeQueueOrder"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WorkspaceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WorkspaceContextUpdateOptions | ((error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["defaultActivitySid"] !== undefined) + data["DefaultActivitySid"] = params["defaultActivitySid"]; + if (params["eventCallbackUrl"] !== undefined) + data["EventCallbackUrl"] = params["eventCallbackUrl"]; + if (params["eventsFilter"] !== undefined) + data["EventsFilter"] = params["eventsFilter"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["multiTaskEnabled"] !== undefined) + data["MultiTaskEnabled"] = serialize.bool(params["multiTaskEnabled"]); + if (params["timeoutActivitySid"] !== undefined) + data["TimeoutActivitySid"] = params["timeoutActivitySid"]; + if (params["prioritizeQueueOrder"] !== undefined) + data["PrioritizeQueueOrder"] = params["prioritizeQueueOrder"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<WorkspaceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<WorkspaceInstance> => ({ + ...response, + body: new WorkspaceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkspacePayload extends TwilioResponsePayload { + workspaces: WorkspaceResource[]; +} + +interface WorkspaceResource { + account_sid: string; + date_created: Date; + date_updated: Date; + default_activity_name: string; + default_activity_sid: string; + event_callback_url: string; + events_filter: string; + friendly_name: string; + multi_task_enabled: boolean; + sid: string; + timeout_activity_name: string; + timeout_activity_sid: string; + prioritize_queue_order: WorkspaceQueueOrder; + url: string; + links: Record<string, string>; +} + +export class WorkspaceInstance { + protected _solution: WorkspaceContextSolution; + protected _context?: WorkspaceContext; + + constructor(protected _version: V1, payload: WorkspaceResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.defaultActivityName = (payload.default_activity_name); + this.defaultActivitySid = (payload.default_activity_sid); + this.eventCallbackUrl = (payload.event_callback_url); + this.eventsFilter = (payload.events_filter); + this.friendlyName = (payload.friendly_name); + this.multiTaskEnabled = (payload.multi_task_enabled); + this.sid = (payload.sid); + this.timeoutActivityName = (payload.timeout_activity_name); + this.timeoutActivitySid = (payload.timeout_activity_sid); + this.prioritizeQueueOrder = payload.prioritize_queue_order; + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + */ + accountSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The name of the default activity. + */ + defaultActivityName: string; + /** + * The SID of the Activity that will be used when new Workers are created in the Workspace. + */ + defaultActivitySid: string; + /** + * The URL we call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio\'s [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + */ + eventCallbackUrl: string; + /** + * The list of Workspace events for which to call `event_callback_url`. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + */ + eventsFilter: string; + /** + * The string that you assigned to describe the Workspace resource. For example `Customer Support` or `2014 Election Campaign`. + */ + friendlyName: string; + /** + * Whether multi-tasking is enabled. The default is `true`, which enables multi-tasking. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking each Worker would only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + */ + multiTaskEnabled: boolean; + /** + * The unique string that we created to identify the Workspace resource. + */ + sid: string; + /** + * The name of the timeout activity. + */ + timeoutActivityName: string; + /** + * The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + */ + timeoutActivitySid: string; + prioritizeQueueOrder: WorkspaceQueueOrder; + /** + * The absolute URL of the Workspace resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): WorkspaceContext { + this._context = this._context || new WorkspaceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a WorkspaceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a WorkspaceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a WorkspaceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance + */ + fetch(callback?: (error: Error | null, item?: WorkspaceInstance) => any): Promise<WorkspaceInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WorkspaceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WorkspaceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance + */ + update(callback?: (error: Error | null, item?: WorkspaceInstance) => any): Promise<WorkspaceInstance>; + /** + * Update a WorkspaceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance + */ + update(params: WorkspaceContextUpdateOptions, callback?: (error: Error | null, item?: WorkspaceInstance) => any): Promise<WorkspaceInstance>; + + update(params?: any, callback?: (error: Error | null, item?: WorkspaceInstance) => any): Promise<WorkspaceInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a WorkspaceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>>; + /** + * Update a WorkspaceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance with HTTP metadata + */ + updateWithHttpInfo(params: WorkspaceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the activities. + */ + activities(): ActivityListInstance { + return this._proxy.activities; + } + + /** + * Access the events. + */ + events(): EventListInstance { + return this._proxy.events; + } + + /** + * Access the tasks. + */ + tasks(): TaskListInstance { + return this._proxy.tasks; + } + + /** + * Access the taskChannels. + */ + taskChannels(): TaskChannelListInstance { + return this._proxy.taskChannels; + } + + /** + * Access the taskQueues. + */ + taskQueues(): TaskQueueListInstance { + return this._proxy.taskQueues; + } + + /** + * Access the workers. + */ + workers(): WorkerListInstance { + return this._proxy.workers; + } + + /** + * Access the workflows. + */ + workflows(): WorkflowListInstance { + return this._proxy.workflows; + } + + /** + * Access the cumulativeStatistics. + */ + cumulativeStatistics(): WorkspaceCumulativeStatisticsListInstance { + return this._proxy.cumulativeStatistics; + } + + /** + * Access the realTimeStatistics. + */ + realTimeStatistics(): WorkspaceRealTimeStatisticsListInstance { + return this._proxy.realTimeStatistics; + } + + /** + * Access the statistics. + */ + statistics(): WorkspaceStatisticsListInstance { + return this._proxy.statistics; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + defaultActivityName: this.defaultActivityName, + defaultActivitySid: this.defaultActivitySid, + eventCallbackUrl: this.eventCallbackUrl, + eventsFilter: this.eventsFilter, + friendlyName: this.friendlyName, + multiTaskEnabled: this.multiTaskEnabled, + sid: this.sid, + timeoutActivityName: this.timeoutActivityName, + timeoutActivitySid: this.timeoutActivitySid, + prioritizeQueueOrder: this.prioritizeQueueOrder, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkspaceSolution { +} + +export interface WorkspaceListInstance { + _version: V1; + _solution: WorkspaceSolution; + _uri: string; + + (sid: string, ): WorkspaceContext; + get(sid: string, ): WorkspaceContext; + + + + + + + + + /** + * Create a WorkspaceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance + */ + create(params: WorkspaceListInstanceCreateOptions, callback?: (error: Error | null, item?: WorkspaceInstance) => any): Promise<WorkspaceInstance>; + + /** + * Create a WorkspaceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceInstance with HTTP metadata + */ + createWithHttpInfo(params: WorkspaceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>>; + + + + + /** + * Streams WorkspaceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkspaceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: WorkspaceInstance, done: (err?: Error) => void) => void): void; + each(params: WorkspaceListInstanceEachOptions, callback?: (item: WorkspaceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams WorkspaceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkspaceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: WorkspaceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: WorkspaceListInstanceEachOptions, callback?: (item: WorkspaceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of WorkspaceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: WorkspacePage) => any): Promise<WorkspacePage>; + /** + * Retrieve a single target page of WorkspaceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<WorkspacePage>) => any): Promise<ApiResponse<WorkspacePage>>; + /** + * Lists WorkspaceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkspaceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: WorkspaceInstance[]) => any): Promise<WorkspaceInstance[]>; + list(params: WorkspaceListInstanceOptions, callback?: (error: Error | null, items: WorkspaceInstance[]) => any): Promise<WorkspaceInstance[]>; + /** + * Lists WorkspaceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkspaceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<WorkspaceInstance[]>) => any): Promise<ApiResponse<WorkspaceInstance[]>>; + listWithHttpInfo(params: WorkspaceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<WorkspaceInstance[]>) => any): Promise<ApiResponse<WorkspaceInstance[]>>; + /** + * Retrieve a single page of WorkspaceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkspaceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: WorkspacePage) => any): Promise<WorkspacePage>; + page(params: WorkspaceListInstancePageOptions, callback?: (error: Error | null, items: WorkspacePage) => any): Promise<WorkspacePage>; + /** + * Retrieve a single page of WorkspaceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkspaceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<WorkspacePage>) => any): Promise<ApiResponse<WorkspacePage>>; + pageWithHttpInfo(params: WorkspaceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<WorkspacePage>) => any): Promise<ApiResponse<WorkspacePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkspaceListInstance(version: V1): WorkspaceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as WorkspaceListInstance; + + instance.get = function get(sid, ): WorkspaceContext { + return new WorkspaceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Workspaces`; + + instance.create = function create(params: WorkspaceListInstanceCreateOptions, callback?: (error: Error | null, items: WorkspaceInstance) => any): Promise<WorkspaceInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["eventCallbackUrl"] !== undefined) + data["EventCallbackUrl"] = params["eventCallbackUrl"]; + if (params["eventsFilter"] !== undefined) + data["EventsFilter"] = params["eventsFilter"]; + if (params["multiTaskEnabled"] !== undefined) + data["MultiTaskEnabled"] = serialize.bool(params["multiTaskEnabled"]); + if (params["template"] !== undefined) + data["Template"] = params["template"]; + if (params["prioritizeQueueOrder"] !== undefined) + data["PrioritizeQueueOrder"] = params["prioritizeQueueOrder"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WorkspaceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: WorkspaceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<WorkspaceInstance>) => any): Promise<ApiResponse<WorkspaceInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["eventCallbackUrl"] !== undefined) + data["EventCallbackUrl"] = params["eventCallbackUrl"]; + if (params["eventsFilter"] !== undefined) + data["EventsFilter"] = params["eventsFilter"]; + if (params["multiTaskEnabled"] !== undefined) + data["MultiTaskEnabled"] = serialize.bool(params["multiTaskEnabled"]); + if (params["template"] !== undefined) + data["Template"] = params["template"]; + if (params["prioritizeQueueOrder"] !== undefined) + data["PrioritizeQueueOrder"] = params["prioritizeQueueOrder"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<WorkspaceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<WorkspaceInstance> => ({ + ...response, + body: new WorkspaceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: WorkspaceListInstancePageOptions | ((error: Error | null, items: WorkspacePage) => any), callback?: (error: Error | null, items: WorkspacePage) => any): Promise<WorkspacePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new WorkspacePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: WorkspacePage) => any): Promise<WorkspacePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new WorkspacePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: WorkspaceListInstancePageOptions | ((error: Error | null, items: ApiResponse<WorkspacePage>) => any), callback?: (error: Error | null, items: ApiResponse<WorkspacePage>) => any): Promise<ApiResponse<WorkspacePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkspacePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WorkspacePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<WorkspacePage>) => any): Promise<ApiResponse<WorkspacePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<WorkspacePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WorkspacePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class WorkspacePage extends Page<V1, WorkspacePayload, WorkspaceResource, WorkspaceInstance> { +/** +* Initialize the WorkspacePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: WorkspaceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of WorkspaceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: WorkspaceResource): WorkspaceInstance { + + return new WorkspaceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/activity.ts b/rest/taskrouter/v1/workspace/activity.ts new file mode 100644 index 000000000..aca257643 --- /dev/null +++ b/rest/taskrouter/v1/workspace/activity.ts @@ -0,0 +1,944 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a ActivityInstance + */ +export interface ActivityContextUpdateOptions { + /** A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a ActivityInstance + */ +export interface ActivityListInstanceCreateOptions { + /** A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. */ + "friendlyName": string; + /** Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. */ + "available"?: boolean; +} + +/** + * Options to pass to each + */ +export interface ActivityListInstanceEachOptions { + /** The `friendly_name` of the Activity resources to read. */ + "friendlyName"?: string; + /** Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of \'1\' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. */ + "available"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ActivityInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ActivityListInstanceOptions { + /** The `friendly_name` of the Activity resources to read. */ + "friendlyName"?: string; + /** Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of \'1\' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. */ + "available"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ActivityListInstancePageOptions { + /** The `friendly_name` of the Activity resources to read. */ + "friendlyName"?: string; + /** Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of \'1\' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. */ + "available"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ActivityContext { + + /** + * Remove a ActivityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ActivityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ActivityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance + */ + fetch(callback?: (error: Error | null, item?: ActivityInstance) => any): Promise<ActivityInstance> + + /** + * Fetch a ActivityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>> + + /** + * Update a ActivityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance + */ + update(callback?: (error: Error | null, item?: ActivityInstance) => any): Promise<ActivityInstance>; + /** + * Update a ActivityInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance + */ + update(params: ActivityContextUpdateOptions, callback?: (error: Error | null, item?: ActivityInstance) => any): Promise<ActivityInstance>; + + /** + * Update a ActivityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>>; + /** + * Update a ActivityInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance with HTTP metadata + */ + updateWithHttpInfo(params: ActivityContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ActivityContextSolution { + "workspaceSid": string; + "sid": string; +} + +export class ActivityContextImpl implements ActivityContext { + protected _solution: ActivityContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, sid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { workspaceSid, sid, }; + this._uri = `/Workspaces/${workspaceSid}/Activities/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ActivityInstance) => any): Promise<ActivityInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ActivityInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ActivityResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ActivityInstance> => ({ + ...response, + body: new ActivityInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ActivityContextUpdateOptions | ((error: Error | null, item?: ActivityInstance) => any),callback?: (error: Error | null, item?: ActivityInstance) => any): Promise<ActivityInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ActivityInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ActivityContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ActivityInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ActivityResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ActivityInstance> => ({ + ...response, + body: new ActivityInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ActivityPayload extends TwilioResponsePayload { + activities: ActivityResource[]; +} + +interface ActivityResource { + account_sid: string; + available: boolean; + date_created: Date; + date_updated: Date; + friendly_name: string; + sid: string; + workspace_sid: string; + url: string; + links: Record<string, string>; +} + +export class ActivityInstance { + protected _solution: ActivityContextSolution; + protected _context?: ActivityContext; + + constructor(protected _version: V1, payload: ActivityResource, workspaceSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.available = (payload.available); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { workspaceSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Activity resource. + */ + accountSid: string; + /** + * Whether the Worker is eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` indicates the Activity is available. All other values indicate that it is not. The value cannot be changed after the Activity is created. + */ + available: boolean; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the Activity resource. + */ + friendlyName: string; + /** + * The unique string that we created to identify the Activity resource. + */ + sid: string; + /** + * The SID of the Workspace that contains the Activity. + */ + workspaceSid: string; + /** + * The absolute URL of the Activity resource. + */ + url: string; + links: Record<string, string>; + + private get _proxy(): ActivityContext { + this._context = this._context || new ActivityContextImpl(this._version, this._solution.workspaceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a ActivityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ActivityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ActivityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance + */ + fetch(callback?: (error: Error | null, item?: ActivityInstance) => any): Promise<ActivityInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ActivityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ActivityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance + */ + update(callback?: (error: Error | null, item?: ActivityInstance) => any): Promise<ActivityInstance>; + /** + * Update a ActivityInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance + */ + update(params: ActivityContextUpdateOptions, callback?: (error: Error | null, item?: ActivityInstance) => any): Promise<ActivityInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ActivityInstance) => any): Promise<ActivityInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ActivityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>>; + /** + * Update a ActivityInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance with HTTP metadata + */ + updateWithHttpInfo(params: ActivityContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + available: this.available, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + sid: this.sid, + workspaceSid: this.workspaceSid, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ActivitySolution { + workspaceSid: string; +} + +export interface ActivityListInstance { + _version: V1; + _solution: ActivitySolution; + _uri: string; + + (sid: string, ): ActivityContext; + get(sid: string, ): ActivityContext; + + + + + + + + + /** + * Create a ActivityInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance + */ + create(params: ActivityListInstanceCreateOptions, callback?: (error: Error | null, item?: ActivityInstance) => any): Promise<ActivityInstance>; + + /** + * Create a ActivityInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ActivityInstance with HTTP metadata + */ + createWithHttpInfo(params: ActivityListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>>; + + + + + /** + * Streams ActivityInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ActivityListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ActivityInstance, done: (err?: Error) => void) => void): void; + each(params: ActivityListInstanceEachOptions, callback?: (item: ActivityInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ActivityInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ActivityListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ActivityInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ActivityListInstanceEachOptions, callback?: (item: ActivityInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ActivityInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ActivityPage) => any): Promise<ActivityPage>; + /** + * Retrieve a single target page of ActivityInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ActivityPage>) => any): Promise<ApiResponse<ActivityPage>>; + /** + * Lists ActivityInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ActivityListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ActivityInstance[]) => any): Promise<ActivityInstance[]>; + list(params: ActivityListInstanceOptions, callback?: (error: Error | null, items: ActivityInstance[]) => any): Promise<ActivityInstance[]>; + /** + * Lists ActivityInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ActivityListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ActivityInstance[]>) => any): Promise<ApiResponse<ActivityInstance[]>>; + listWithHttpInfo(params: ActivityListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ActivityInstance[]>) => any): Promise<ApiResponse<ActivityInstance[]>>; + /** + * Retrieve a single page of ActivityInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ActivityListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ActivityPage) => any): Promise<ActivityPage>; + page(params: ActivityListInstancePageOptions, callback?: (error: Error | null, items: ActivityPage) => any): Promise<ActivityPage>; + /** + * Retrieve a single page of ActivityInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ActivityListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ActivityPage>) => any): Promise<ApiResponse<ActivityPage>>; + pageWithHttpInfo(params: ActivityListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ActivityPage>) => any): Promise<ApiResponse<ActivityPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ActivityListInstance(version: V1, workspaceSid: string): ActivityListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ActivityListInstance; + + instance.get = function get(sid, ): ActivityContext { + return new ActivityContextImpl(version, workspaceSid, sid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = `/Workspaces/${workspaceSid}/Activities`; + + instance.create = function create(params: ActivityListInstanceCreateOptions, callback?: (error: Error | null, items: ActivityInstance) => any): Promise<ActivityInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["available"] !== undefined) + data["Available"] = serialize.bool(params["available"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ActivityInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ActivityListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ActivityInstance>) => any): Promise<ApiResponse<ActivityInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["available"] !== undefined) + data["Available"] = serialize.bool(params["available"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ActivityResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ActivityInstance> => ({ + ...response, + body: new ActivityInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ActivityListInstancePageOptions | ((error: Error | null, items: ActivityPage) => any), callback?: (error: Error | null, items: ActivityPage) => any): Promise<ActivityPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["available"] !== undefined) + data["Available"] = params["available"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ActivityPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ActivityPage) => any): Promise<ActivityPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ActivityPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ActivityListInstancePageOptions | ((error: Error | null, items: ApiResponse<ActivityPage>) => any), callback?: (error: Error | null, items: ApiResponse<ActivityPage>) => any): Promise<ApiResponse<ActivityPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["available"] !== undefined) + data["Available"] = params["available"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ActivityPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ActivityPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ActivityPage>) => any): Promise<ApiResponse<ActivityPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ActivityPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ActivityPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ActivityPage extends Page<V1, ActivityPayload, ActivityResource, ActivityInstance> { +/** +* Initialize the ActivityPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ActivitySolution) { + super(version, response, solution); + } + + /** + * Build an instance of ActivityInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ActivityResource): ActivityInstance { + + return new ActivityInstance( + this._version, + payload, + this._solution.workspaceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/event.ts b/rest/taskrouter/v1/workspace/event.ts new file mode 100644 index 000000000..424365da3 --- /dev/null +++ b/rest/taskrouter/v1/workspace/event.ts @@ -0,0 +1,749 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface EventListInstanceEachOptions { + /** Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** The type of Events to read. Returns only Events of the type specified. */ + "eventType"?: string; + /** The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. */ + "minutes"?: number; + /** The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. */ + "reservationSid"?: string; + /** Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. */ + "startDate"?: Date; + /** The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. */ + "taskQueueSid"?: string; + /** The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. */ + "taskSid"?: string; + /** The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. */ + "workerSid"?: string; + /** The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. */ + "workflowSid"?: string; + /** The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. */ + "taskChannel"?: string; + /** The SID of the Event resource to read. */ + "sid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EventInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EventListInstanceOptions { + /** Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** The type of Events to read. Returns only Events of the type specified. */ + "eventType"?: string; + /** The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. */ + "minutes"?: number; + /** The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. */ + "reservationSid"?: string; + /** Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. */ + "startDate"?: Date; + /** The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. */ + "taskQueueSid"?: string; + /** The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. */ + "taskSid"?: string; + /** The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. */ + "workerSid"?: string; + /** The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. */ + "workflowSid"?: string; + /** The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. */ + "taskChannel"?: string; + /** The SID of the Event resource to read. */ + "sid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EventListInstancePageOptions { + /** Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** The type of Events to read. Returns only Events of the type specified. */ + "eventType"?: string; + /** The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. */ + "minutes"?: number; + /** The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. */ + "reservationSid"?: string; + /** Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. */ + "startDate"?: Date; + /** The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. */ + "taskQueueSid"?: string; + /** The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. */ + "taskSid"?: string; + /** The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. */ + "workerSid"?: string; + /** The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. */ + "workflowSid"?: string; + /** The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. */ + "taskChannel"?: string; + /** The SID of the Event resource to read. */ + "sid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EventContext { + + /** + * Fetch a EventInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventInstance + */ + fetch(callback?: (error: Error | null, item?: EventInstance) => any): Promise<EventInstance> + + /** + * Fetch a EventInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EventInstance>) => any): Promise<ApiResponse<EventInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EventContextSolution { + "workspaceSid": string; + "sid": string; +} + +export class EventContextImpl implements EventContext { + protected _solution: EventContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, sid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { workspaceSid, sid, }; + this._uri = `/Workspaces/${workspaceSid}/Events/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: EventInstance) => any): Promise<EventInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EventInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EventInstance>) => any): Promise<ApiResponse<EventInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EventResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EventInstance> => ({ + ...response, + body: new EventInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EventPayload extends TwilioResponsePayload { + events: EventResource[]; +} + +interface EventResource { + account_sid: string; + actor_sid: string; + actor_type: string; + actor_url: string; + description: string; + event_data: any; + event_date: Date; + event_date_ms: number; + event_type: string; + resource_sid: string; + resource_type: string; + resource_url: string; + sid: string; + source: string; + source_ip_address: string; + url: string; + workspace_sid: string; +} + +export class EventInstance { + protected _solution: EventContextSolution; + protected _context?: EventContext; + + constructor(protected _version: V1, payload: EventResource, workspaceSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.actorSid = (payload.actor_sid); + this.actorType = (payload.actor_type); + this.actorUrl = (payload.actor_url); + this.description = (payload.description); + this.eventData = (payload.event_data); + this.eventDate = deserialize.iso8601DateTime(payload.event_date); + this.eventDateMs = (payload.event_date_ms); + this.eventType = (payload.event_type); + this.resourceSid = (payload.resource_sid); + this.resourceType = (payload.resource_type); + this.resourceUrl = (payload.resource_url); + this.sid = (payload.sid); + this.source = (payload.source); + this.sourceIpAddress = (payload.source_ip_address); + this.url = (payload.url); + this.workspaceSid = (payload.workspace_sid); + + this._solution = { workspaceSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Event resource. + */ + accountSid: string; + /** + * The SID of the resource that triggered the event. + */ + actorSid: string; + /** + * The type of resource that triggered the event. + */ + actorType: string; + /** + * The absolute URL of the resource that triggered the event. + */ + actorUrl: string; + /** + * A description of the event. + */ + description: string; + /** + * Data about the event. For more information, see [Event types](https://www.twilio.com/docs/taskrouter/api/event#event-types). + */ + eventData: any; + /** + * The time the event was sent, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + eventDate: Date; + /** + * The time the event was sent in milliseconds. + */ + eventDateMs: number; + /** + * The identifier for the event. + */ + eventType: string; + /** + * The SID of the object the event is most relevant to, such as a TaskSid, ReservationSid, or a WorkerSid. + */ + resourceSid: string; + /** + * The type of object the event is most relevant to, such as a Task, Reservation, or a Worker). + */ + resourceType: string; + /** + * The URL of the resource the event is most relevant to. + */ + resourceUrl: string; + /** + * The unique string that we created to identify the Event resource. + */ + sid: string; + /** + * Where the Event originated. + */ + source: string; + /** + * The IP from which the Event originated. + */ + sourceIpAddress: string; + /** + * The absolute URL of the Event resource. + */ + url: string; + /** + * The SID of the Workspace that contains the Event. + */ + workspaceSid: string; + + private get _proxy(): EventContext { + this._context = this._context || new EventContextImpl(this._version, this._solution.workspaceSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a EventInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventInstance + */ + fetch(callback?: (error: Error | null, item?: EventInstance) => any): Promise<EventInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EventInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EventInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EventInstance>) => any): Promise<ApiResponse<EventInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + actorSid: this.actorSid, + actorType: this.actorType, + actorUrl: this.actorUrl, + description: this.description, + eventData: this.eventData, + eventDate: this.eventDate, + eventDateMs: this.eventDateMs, + eventType: this.eventType, + resourceSid: this.resourceSid, + resourceType: this.resourceType, + resourceUrl: this.resourceUrl, + sid: this.sid, + source: this.source, + sourceIpAddress: this.sourceIpAddress, + url: this.url, + workspaceSid: this.workspaceSid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EventSolution { + workspaceSid: string; +} + +export interface EventListInstance { + _version: V1; + _solution: EventSolution; + _uri: string; + + (sid: string, ): EventContext; + get(sid: string, ): EventContext; + + + + + + /** + * Streams EventInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + each(params: EventListInstanceEachOptions, callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EventInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EventListInstanceEachOptions, callback?: (item: EventInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EventInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EventPage) => any): Promise<EventPage>; + /** + * Retrieve a single target page of EventInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EventPage>) => any): Promise<ApiResponse<EventPage>>; + /** + * Lists EventInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EventInstance[]) => any): Promise<EventInstance[]>; + list(params: EventListInstanceOptions, callback?: (error: Error | null, items: EventInstance[]) => any): Promise<EventInstance[]>; + /** + * Lists EventInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EventInstance[]>) => any): Promise<ApiResponse<EventInstance[]>>; + listWithHttpInfo(params: EventListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EventInstance[]>) => any): Promise<ApiResponse<EventInstance[]>>; + /** + * Retrieve a single page of EventInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EventPage) => any): Promise<EventPage>; + page(params: EventListInstancePageOptions, callback?: (error: Error | null, items: EventPage) => any): Promise<EventPage>; + /** + * Retrieve a single page of EventInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EventListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EventPage>) => any): Promise<ApiResponse<EventPage>>; + pageWithHttpInfo(params: EventListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EventPage>) => any): Promise<ApiResponse<EventPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EventListInstance(version: V1, workspaceSid: string): EventListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as EventListInstance; + + instance.get = function get(sid, ): EventContext { + return new EventContextImpl(version, workspaceSid, sid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = `/Workspaces/${workspaceSid}/Events`; + + instance.page = function page(params?: EventListInstancePageOptions | ((error: Error | null, items: EventPage) => any), callback?: (error: Error | null, items: EventPage) => any): Promise<EventPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["eventType"] !== undefined) + data["EventType"] = params["eventType"]; + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["reservationSid"] !== undefined) + data["ReservationSid"] = params["reservationSid"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskQueueSid"] !== undefined) + data["TaskQueueSid"] = params["taskQueueSid"]; + if (params["taskSid"] !== undefined) + data["TaskSid"] = params["taskSid"]; + if (params["workerSid"] !== undefined) + data["WorkerSid"] = params["workerSid"]; + if (params["workflowSid"] !== undefined) + data["WorkflowSid"] = params["workflowSid"]; + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["sid"] !== undefined) + data["Sid"] = params["sid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EventPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EventPage) => any): Promise<EventPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EventPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EventListInstancePageOptions | ((error: Error | null, items: ApiResponse<EventPage>) => any), callback?: (error: Error | null, items: ApiResponse<EventPage>) => any): Promise<ApiResponse<EventPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["eventType"] !== undefined) + data["EventType"] = params["eventType"]; + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["reservationSid"] !== undefined) + data["ReservationSid"] = params["reservationSid"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskQueueSid"] !== undefined) + data["TaskQueueSid"] = params["taskQueueSid"]; + if (params["taskSid"] !== undefined) + data["TaskSid"] = params["taskSid"]; + if (params["workerSid"] !== undefined) + data["WorkerSid"] = params["workerSid"]; + if (params["workflowSid"] !== undefined) + data["WorkflowSid"] = params["workflowSid"]; + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["sid"] !== undefined) + data["Sid"] = params["sid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EventPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EventPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EventPage>) => any): Promise<ApiResponse<EventPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EventPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EventPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EventPage extends Page<V1, EventPayload, EventResource, EventInstance> { +/** +* Initialize the EventPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: EventSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EventInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EventResource): EventInstance { + + return new EventInstance( + this._version, + payload, + this._solution.workspaceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/task.ts b/rest/taskrouter/v1/workspace/task.ts new file mode 100644 index 000000000..c1941301d --- /dev/null +++ b/rest/taskrouter/v1/workspace/task.ts @@ -0,0 +1,1314 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { ReservationListInstance } from "./task/reservation"; + + +/** + * The current status of the Task\'s assignment. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. + */ +export type TaskStatus = 'pending'|'reserved'|'assigned'|'canceled'|'completed'|'wrapping'; + + +/** + * Options to pass to remove a TaskInstance + */ +export interface TaskContextRemoveOptions { + /** If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). */ + "ifMatch"?: string; +} + + +/** + * Options to pass to update a TaskInstance + */ +export interface TaskContextUpdateOptions { + /** If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). */ + "ifMatch"?: string; + /** The JSON string that describes the custom attributes of the task. */ + "attributes"?: string; + /** */ + "assignmentStatus"?: TaskStatus; + /** The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. */ + "reason"?: string; + /** The Task\\\'s new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). */ + "priority"?: number; + /** When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel\\\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; + /** The task\\\'s new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can\\\'t be in the future or before the year of 1900. */ + "virtualStartTime"?: Date; +} + +/** + * Options to pass to create a TaskInstance + */ +export interface TaskListInstanceCreateOptions { + /** The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. */ + "timeout"?: number; + /** The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). */ + "priority"?: number; + /** When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. */ + "taskChannel"?: string; + /** The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. */ + "workflowSid"?: string; + /** A JSON string with the attributes of the new task. This value is passed to the Workflow\\\'s `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. */ + "attributes"?: string; + /** The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can\\\'t be in the future or before the year of 1900. */ + "virtualStartTime"?: Date; + /** A SID of a Worker, Queue, or Workflow to route a Task to */ + "routingTarget"?: string; + /** A boolean that indicates if the Task should respect a Worker\\\'s capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker\\\'s capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. */ + "ignoreCapacity"?: string; + /** The SID of the TaskQueue in which the Task belongs */ + "taskQueueSid"?: string; +} + +/** + * Options to pass to each + */ +export interface TaskListInstanceEachOptions { + /** The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. */ + "priority"?: number; + /** The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. */ + "assignmentStatus"?: Array<string>; + /** The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. */ + "workflowSid"?: string; + /** The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. */ + "workflowName"?: string; + /** The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. */ + "taskQueueSid"?: string; + /** The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. */ + "taskQueueName"?: string; + /** The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. */ + "evaluateTaskAttributes"?: string; + /** A SID of a Worker, Queue, or Workflow to route a Task to */ + "routingTarget"?: string; + /** How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. */ + "ordering"?: string; + /** Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. */ + "hasAddons"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TaskInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TaskListInstanceOptions { + /** The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. */ + "priority"?: number; + /** The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. */ + "assignmentStatus"?: Array<string>; + /** The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. */ + "workflowSid"?: string; + /** The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. */ + "workflowName"?: string; + /** The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. */ + "taskQueueSid"?: string; + /** The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. */ + "taskQueueName"?: string; + /** The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. */ + "evaluateTaskAttributes"?: string; + /** A SID of a Worker, Queue, or Workflow to route a Task to */ + "routingTarget"?: string; + /** How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. */ + "ordering"?: string; + /** Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. */ + "hasAddons"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TaskListInstancePageOptions { + /** The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. */ + "priority"?: number; + /** The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. */ + "assignmentStatus"?: Array<string>; + /** The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. */ + "workflowSid"?: string; + /** The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. */ + "workflowName"?: string; + /** The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. */ + "taskQueueSid"?: string; + /** The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. */ + "taskQueueName"?: string; + /** The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. */ + "evaluateTaskAttributes"?: string; + /** A SID of a Worker, Queue, or Workflow to route a Task to */ + "routingTarget"?: string; + /** How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. */ + "ordering"?: string; + /** Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. */ + "hasAddons"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TaskContext { + reservations: ReservationListInstance; + + /** + * Remove a TaskInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + /** + * Remove a TaskInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance + */ + remove(params: TaskContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + + /** + * Remove a TaskInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + /** + * Remove a TaskInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance with HTTP metadata + */ + removeWithHttpInfo(params: TaskContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + + /** + * Fetch a TaskInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance + */ + fetch(callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance> + + /** + * Fetch a TaskInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>> + + /** + * Update a TaskInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance + */ + update(callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance>; + /** + * Update a TaskInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance + */ + update(params: TaskContextUpdateOptions, callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance>; + + /** + * Update a TaskInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>>; + /** + * Update a TaskInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance with HTTP metadata + */ + updateWithHttpInfo(params: TaskContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TaskContextSolution { + "workspaceSid": string; + "sid": string; +} + +export class TaskContextImpl implements TaskContext { + protected _solution: TaskContextSolution; + protected _uri: string; + + protected _reservations?: ReservationListInstance; + + constructor(protected _version: V1, workspaceSid: string, sid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { workspaceSid, sid, }; + this._uri = `/Workspaces/${workspaceSid}/Tasks/${sid}`; + } + + get reservations(): ReservationListInstance { + this._reservations = this._reservations || ReservationListInstance(this._version, this._solution.workspaceSid, this._solution.sid); + return this._reservations; + } + + remove(params?: TaskContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: TaskContextRemoveOptions | ((error: Error | null, item?: ApiResponse<boolean>) => any),callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TaskInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TaskResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TaskInstance> => ({ + ...response, + body: new TaskInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: TaskContextUpdateOptions | ((error: Error | null, item?: TaskInstance) => any),callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["assignmentStatus"] !== undefined) + data["AssignmentStatus"] = params["assignmentStatus"]; + if (params["reason"] !== undefined) + data["Reason"] = params["reason"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["virtualStartTime"] !== undefined) + data["VirtualStartTime"] = serialize.iso8601DateTime(params["virtualStartTime"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TaskInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: TaskContextUpdateOptions | ((error: Error | null, item?: ApiResponse<TaskInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["assignmentStatus"] !== undefined) + data["AssignmentStatus"] = params["assignmentStatus"]; + if (params["reason"] !== undefined) + data["Reason"] = params["reason"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["virtualStartTime"] !== undefined) + data["VirtualStartTime"] = serialize.iso8601DateTime(params["virtualStartTime"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<TaskResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TaskInstance> => ({ + ...response, + body: new TaskInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TaskPayload extends TwilioResponsePayload { + tasks: TaskResource[]; +} + +interface TaskResource { + account_sid: string; + age: number; + assignment_status: TaskStatus; + attributes: string; + addons: string; + date_created: Date; + date_updated: Date; + task_queue_entered_date: Date; + priority: number; + reason: string; + sid: string; + task_queue_sid: string; + task_queue_friendly_name: string; + task_channel_sid: string; + task_channel_unique_name: string; + timeout: number; + workflow_sid: string; + workflow_friendly_name: string; + workspace_sid: string; + url: string; + links: Record<string, string>; + virtual_start_time: Date; + ignore_capacity: boolean; + routing_target: string; +} + +export class TaskInstance { + protected _solution: TaskContextSolution; + protected _context?: TaskContext; + + constructor(protected _version: V1, payload: TaskResource, workspaceSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.age = deserialize.integer(payload.age); + this.assignmentStatus = payload.assignment_status; + this.attributes = (payload.attributes); + this.addons = (payload.addons); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.taskQueueEnteredDate = deserialize.iso8601DateTime(payload.task_queue_entered_date); + this.priority = deserialize.integer(payload.priority); + this.reason = (payload.reason); + this.sid = (payload.sid); + this.taskQueueSid = (payload.task_queue_sid); + this.taskQueueFriendlyName = (payload.task_queue_friendly_name); + this.taskChannelSid = (payload.task_channel_sid); + this.taskChannelUniqueName = (payload.task_channel_unique_name); + this.timeout = deserialize.integer(payload.timeout); + this.workflowSid = (payload.workflow_sid); + this.workflowFriendlyName = (payload.workflow_friendly_name); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + this.links = (payload.links); + this.virtualStartTime = deserialize.iso8601DateTime(payload.virtual_start_time); + this.ignoreCapacity = (payload.ignore_capacity); + this.routingTarget = (payload.routing_target); + + this._solution = { workspaceSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Task resource. + */ + accountSid: string; + /** + * The number of seconds since the Task was created. + */ + age: number; + assignmentStatus: TaskStatus; + /** + * The JSON string with custom attributes of the work. **Note** If this property has been assigned a value, it will only be displayed in FETCH action that returns a single resource. Otherwise, it will be null. + */ + attributes: string; + /** + * An object that contains the [Add-on](https://www.twilio.com/docs/add-ons) data for all installed Add-ons. + */ + addons: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The date and time in GMT when the Task entered the TaskQueue, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + taskQueueEnteredDate: Date; + /** + * The current priority score of the Task as assigned to a Worker by the workflow. Tasks with higher priority values will be assigned before Tasks with lower values. + */ + priority: number; + /** + * The reason the Task was canceled or completed, if applicable. + */ + reason: string; + /** + * The unique string that we created to identify the Task resource. + */ + sid: string; + /** + * The SID of the TaskQueue. + */ + taskQueueSid: string; + /** + * The friendly name of the TaskQueue. + */ + taskQueueFriendlyName: string; + /** + * The SID of the TaskChannel. + */ + taskChannelSid: string; + /** + * The unique name of the TaskChannel. + */ + taskChannelUniqueName: string; + /** + * The amount of time in seconds that the Task can live before being assigned. + */ + timeout: number; + /** + * The SID of the Workflow that is controlling the Task. + */ + workflowSid: string; + /** + * The friendly name of the Workflow that is controlling the Task. + */ + workflowFriendlyName: string; + /** + * The SID of the Workspace that contains the Task. + */ + workspaceSid: string; + /** + * The absolute URL of the Task resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + /** + * The date and time in GMT indicating the ordering for routing of the Task specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + virtualStartTime: Date; + /** + * A boolean that indicates if the Task should respect a Worker\'s capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker\'s capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + */ + ignoreCapacity: boolean; + /** + * A SID of a Worker, Queue, or Workflow to route a Task to + */ + routingTarget: string; + + private get _proxy(): TaskContext { + this._context = this._context || new TaskContextImpl(this._version, this._solution.workspaceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a TaskInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + /** + * Remove a TaskInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance + */ + remove(params: TaskContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a TaskInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + /** + * Remove a TaskInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance with HTTP metadata + */ + removeWithHttpInfo(params: TaskContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a TaskInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance + */ + fetch(callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TaskInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TaskInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance + */ + update(callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance>; + /** + * Update a TaskInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance + */ + update(params: TaskContextUpdateOptions, callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance>; + + update(params?: any, callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a TaskInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>>; + /** + * Update a TaskInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance with HTTP metadata + */ + updateWithHttpInfo(params: TaskContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the reservations. + */ + reservations(): ReservationListInstance { + return this._proxy.reservations; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + age: this.age, + assignmentStatus: this.assignmentStatus, + attributes: this.attributes, + addons: this.addons, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + taskQueueEnteredDate: this.taskQueueEnteredDate, + priority: this.priority, + reason: this.reason, + sid: this.sid, + taskQueueSid: this.taskQueueSid, + taskQueueFriendlyName: this.taskQueueFriendlyName, + taskChannelSid: this.taskChannelSid, + taskChannelUniqueName: this.taskChannelUniqueName, + timeout: this.timeout, + workflowSid: this.workflowSid, + workflowFriendlyName: this.workflowFriendlyName, + workspaceSid: this.workspaceSid, + url: this.url, + links: this.links, + virtualStartTime: this.virtualStartTime, + ignoreCapacity: this.ignoreCapacity, + routingTarget: this.routingTarget, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TaskSolution { + workspaceSid: string; +} + +export interface TaskListInstance { + _version: V1; + _solution: TaskSolution; + _uri: string; + + (sid: string, ): TaskContext; + get(sid: string, ): TaskContext; + + + + + + + + + /** + * Create a TaskInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance + */ + create(callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance>; + /** + * Create a TaskInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance + */ + create(params: TaskListInstanceCreateOptions, callback?: (error: Error | null, item?: TaskInstance) => any): Promise<TaskInstance>; + + /** + * Create a TaskInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>>; + /** + * Create a TaskInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskInstance with HTTP metadata + */ + createWithHttpInfo(params: TaskListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>>; + + + + + /** + * Streams TaskInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TaskInstance, done: (err?: Error) => void) => void): void; + each(params: TaskListInstanceEachOptions, callback?: (item: TaskInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TaskInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TaskInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TaskListInstanceEachOptions, callback?: (item: TaskInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TaskInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TaskPage) => any): Promise<TaskPage>; + /** + * Retrieve a single target page of TaskInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TaskPage>) => any): Promise<ApiResponse<TaskPage>>; + /** + * Lists TaskInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TaskInstance[]) => any): Promise<TaskInstance[]>; + list(params: TaskListInstanceOptions, callback?: (error: Error | null, items: TaskInstance[]) => any): Promise<TaskInstance[]>; + /** + * Lists TaskInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TaskInstance[]>) => any): Promise<ApiResponse<TaskInstance[]>>; + listWithHttpInfo(params: TaskListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TaskInstance[]>) => any): Promise<ApiResponse<TaskInstance[]>>; + /** + * Retrieve a single page of TaskInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TaskPage) => any): Promise<TaskPage>; + page(params: TaskListInstancePageOptions, callback?: (error: Error | null, items: TaskPage) => any): Promise<TaskPage>; + /** + * Retrieve a single page of TaskInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TaskPage>) => any): Promise<ApiResponse<TaskPage>>; + pageWithHttpInfo(params: TaskListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TaskPage>) => any): Promise<ApiResponse<TaskPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TaskListInstance(version: V1, workspaceSid: string): TaskListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as TaskListInstance; + + instance.get = function get(sid, ): TaskContext { + return new TaskContextImpl(version, workspaceSid, sid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = `/Workspaces/${workspaceSid}/Tasks`; + + instance.create = function create(params?: TaskListInstanceCreateOptions | ((error: Error | null, items: TaskInstance) => any), callback?: (error: Error | null, items: TaskInstance) => any): Promise<TaskInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["workflowSid"] !== undefined) + data["WorkflowSid"] = params["workflowSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["virtualStartTime"] !== undefined) + data["VirtualStartTime"] = serialize.iso8601DateTime(params["virtualStartTime"]); + if (params["routingTarget"] !== undefined) + data["RoutingTarget"] = params["routingTarget"]; + if (params["ignoreCapacity"] !== undefined) + data["IgnoreCapacity"] = params["ignoreCapacity"]; + if (params["taskQueueSid"] !== undefined) + data["TaskQueueSid"] = params["taskQueueSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TaskInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: TaskListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<TaskInstance>) => any), callback?: (error: Error | null, items: ApiResponse<TaskInstance>) => any): Promise<ApiResponse<TaskInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["workflowSid"] !== undefined) + data["WorkflowSid"] = params["workflowSid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["virtualStartTime"] !== undefined) + data["VirtualStartTime"] = serialize.iso8601DateTime(params["virtualStartTime"]); + if (params["routingTarget"] !== undefined) + data["RoutingTarget"] = params["routingTarget"]; + if (params["ignoreCapacity"] !== undefined) + data["IgnoreCapacity"] = params["ignoreCapacity"]; + if (params["taskQueueSid"] !== undefined) + data["TaskQueueSid"] = params["taskQueueSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TaskResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TaskInstance> => ({ + ...response, + body: new TaskInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TaskListInstancePageOptions | ((error: Error | null, items: TaskPage) => any), callback?: (error: Error | null, items: TaskPage) => any): Promise<TaskPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["assignmentStatus"] !== undefined) + data["AssignmentStatus"] = serialize.map(params["assignmentStatus"], (e: string) => (e)); + if (params["workflowSid"] !== undefined) + data["WorkflowSid"] = params["workflowSid"]; + if (params["workflowName"] !== undefined) + data["WorkflowName"] = params["workflowName"]; + if (params["taskQueueSid"] !== undefined) + data["TaskQueueSid"] = params["taskQueueSid"]; + if (params["taskQueueName"] !== undefined) + data["TaskQueueName"] = params["taskQueueName"]; + if (params["evaluateTaskAttributes"] !== undefined) + data["EvaluateTaskAttributes"] = params["evaluateTaskAttributes"]; + if (params["routingTarget"] !== undefined) + data["RoutingTarget"] = params["routingTarget"]; + if (params["ordering"] !== undefined) + data["Ordering"] = params["ordering"]; + if (params["hasAddons"] !== undefined) + data["HasAddons"] = serialize.bool(params["hasAddons"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TaskPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TaskPage) => any): Promise<TaskPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TaskPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TaskListInstancePageOptions | ((error: Error | null, items: ApiResponse<TaskPage>) => any), callback?: (error: Error | null, items: ApiResponse<TaskPage>) => any): Promise<ApiResponse<TaskPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["assignmentStatus"] !== undefined) + data["AssignmentStatus"] = serialize.map(params["assignmentStatus"], (e: string) => (e)); + if (params["workflowSid"] !== undefined) + data["WorkflowSid"] = params["workflowSid"]; + if (params["workflowName"] !== undefined) + data["WorkflowName"] = params["workflowName"]; + if (params["taskQueueSid"] !== undefined) + data["TaskQueueSid"] = params["taskQueueSid"]; + if (params["taskQueueName"] !== undefined) + data["TaskQueueName"] = params["taskQueueName"]; + if (params["evaluateTaskAttributes"] !== undefined) + data["EvaluateTaskAttributes"] = params["evaluateTaskAttributes"]; + if (params["routingTarget"] !== undefined) + data["RoutingTarget"] = params["routingTarget"]; + if (params["ordering"] !== undefined) + data["Ordering"] = params["ordering"]; + if (params["hasAddons"] !== undefined) + data["HasAddons"] = serialize.bool(params["hasAddons"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TaskPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TaskPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TaskPage>) => any): Promise<ApiResponse<TaskPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TaskPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TaskPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TaskPage extends Page<V1, TaskPayload, TaskResource, TaskInstance> { +/** +* Initialize the TaskPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TaskSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TaskInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TaskResource): TaskInstance { + + return new TaskInstance( + this._version, + payload, + this._solution.workspaceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/task/reservation.ts b/rest/taskrouter/v1/workspace/task/reservation.ts new file mode 100644 index 000000000..ba4110dc5 --- /dev/null +++ b/rest/taskrouter/v1/workspace/task/reservation.ts @@ -0,0 +1,1119 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type ReservationCallStatus = 'initiated'|'ringing'|'answered'|'completed'; + +export type ReservationConferenceEvent = 'start'|'end'|'join'|'leave'|'mute'|'hold'|'speaker'; + +/** + * The current status of the reservation. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + */ +export type ReservationStatus = 'pending'|'accepted'|'rejected'|'timeout'|'canceled'|'rescinded'|'wrapping'|'completed'; + +export type ReservationSupervisorMode = 'monitor'|'whisper'|'barge'; + + + +/** + * Options to pass to update a ReservationInstance + */ +export interface ReservationContextUpdateOptions { + /** The If-Match HTTP request header */ + "ifMatch"?: string; + /** */ + "reservationStatus"?: ReservationStatus; + /** The new worker activity SID if rejecting a reservation. */ + "workerActivitySid"?: string; + /** The assignment instruction for reservation. */ + "instruction"?: string; + /** The SID of the Activity resource to start after executing a Dequeue instruction. */ + "dequeuePostWorkActivitySid"?: string; + /** The Caller ID of the call to the worker when executing a Dequeue instruction. */ + "dequeueFrom"?: string; + /** Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. */ + "dequeueRecord"?: string; + /** Timeout for call when executing a Dequeue instruction. */ + "dequeueTimeout"?: number; + /** The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. */ + "dequeueTo"?: string; + /** The Callback URL for completed call event when executing a Dequeue instruction. */ + "dequeueStatusCallbackUrl"?: string; + /** The Caller ID of the outbound call when executing a Call instruction. */ + "callFrom"?: string; + /** Whether to record both legs of a call when executing a Call instruction or which leg to record. */ + "callRecord"?: string; + /** Timeout for call when executing a Call instruction. */ + "callTimeout"?: number; + /** The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. */ + "callTo"?: string; + /** TwiML URI executed on answering the worker\\\'s leg as a result of the Call instruction. */ + "callUrl"?: string; + /** The URL to call for the completed call event when executing a Call instruction. */ + "callStatusCallbackUrl"?: string; + /** Whether to accept a reservation when executing a Call instruction. */ + "callAccept"?: boolean; + /** The Call SID of the call parked in the queue when executing a Redirect instruction. */ + "redirectCallSid"?: string; + /** Whether the reservation should be accepted when executing a Redirect instruction. */ + "redirectAccept"?: boolean; + /** TwiML URI to redirect the call to when executing the Redirect instruction. */ + "redirectUrl"?: string; + /** The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. */ + "to"?: string; + /** The Caller ID of the call to the worker when executing a Conference instruction. */ + "from"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. */ + "statusCallbackMethod"?: string; + /** The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. */ + "statusCallbackEvent"?: Array<ReservationCallStatus>; + /** Timeout for call when executing a Conference instruction. */ + "timeout"?: number; + /** Whether to record the participant and their conferences, including the time between conferences. The default is `false`. */ + "record"?: boolean; + /** Whether the agent is muted in the conference. The default is `false`. */ + "muted"?: boolean; + /** Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. */ + "beep"?: string; + /** Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. */ + "startConferenceOnEnter"?: boolean; + /** Whether to end the conference when the agent leaves. */ + "endConferenceOnExit"?: boolean; + /** The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). */ + "waitUrl"?: string; + /** The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. */ + "waitMethod"?: string; + /** Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. */ + "earlyMedia"?: boolean; + /** The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. */ + "maxParticipants"?: number; + /** The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. */ + "conferenceStatusCallback"?: string; + /** The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "conferenceStatusCallbackMethod"?: string; + /** The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. */ + "conferenceStatusCallbackEvent"?: Array<ReservationConferenceEvent>; + /** Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. */ + "conferenceRecord"?: string; + /** How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. */ + "conferenceTrim"?: string; + /** The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. */ + "recordingChannels"?: string; + /** The URL that we should call using the `recording_status_callback_method` when the recording status changes. */ + "recordingStatusCallback"?: string; + /** The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "recordingStatusCallbackMethod"?: string; + /** The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. */ + "conferenceRecordingStatusCallback"?: string; + /** The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "conferenceRecordingStatusCallbackMethod"?: string; + /** The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. */ + "region"?: string; + /** The SIP username used for authentication. */ + "sipAuthUsername"?: string; + /** The SIP password for authentication. */ + "sipAuthPassword"?: string; + /** The Call progress events sent via webhooks as a result of a Dequeue instruction. */ + "dequeueStatusCallbackEvent"?: Array<string>; + /** The new worker activity SID after executing a Conference instruction. */ + "postWorkActivitySid"?: string; + /** */ + "supervisorMode"?: ReservationSupervisorMode; + /** The Supervisor SID/URI when executing the Supervise instruction. */ + "supervisor"?: string; + /** Whether to end the conference when the customer leaves. */ + "endConferenceOnCustomerExit"?: boolean; + /** Whether to play a notification beep when the customer joins. */ + "beepOnCustomerEntrance"?: boolean; + /** The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. */ + "jitterBufferSize"?: string; +} + +/** + * Options to pass to each + */ +export interface ReservationListInstanceEachOptions { + /** Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. */ + "reservationStatus"?: ReservationStatus; + /** The SID of the reserved Worker resource to read. */ + "workerSid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ReservationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ReservationListInstanceOptions { + /** Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. */ + "reservationStatus"?: ReservationStatus; + /** The SID of the reserved Worker resource to read. */ + "workerSid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ReservationListInstancePageOptions { + /** Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. */ + "reservationStatus"?: ReservationStatus; + /** The SID of the reserved Worker resource to read. */ + "workerSid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ReservationContext { + + /** + * Fetch a ReservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + fetch(callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance> + + /** + * Fetch a ReservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>> + + /** + * Update a ReservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + update(callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance>; + /** + * Update a ReservationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + update(params: ReservationContextUpdateOptions, callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance>; + + /** + * Update a ReservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>>; + /** + * Update a ReservationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ReservationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ReservationContextSolution { + "workspaceSid": string; + "taskSid": string; + "sid": string; +} + +export class ReservationContextImpl implements ReservationContext { + protected _solution: ReservationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, taskSid: string, sid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(taskSid)) { + throw new Error('Parameter \'taskSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { workspaceSid, taskSid, sid, }; + this._uri = `/Workspaces/${workspaceSid}/Tasks/${taskSid}/Reservations/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ReservationInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.taskSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ReservationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ReservationInstance> => ({ + ...response, + body: new ReservationInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.taskSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ReservationContextUpdateOptions | ((error: Error | null, item?: ReservationInstance) => any),callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["reservationStatus"] !== undefined) + data["ReservationStatus"] = params["reservationStatus"]; + if (params["workerActivitySid"] !== undefined) + data["WorkerActivitySid"] = params["workerActivitySid"]; + if (params["instruction"] !== undefined) + data["Instruction"] = params["instruction"]; + if (params["dequeuePostWorkActivitySid"] !== undefined) + data["DequeuePostWorkActivitySid"] = params["dequeuePostWorkActivitySid"]; + if (params["dequeueFrom"] !== undefined) + data["DequeueFrom"] = params["dequeueFrom"]; + if (params["dequeueRecord"] !== undefined) + data["DequeueRecord"] = params["dequeueRecord"]; + if (params["dequeueTimeout"] !== undefined) + data["DequeueTimeout"] = params["dequeueTimeout"]; + if (params["dequeueTo"] !== undefined) + data["DequeueTo"] = params["dequeueTo"]; + if (params["dequeueStatusCallbackUrl"] !== undefined) + data["DequeueStatusCallbackUrl"] = params["dequeueStatusCallbackUrl"]; + if (params["callFrom"] !== undefined) + data["CallFrom"] = params["callFrom"]; + if (params["callRecord"] !== undefined) + data["CallRecord"] = params["callRecord"]; + if (params["callTimeout"] !== undefined) + data["CallTimeout"] = params["callTimeout"]; + if (params["callTo"] !== undefined) + data["CallTo"] = params["callTo"]; + if (params["callUrl"] !== undefined) + data["CallUrl"] = params["callUrl"]; + if (params["callStatusCallbackUrl"] !== undefined) + data["CallStatusCallbackUrl"] = params["callStatusCallbackUrl"]; + if (params["callAccept"] !== undefined) + data["CallAccept"] = serialize.bool(params["callAccept"]); + if (params["redirectCallSid"] !== undefined) + data["RedirectCallSid"] = params["redirectCallSid"]; + if (params["redirectAccept"] !== undefined) + data["RedirectAccept"] = serialize.bool(params["redirectAccept"]); + if (params["redirectUrl"] !== undefined) + data["RedirectUrl"] = params["redirectUrl"]; + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["statusCallbackEvent"] !== undefined) + data["StatusCallbackEvent"] = serialize.map(params["statusCallbackEvent"], (e: ReservationCallStatus) => (e)); + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["record"] !== undefined) + data["Record"] = serialize.bool(params["record"]); + if (params["muted"] !== undefined) + data["Muted"] = serialize.bool(params["muted"]); + if (params["beep"] !== undefined) + data["Beep"] = params["beep"]; + if (params["startConferenceOnEnter"] !== undefined) + data["StartConferenceOnEnter"] = serialize.bool(params["startConferenceOnEnter"]); + if (params["endConferenceOnExit"] !== undefined) + data["EndConferenceOnExit"] = serialize.bool(params["endConferenceOnExit"]); + if (params["waitUrl"] !== undefined) + data["WaitUrl"] = params["waitUrl"]; + if (params["waitMethod"] !== undefined) + data["WaitMethod"] = params["waitMethod"]; + if (params["earlyMedia"] !== undefined) + data["EarlyMedia"] = serialize.bool(params["earlyMedia"]); + if (params["maxParticipants"] !== undefined) + data["MaxParticipants"] = params["maxParticipants"]; + if (params["conferenceStatusCallback"] !== undefined) + data["ConferenceStatusCallback"] = params["conferenceStatusCallback"]; + if (params["conferenceStatusCallbackMethod"] !== undefined) + data["ConferenceStatusCallbackMethod"] = params["conferenceStatusCallbackMethod"]; + if (params["conferenceStatusCallbackEvent"] !== undefined) + data["ConferenceStatusCallbackEvent"] = serialize.map(params["conferenceStatusCallbackEvent"], (e: ReservationConferenceEvent) => (e)); + if (params["conferenceRecord"] !== undefined) + data["ConferenceRecord"] = params["conferenceRecord"]; + if (params["conferenceTrim"] !== undefined) + data["ConferenceTrim"] = params["conferenceTrim"]; + if (params["recordingChannels"] !== undefined) + data["RecordingChannels"] = params["recordingChannels"]; + if (params["recordingStatusCallback"] !== undefined) + data["RecordingStatusCallback"] = params["recordingStatusCallback"]; + if (params["recordingStatusCallbackMethod"] !== undefined) + data["RecordingStatusCallbackMethod"] = params["recordingStatusCallbackMethod"]; + if (params["conferenceRecordingStatusCallback"] !== undefined) + data["ConferenceRecordingStatusCallback"] = params["conferenceRecordingStatusCallback"]; + if (params["conferenceRecordingStatusCallbackMethod"] !== undefined) + data["ConferenceRecordingStatusCallbackMethod"] = params["conferenceRecordingStatusCallbackMethod"]; + if (params["region"] !== undefined) + data["Region"] = params["region"]; + if (params["sipAuthUsername"] !== undefined) + data["SipAuthUsername"] = params["sipAuthUsername"]; + if (params["sipAuthPassword"] !== undefined) + data["SipAuthPassword"] = params["sipAuthPassword"]; + if (params["dequeueStatusCallbackEvent"] !== undefined) + data["DequeueStatusCallbackEvent"] = serialize.map(params["dequeueStatusCallbackEvent"], (e: string) => (e)); + if (params["postWorkActivitySid"] !== undefined) + data["PostWorkActivitySid"] = params["postWorkActivitySid"]; + if (params["supervisorMode"] !== undefined) + data["SupervisorMode"] = params["supervisorMode"]; + if (params["supervisor"] !== undefined) + data["Supervisor"] = params["supervisor"]; + if (params["endConferenceOnCustomerExit"] !== undefined) + data["EndConferenceOnCustomerExit"] = serialize.bool(params["endConferenceOnCustomerExit"]); + if (params["beepOnCustomerEntrance"] !== undefined) + data["BeepOnCustomerEntrance"] = serialize.bool(params["beepOnCustomerEntrance"]); + if (params["jitterBufferSize"] !== undefined) + data["JitterBufferSize"] = params["jitterBufferSize"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ReservationInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.taskSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ReservationContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ReservationInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["reservationStatus"] !== undefined) + data["ReservationStatus"] = params["reservationStatus"]; + if (params["workerActivitySid"] !== undefined) + data["WorkerActivitySid"] = params["workerActivitySid"]; + if (params["instruction"] !== undefined) + data["Instruction"] = params["instruction"]; + if (params["dequeuePostWorkActivitySid"] !== undefined) + data["DequeuePostWorkActivitySid"] = params["dequeuePostWorkActivitySid"]; + if (params["dequeueFrom"] !== undefined) + data["DequeueFrom"] = params["dequeueFrom"]; + if (params["dequeueRecord"] !== undefined) + data["DequeueRecord"] = params["dequeueRecord"]; + if (params["dequeueTimeout"] !== undefined) + data["DequeueTimeout"] = params["dequeueTimeout"]; + if (params["dequeueTo"] !== undefined) + data["DequeueTo"] = params["dequeueTo"]; + if (params["dequeueStatusCallbackUrl"] !== undefined) + data["DequeueStatusCallbackUrl"] = params["dequeueStatusCallbackUrl"]; + if (params["callFrom"] !== undefined) + data["CallFrom"] = params["callFrom"]; + if (params["callRecord"] !== undefined) + data["CallRecord"] = params["callRecord"]; + if (params["callTimeout"] !== undefined) + data["CallTimeout"] = params["callTimeout"]; + if (params["callTo"] !== undefined) + data["CallTo"] = params["callTo"]; + if (params["callUrl"] !== undefined) + data["CallUrl"] = params["callUrl"]; + if (params["callStatusCallbackUrl"] !== undefined) + data["CallStatusCallbackUrl"] = params["callStatusCallbackUrl"]; + if (params["callAccept"] !== undefined) + data["CallAccept"] = serialize.bool(params["callAccept"]); + if (params["redirectCallSid"] !== undefined) + data["RedirectCallSid"] = params["redirectCallSid"]; + if (params["redirectAccept"] !== undefined) + data["RedirectAccept"] = serialize.bool(params["redirectAccept"]); + if (params["redirectUrl"] !== undefined) + data["RedirectUrl"] = params["redirectUrl"]; + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["statusCallbackEvent"] !== undefined) + data["StatusCallbackEvent"] = serialize.map(params["statusCallbackEvent"], (e: ReservationCallStatus) => (e)); + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["record"] !== undefined) + data["Record"] = serialize.bool(params["record"]); + if (params["muted"] !== undefined) + data["Muted"] = serialize.bool(params["muted"]); + if (params["beep"] !== undefined) + data["Beep"] = params["beep"]; + if (params["startConferenceOnEnter"] !== undefined) + data["StartConferenceOnEnter"] = serialize.bool(params["startConferenceOnEnter"]); + if (params["endConferenceOnExit"] !== undefined) + data["EndConferenceOnExit"] = serialize.bool(params["endConferenceOnExit"]); + if (params["waitUrl"] !== undefined) + data["WaitUrl"] = params["waitUrl"]; + if (params["waitMethod"] !== undefined) + data["WaitMethod"] = params["waitMethod"]; + if (params["earlyMedia"] !== undefined) + data["EarlyMedia"] = serialize.bool(params["earlyMedia"]); + if (params["maxParticipants"] !== undefined) + data["MaxParticipants"] = params["maxParticipants"]; + if (params["conferenceStatusCallback"] !== undefined) + data["ConferenceStatusCallback"] = params["conferenceStatusCallback"]; + if (params["conferenceStatusCallbackMethod"] !== undefined) + data["ConferenceStatusCallbackMethod"] = params["conferenceStatusCallbackMethod"]; + if (params["conferenceStatusCallbackEvent"] !== undefined) + data["ConferenceStatusCallbackEvent"] = serialize.map(params["conferenceStatusCallbackEvent"], (e: ReservationConferenceEvent) => (e)); + if (params["conferenceRecord"] !== undefined) + data["ConferenceRecord"] = params["conferenceRecord"]; + if (params["conferenceTrim"] !== undefined) + data["ConferenceTrim"] = params["conferenceTrim"]; + if (params["recordingChannels"] !== undefined) + data["RecordingChannels"] = params["recordingChannels"]; + if (params["recordingStatusCallback"] !== undefined) + data["RecordingStatusCallback"] = params["recordingStatusCallback"]; + if (params["recordingStatusCallbackMethod"] !== undefined) + data["RecordingStatusCallbackMethod"] = params["recordingStatusCallbackMethod"]; + if (params["conferenceRecordingStatusCallback"] !== undefined) + data["ConferenceRecordingStatusCallback"] = params["conferenceRecordingStatusCallback"]; + if (params["conferenceRecordingStatusCallbackMethod"] !== undefined) + data["ConferenceRecordingStatusCallbackMethod"] = params["conferenceRecordingStatusCallbackMethod"]; + if (params["region"] !== undefined) + data["Region"] = params["region"]; + if (params["sipAuthUsername"] !== undefined) + data["SipAuthUsername"] = params["sipAuthUsername"]; + if (params["sipAuthPassword"] !== undefined) + data["SipAuthPassword"] = params["sipAuthPassword"]; + if (params["dequeueStatusCallbackEvent"] !== undefined) + data["DequeueStatusCallbackEvent"] = serialize.map(params["dequeueStatusCallbackEvent"], (e: string) => (e)); + if (params["postWorkActivitySid"] !== undefined) + data["PostWorkActivitySid"] = params["postWorkActivitySid"]; + if (params["supervisorMode"] !== undefined) + data["SupervisorMode"] = params["supervisorMode"]; + if (params["supervisor"] !== undefined) + data["Supervisor"] = params["supervisor"]; + if (params["endConferenceOnCustomerExit"] !== undefined) + data["EndConferenceOnCustomerExit"] = serialize.bool(params["endConferenceOnCustomerExit"]); + if (params["beepOnCustomerEntrance"] !== undefined) + data["BeepOnCustomerEntrance"] = serialize.bool(params["beepOnCustomerEntrance"]); + if (params["jitterBufferSize"] !== undefined) + data["JitterBufferSize"] = params["jitterBufferSize"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ReservationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ReservationInstance> => ({ + ...response, + body: new ReservationInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.taskSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ReservationPayload extends TwilioResponsePayload { + reservations: ReservationResource[]; +} + +interface ReservationResource { + account_sid: string; + date_created: Date; + date_updated: Date; + reservation_status: ReservationStatus; + sid: string; + task_sid: string; + worker_name: string; + worker_sid: string; + workspace_sid: string; + url: string; + links: Record<string, string>; +} + +export class ReservationInstance { + protected _solution: ReservationContextSolution; + protected _context?: ReservationContext; + + constructor(protected _version: V1, payload: ReservationResource, workspaceSid: string, taskSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.reservationStatus = payload.reservation_status; + this.sid = (payload.sid); + this.taskSid = (payload.task_sid); + this.workerName = (payload.worker_name); + this.workerSid = (payload.worker_sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { workspaceSid, taskSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskReservation resource. + */ + accountSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + reservationStatus: ReservationStatus; + /** + * The unique string that we created to identify the TaskReservation resource. + */ + sid: string; + /** + * The SID of the reserved Task resource. + */ + taskSid: string; + /** + * The `friendly_name` of the Worker that is reserved. + */ + workerName: string; + /** + * The SID of the reserved Worker resource. + */ + workerSid: string; + /** + * The SID of the Workspace that this task is contained within. + */ + workspaceSid: string; + /** + * The absolute URL of the TaskReservation reservation. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): ReservationContext { + this._context = this._context || new ReservationContextImpl(this._version, this._solution.workspaceSid, this._solution.taskSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a ReservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + fetch(callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ReservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ReservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + update(callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance>; + /** + * Update a ReservationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + update(params: ReservationContextUpdateOptions, callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ReservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>>; + /** + * Update a ReservationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ReservationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + reservationStatus: this.reservationStatus, + sid: this.sid, + taskSid: this.taskSid, + workerName: this.workerName, + workerSid: this.workerSid, + workspaceSid: this.workspaceSid, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ReservationSolution { + workspaceSid: string; + taskSid: string; +} + +export interface ReservationListInstance { + _version: V1; + _solution: ReservationSolution; + _uri: string; + + (sid: string, ): ReservationContext; + get(sid: string, ): ReservationContext; + + + + + + + + /** + * Streams ReservationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ReservationInstance, done: (err?: Error) => void) => void): void; + each(params: ReservationListInstanceEachOptions, callback?: (item: ReservationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ReservationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ReservationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ReservationListInstanceEachOptions, callback?: (item: ReservationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ReservationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage>; + /** + * Retrieve a single target page of ReservationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ReservationPage>) => any): Promise<ApiResponse<ReservationPage>>; + /** + * Lists ReservationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ReservationInstance[]) => any): Promise<ReservationInstance[]>; + list(params: ReservationListInstanceOptions, callback?: (error: Error | null, items: ReservationInstance[]) => any): Promise<ReservationInstance[]>; + /** + * Lists ReservationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ReservationInstance[]>) => any): Promise<ApiResponse<ReservationInstance[]>>; + listWithHttpInfo(params: ReservationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ReservationInstance[]>) => any): Promise<ApiResponse<ReservationInstance[]>>; + /** + * Retrieve a single page of ReservationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage>; + page(params: ReservationListInstancePageOptions, callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage>; + /** + * Retrieve a single page of ReservationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ReservationPage>) => any): Promise<ApiResponse<ReservationPage>>; + pageWithHttpInfo(params: ReservationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ReservationPage>) => any): Promise<ApiResponse<ReservationPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ReservationListInstance(version: V1, workspaceSid: string, taskSid: string): ReservationListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(taskSid)) { + throw new Error('Parameter \'taskSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ReservationListInstance; + + instance.get = function get(sid, ): ReservationContext { + return new ReservationContextImpl(version, workspaceSid, taskSid, sid); + } + + instance._version = version; + instance._solution = { workspaceSid, taskSid, }; + instance._uri = `/Workspaces/${workspaceSid}/Tasks/${taskSid}/Reservations`; + + instance.page = function page(params?: ReservationListInstancePageOptions | ((error: Error | null, items: ReservationPage) => any), callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["reservationStatus"] !== undefined) + data["ReservationStatus"] = params["reservationStatus"]; + if (params["workerSid"] !== undefined) + data["WorkerSid"] = params["workerSid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ReservationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ReservationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ReservationListInstancePageOptions | ((error: Error | null, items: ApiResponse<ReservationPage>) => any), callback?: (error: Error | null, items: ApiResponse<ReservationPage>) => any): Promise<ApiResponse<ReservationPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["reservationStatus"] !== undefined) + data["ReservationStatus"] = params["reservationStatus"]; + if (params["workerSid"] !== undefined) + data["WorkerSid"] = params["workerSid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ReservationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ReservationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ReservationPage>) => any): Promise<ApiResponse<ReservationPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ReservationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ReservationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ReservationPage extends Page<V1, ReservationPayload, ReservationResource, ReservationInstance> { +/** +* Initialize the ReservationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ReservationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ReservationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ReservationResource): ReservationInstance { + + return new ReservationInstance( + this._version, + payload, + this._solution.workspaceSid, + this._solution.taskSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/taskChannel.ts b/rest/taskrouter/v1/workspace/taskChannel.ts new file mode 100644 index 000000000..fcb8880e6 --- /dev/null +++ b/rest/taskrouter/v1/workspace/taskChannel.ts @@ -0,0 +1,954 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a TaskChannelInstance + */ +export interface TaskChannelContextUpdateOptions { + /** A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. */ + "channelOptimizedRouting"?: boolean; +} + +/** + * Options to pass to create a TaskChannelInstance + */ +export interface TaskChannelListInstanceCreateOptions { + /** A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. */ + "friendlyName": string; + /** An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. */ + "uniqueName": string; + /** Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. */ + "channelOptimizedRouting"?: boolean; +} + +/** + * Options to pass to each + */ +export interface TaskChannelListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TaskChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TaskChannelListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TaskChannelListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TaskChannelContext { + + /** + * Remove a TaskChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a TaskChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a TaskChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance + */ + fetch(callback?: (error: Error | null, item?: TaskChannelInstance) => any): Promise<TaskChannelInstance> + + /** + * Fetch a TaskChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>> + + /** + * Update a TaskChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance + */ + update(callback?: (error: Error | null, item?: TaskChannelInstance) => any): Promise<TaskChannelInstance>; + /** + * Update a TaskChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance + */ + update(params: TaskChannelContextUpdateOptions, callback?: (error: Error | null, item?: TaskChannelInstance) => any): Promise<TaskChannelInstance>; + + /** + * Update a TaskChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>>; + /** + * Update a TaskChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: TaskChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TaskChannelContextSolution { + "workspaceSid": string; + "sid": string; +} + +export class TaskChannelContextImpl implements TaskChannelContext { + protected _solution: TaskChannelContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, sid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { workspaceSid, sid, }; + this._uri = `/Workspaces/${workspaceSid}/TaskChannels/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TaskChannelInstance) => any): Promise<TaskChannelInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TaskChannelInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TaskChannelResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TaskChannelInstance> => ({ + ...response, + body: new TaskChannelInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: TaskChannelContextUpdateOptions | ((error: Error | null, item?: TaskChannelInstance) => any),callback?: (error: Error | null, item?: TaskChannelInstance) => any): Promise<TaskChannelInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["channelOptimizedRouting"] !== undefined) + data["ChannelOptimizedRouting"] = serialize.bool(params["channelOptimizedRouting"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TaskChannelInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: TaskChannelContextUpdateOptions | ((error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["channelOptimizedRouting"] !== undefined) + data["ChannelOptimizedRouting"] = serialize.bool(params["channelOptimizedRouting"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<TaskChannelResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TaskChannelInstance> => ({ + ...response, + body: new TaskChannelInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TaskChannelPayload extends TwilioResponsePayload { + channels: TaskChannelResource[]; +} + +interface TaskChannelResource { + account_sid: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + sid: string; + unique_name: string; + workspace_sid: string; + channel_optimized_routing: boolean; + url: string; + links: Record<string, string>; +} + +export class TaskChannelInstance { + protected _solution: TaskChannelContextSolution; + protected _context?: TaskChannelContext; + + constructor(protected _version: V1, payload: TaskChannelResource, workspaceSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.workspaceSid = (payload.workspace_sid); + this.channelOptimizedRouting = (payload.channel_optimized_routing); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { workspaceSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Task Channel resource. + */ + accountSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The unique string that we created to identify the Task Channel resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + */ + uniqueName: string; + /** + * The SID of the Workspace that contains the Task Channel. + */ + workspaceSid: string; + /** + * Whether the Task Channel will prioritize Workers that have been idle. When `true`, Workers that have been idle the longest are prioritized. + */ + channelOptimizedRouting: boolean; + /** + * The absolute URL of the Task Channel resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): TaskChannelContext { + this._context = this._context || new TaskChannelContextImpl(this._version, this._solution.workspaceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a TaskChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TaskChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TaskChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance + */ + fetch(callback?: (error: Error | null, item?: TaskChannelInstance) => any): Promise<TaskChannelInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TaskChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TaskChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance + */ + update(callback?: (error: Error | null, item?: TaskChannelInstance) => any): Promise<TaskChannelInstance>; + /** + * Update a TaskChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance + */ + update(params: TaskChannelContextUpdateOptions, callback?: (error: Error | null, item?: TaskChannelInstance) => any): Promise<TaskChannelInstance>; + + update(params?: any, callback?: (error: Error | null, item?: TaskChannelInstance) => any): Promise<TaskChannelInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a TaskChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>>; + /** + * Update a TaskChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: TaskChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + sid: this.sid, + uniqueName: this.uniqueName, + workspaceSid: this.workspaceSid, + channelOptimizedRouting: this.channelOptimizedRouting, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TaskChannelSolution { + workspaceSid: string; +} + +export interface TaskChannelListInstance { + _version: V1; + _solution: TaskChannelSolution; + _uri: string; + + (sid: string, ): TaskChannelContext; + get(sid: string, ): TaskChannelContext; + + + + + + + + + /** + * Create a TaskChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance + */ + create(params: TaskChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: TaskChannelInstance) => any): Promise<TaskChannelInstance>; + + /** + * Create a TaskChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskChannelInstance with HTTP metadata + */ + createWithHttpInfo(params: TaskChannelListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>>; + + + + + /** + * Streams TaskChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TaskChannelInstance, done: (err?: Error) => void) => void): void; + each(params: TaskChannelListInstanceEachOptions, callback?: (item: TaskChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TaskChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TaskChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TaskChannelListInstanceEachOptions, callback?: (item: TaskChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TaskChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TaskChannelPage) => any): Promise<TaskChannelPage>; + /** + * Retrieve a single target page of TaskChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TaskChannelPage>) => any): Promise<ApiResponse<TaskChannelPage>>; + /** + * Lists TaskChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TaskChannelInstance[]) => any): Promise<TaskChannelInstance[]>; + list(params: TaskChannelListInstanceOptions, callback?: (error: Error | null, items: TaskChannelInstance[]) => any): Promise<TaskChannelInstance[]>; + /** + * Lists TaskChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TaskChannelInstance[]>) => any): Promise<ApiResponse<TaskChannelInstance[]>>; + listWithHttpInfo(params: TaskChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TaskChannelInstance[]>) => any): Promise<ApiResponse<TaskChannelInstance[]>>; + /** + * Retrieve a single page of TaskChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TaskChannelPage) => any): Promise<TaskChannelPage>; + page(params: TaskChannelListInstancePageOptions, callback?: (error: Error | null, items: TaskChannelPage) => any): Promise<TaskChannelPage>; + /** + * Retrieve a single page of TaskChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TaskChannelPage>) => any): Promise<ApiResponse<TaskChannelPage>>; + pageWithHttpInfo(params: TaskChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TaskChannelPage>) => any): Promise<ApiResponse<TaskChannelPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TaskChannelListInstance(version: V1, workspaceSid: string): TaskChannelListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as TaskChannelListInstance; + + instance.get = function get(sid, ): TaskChannelContext { + return new TaskChannelContextImpl(version, workspaceSid, sid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = `/Workspaces/${workspaceSid}/TaskChannels`; + + instance.create = function create(params: TaskChannelListInstanceCreateOptions, callback?: (error: Error | null, items: TaskChannelInstance) => any): Promise<TaskChannelInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["UniqueName"] = params["uniqueName"]; + if (params["channelOptimizedRouting"] !== undefined) + data["ChannelOptimizedRouting"] = serialize.bool(params["channelOptimizedRouting"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TaskChannelInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TaskChannelListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<TaskChannelInstance>) => any): Promise<ApiResponse<TaskChannelInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["UniqueName"] = params["uniqueName"]; + if (params["channelOptimizedRouting"] !== undefined) + data["ChannelOptimizedRouting"] = serialize.bool(params["channelOptimizedRouting"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TaskChannelResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TaskChannelInstance> => ({ + ...response, + body: new TaskChannelInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TaskChannelListInstancePageOptions | ((error: Error | null, items: TaskChannelPage) => any), callback?: (error: Error | null, items: TaskChannelPage) => any): Promise<TaskChannelPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TaskChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TaskChannelPage) => any): Promise<TaskChannelPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TaskChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TaskChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse<TaskChannelPage>) => any), callback?: (error: Error | null, items: ApiResponse<TaskChannelPage>) => any): Promise<ApiResponse<TaskChannelPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TaskChannelPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TaskChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TaskChannelPage>) => any): Promise<ApiResponse<TaskChannelPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TaskChannelPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TaskChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TaskChannelPage extends Page<V1, TaskChannelPayload, TaskChannelResource, TaskChannelInstance> { +/** +* Initialize the TaskChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TaskChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TaskChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TaskChannelResource): TaskChannelInstance { + + return new TaskChannelInstance( + this._version, + payload, + this._solution.workspaceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/taskQueue.ts b/rest/taskrouter/v1/workspace/taskQueue.ts new file mode 100644 index 000000000..db21008e6 --- /dev/null +++ b/rest/taskrouter/v1/workspace/taskQueue.ts @@ -0,0 +1,1134 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { TaskQueueBulkRealTimeStatisticsListInstance } from "./taskQueue/taskQueueBulkRealTimeStatistics"; +import { TaskQueueCumulativeStatisticsListInstance } from "./taskQueue/taskQueueCumulativeStatistics"; +import { TaskQueueRealTimeStatisticsListInstance } from "./taskQueue/taskQueueRealTimeStatistics"; +import { TaskQueueStatisticsListInstance } from "./taskQueue/taskQueueStatistics"; +import { TaskQueuesStatisticsListInstance } from "./taskQueue/taskQueuesStatistics"; + + +/** + * How Tasks will be assigned to Workers. Set this parameter to `LIFO` to assign most recently created Task first or `FIFO` to assign the oldest Task. Default is FIFO. [Click here](https://www.twilio.com/docs/taskrouter/queue-ordering-last-first-out-lifo) to learn more. + */ +export type TaskQueueTaskOrder = 'FIFO'|'LIFO'; + + + + +/** + * Options to pass to update a TaskQueueInstance + */ +export interface TaskQueueContextUpdateOptions { + /** A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. */ + "friendlyName"?: string; + /** A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example \\\'\\\"language\\\" == \\\"spanish\\\"\\\' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. */ + "targetWorkers"?: string; + /** The SID of the Activity to assign Workers when a task is reserved for them. */ + "reservationActivitySid"?: string; + /** The SID of the Activity to assign Workers when a task is assigned for them. */ + "assignmentActivitySid"?: string; + /** The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. */ + "maxReservedWorkers"?: number; + /** */ + "taskOrder"?: TaskQueueTaskOrder; +} + +/** + * Options to pass to create a TaskQueueInstance + */ +export interface TaskQueueListInstanceCreateOptions { + /** A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. */ + "friendlyName": string; + /** A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `\\\'\\\"language\\\" == \\\"spanish\\\"\\\'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). */ + "targetWorkers"?: string; + /** The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. */ + "maxReservedWorkers"?: number; + /** */ + "taskOrder"?: TaskQueueTaskOrder; + /** The SID of the Activity to assign Workers when a task is reserved for them. */ + "reservationActivitySid"?: string; + /** The SID of the Activity to assign Workers when a task is assigned to them. */ + "assignmentActivitySid"?: string; +} + +/** + * Options to pass to each + */ +export interface TaskQueueListInstanceEachOptions { + /** The `friendly_name` of the TaskQueue resources to read. */ + "friendlyName"?: string; + /** The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. */ + "evaluateWorkerAttributes"?: string; + /** The SID of the Worker with the TaskQueue resources to read. */ + "workerSid"?: string; + /** Sorting parameter for TaskQueues */ + "ordering"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TaskQueueInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TaskQueueListInstanceOptions { + /** The `friendly_name` of the TaskQueue resources to read. */ + "friendlyName"?: string; + /** The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. */ + "evaluateWorkerAttributes"?: string; + /** The SID of the Worker with the TaskQueue resources to read. */ + "workerSid"?: string; + /** Sorting parameter for TaskQueues */ + "ordering"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TaskQueueListInstancePageOptions { + /** The `friendly_name` of the TaskQueue resources to read. */ + "friendlyName"?: string; + /** The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. */ + "evaluateWorkerAttributes"?: string; + /** The SID of the Worker with the TaskQueue resources to read. */ + "workerSid"?: string; + /** Sorting parameter for TaskQueues */ + "ordering"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TaskQueueContext { + cumulativeStatistics: TaskQueueCumulativeStatisticsListInstance; + realTimeStatistics: TaskQueueRealTimeStatisticsListInstance; + statistics: TaskQueueStatisticsListInstance; + + /** + * Remove a TaskQueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a TaskQueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a TaskQueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance + */ + fetch(callback?: (error: Error | null, item?: TaskQueueInstance) => any): Promise<TaskQueueInstance> + + /** + * Fetch a TaskQueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>> + + /** + * Update a TaskQueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance + */ + update(callback?: (error: Error | null, item?: TaskQueueInstance) => any): Promise<TaskQueueInstance>; + /** + * Update a TaskQueueInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance + */ + update(params: TaskQueueContextUpdateOptions, callback?: (error: Error | null, item?: TaskQueueInstance) => any): Promise<TaskQueueInstance>; + + /** + * Update a TaskQueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>>; + /** + * Update a TaskQueueInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance with HTTP metadata + */ + updateWithHttpInfo(params: TaskQueueContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TaskQueueContextSolution { + "workspaceSid": string; + "sid": string; +} + +export class TaskQueueContextImpl implements TaskQueueContext { + protected _solution: TaskQueueContextSolution; + protected _uri: string; + + protected _cumulativeStatistics?: TaskQueueCumulativeStatisticsListInstance; + protected _realTimeStatistics?: TaskQueueRealTimeStatisticsListInstance; + protected _statistics?: TaskQueueStatisticsListInstance; + + constructor(protected _version: V1, workspaceSid: string, sid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { workspaceSid, sid, }; + this._uri = `/Workspaces/${workspaceSid}/TaskQueues/${sid}`; + } + + get cumulativeStatistics(): TaskQueueCumulativeStatisticsListInstance { + this._cumulativeStatistics = this._cumulativeStatistics || TaskQueueCumulativeStatisticsListInstance(this._version, this._solution.workspaceSid, this._solution.sid); + return this._cumulativeStatistics; + } + + get realTimeStatistics(): TaskQueueRealTimeStatisticsListInstance { + this._realTimeStatistics = this._realTimeStatistics || TaskQueueRealTimeStatisticsListInstance(this._version, this._solution.workspaceSid, this._solution.sid); + return this._realTimeStatistics; + } + + get statistics(): TaskQueueStatisticsListInstance { + this._statistics = this._statistics || TaskQueueStatisticsListInstance(this._version, this._solution.workspaceSid, this._solution.sid); + return this._statistics; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TaskQueueInstance) => any): Promise<TaskQueueInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TaskQueueInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TaskQueueResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TaskQueueInstance> => ({ + ...response, + body: new TaskQueueInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: TaskQueueContextUpdateOptions | ((error: Error | null, item?: TaskQueueInstance) => any),callback?: (error: Error | null, item?: TaskQueueInstance) => any): Promise<TaskQueueInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["targetWorkers"] !== undefined) + data["TargetWorkers"] = params["targetWorkers"]; + if (params["reservationActivitySid"] !== undefined) + data["ReservationActivitySid"] = params["reservationActivitySid"]; + if (params["assignmentActivitySid"] !== undefined) + data["AssignmentActivitySid"] = params["assignmentActivitySid"]; + if (params["maxReservedWorkers"] !== undefined) + data["MaxReservedWorkers"] = params["maxReservedWorkers"]; + if (params["taskOrder"] !== undefined) + data["TaskOrder"] = params["taskOrder"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TaskQueueInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: TaskQueueContextUpdateOptions | ((error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["targetWorkers"] !== undefined) + data["TargetWorkers"] = params["targetWorkers"]; + if (params["reservationActivitySid"] !== undefined) + data["ReservationActivitySid"] = params["reservationActivitySid"]; + if (params["assignmentActivitySid"] !== undefined) + data["AssignmentActivitySid"] = params["assignmentActivitySid"]; + if (params["maxReservedWorkers"] !== undefined) + data["MaxReservedWorkers"] = params["maxReservedWorkers"]; + if (params["taskOrder"] !== undefined) + data["TaskOrder"] = params["taskOrder"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<TaskQueueResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TaskQueueInstance> => ({ + ...response, + body: new TaskQueueInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TaskQueuePayload extends TwilioResponsePayload { + task_queues: TaskQueueResource[]; +} + +interface TaskQueueResource { + account_sid: string; + assignment_activity_sid: string; + assignment_activity_name: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + max_reserved_workers: number; + reservation_activity_sid: string; + reservation_activity_name: string; + sid: string; + target_workers: string; + task_order: TaskQueueTaskOrder; + url: string; + workspace_sid: string; + links: Record<string, string>; +} + +export class TaskQueueInstance { + protected _solution: TaskQueueContextSolution; + protected _context?: TaskQueueContext; + + constructor(protected _version: V1, payload: TaskQueueResource, workspaceSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.assignmentActivitySid = (payload.assignment_activity_sid); + this.assignmentActivityName = (payload.assignment_activity_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.maxReservedWorkers = deserialize.integer(payload.max_reserved_workers); + this.reservationActivitySid = (payload.reservation_activity_sid); + this.reservationActivityName = (payload.reservation_activity_name); + this.sid = (payload.sid); + this.targetWorkers = (payload.target_workers); + this.taskOrder = payload.task_order; + this.url = (payload.url); + this.workspaceSid = (payload.workspace_sid); + this.links = (payload.links); + + this._solution = { workspaceSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + */ + accountSid: string; + /** + * The SID of the Activity to assign Workers when a task is assigned for them. + */ + assignmentActivitySid: string; + /** + * The name of the Activity to assign Workers when a task is assigned for them. + */ + assignmentActivityName: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The maximum number of Workers to reserve for the assignment of a task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + */ + maxReservedWorkers: number; + /** + * The SID of the Activity to assign Workers once a task is reserved for them. + */ + reservationActivitySid: string; + /** + * The name of the Activity to assign Workers once a task is reserved for them. + */ + reservationActivityName: string; + /** + * The unique string that we created to identify the TaskQueue resource. + */ + sid: string; + /** + * A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example `\'\"language\" == \"spanish\"\'` If no TargetWorkers parameter is provided, Tasks will wait in the TaskQueue until they are either deleted or moved to another TaskQueue. Additional examples on how to describing Worker selection criteria below. Defaults to 1==1. + */ + targetWorkers: string; + taskOrder: TaskQueueTaskOrder; + /** + * The absolute URL of the TaskQueue resource. + */ + url: string; + /** + * The SID of the Workspace that contains the TaskQueue. + */ + workspaceSid: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): TaskQueueContext { + this._context = this._context || new TaskQueueContextImpl(this._version, this._solution.workspaceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a TaskQueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TaskQueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TaskQueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance + */ + fetch(callback?: (error: Error | null, item?: TaskQueueInstance) => any): Promise<TaskQueueInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TaskQueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TaskQueueInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance + */ + update(callback?: (error: Error | null, item?: TaskQueueInstance) => any): Promise<TaskQueueInstance>; + /** + * Update a TaskQueueInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance + */ + update(params: TaskQueueContextUpdateOptions, callback?: (error: Error | null, item?: TaskQueueInstance) => any): Promise<TaskQueueInstance>; + + update(params?: any, callback?: (error: Error | null, item?: TaskQueueInstance) => any): Promise<TaskQueueInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a TaskQueueInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>>; + /** + * Update a TaskQueueInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance with HTTP metadata + */ + updateWithHttpInfo(params: TaskQueueContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the cumulativeStatistics. + */ + cumulativeStatistics(): TaskQueueCumulativeStatisticsListInstance { + return this._proxy.cumulativeStatistics; + } + + /** + * Access the realTimeStatistics. + */ + realTimeStatistics(): TaskQueueRealTimeStatisticsListInstance { + return this._proxy.realTimeStatistics; + } + + /** + * Access the statistics. + */ + statistics(): TaskQueueStatisticsListInstance { + return this._proxy.statistics; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + assignmentActivitySid: this.assignmentActivitySid, + assignmentActivityName: this.assignmentActivityName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + maxReservedWorkers: this.maxReservedWorkers, + reservationActivitySid: this.reservationActivitySid, + reservationActivityName: this.reservationActivityName, + sid: this.sid, + targetWorkers: this.targetWorkers, + taskOrder: this.taskOrder, + url: this.url, + workspaceSid: this.workspaceSid, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TaskQueueSolution { + workspaceSid: string; +} + +export interface TaskQueueListInstance { + _version: V1; + _solution: TaskQueueSolution; + _uri: string; + + (sid: string, ): TaskQueueContext; + get(sid: string, ): TaskQueueContext; + + _bulkRealTimeStatistics?: TaskQueueBulkRealTimeStatisticsListInstance; + bulkRealTimeStatistics: TaskQueueBulkRealTimeStatisticsListInstance; + _statistics?: TaskQueuesStatisticsListInstance; + statistics: TaskQueuesStatisticsListInstance; + + + + + + + + /** + * Create a TaskQueueInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance + */ + create(params: TaskQueueListInstanceCreateOptions, callback?: (error: Error | null, item?: TaskQueueInstance) => any): Promise<TaskQueueInstance>; + + /** + * Create a TaskQueueInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueInstance with HTTP metadata + */ + createWithHttpInfo(params: TaskQueueListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>>; + + + + + /** + * Streams TaskQueueInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueueListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TaskQueueInstance, done: (err?: Error) => void) => void): void; + each(params: TaskQueueListInstanceEachOptions, callback?: (item: TaskQueueInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TaskQueueInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueueListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TaskQueueInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TaskQueueListInstanceEachOptions, callback?: (item: TaskQueueInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TaskQueueInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TaskQueuePage) => any): Promise<TaskQueuePage>; + /** + * Retrieve a single target page of TaskQueueInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TaskQueuePage>) => any): Promise<ApiResponse<TaskQueuePage>>; + /** + * Lists TaskQueueInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueueListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TaskQueueInstance[]) => any): Promise<TaskQueueInstance[]>; + list(params: TaskQueueListInstanceOptions, callback?: (error: Error | null, items: TaskQueueInstance[]) => any): Promise<TaskQueueInstance[]>; + /** + * Lists TaskQueueInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueueListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TaskQueueInstance[]>) => any): Promise<ApiResponse<TaskQueueInstance[]>>; + listWithHttpInfo(params: TaskQueueListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TaskQueueInstance[]>) => any): Promise<ApiResponse<TaskQueueInstance[]>>; + /** + * Retrieve a single page of TaskQueueInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueueListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TaskQueuePage) => any): Promise<TaskQueuePage>; + page(params: TaskQueueListInstancePageOptions, callback?: (error: Error | null, items: TaskQueuePage) => any): Promise<TaskQueuePage>; + /** + * Retrieve a single page of TaskQueueInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueueListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TaskQueuePage>) => any): Promise<ApiResponse<TaskQueuePage>>; + pageWithHttpInfo(params: TaskQueueListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TaskQueuePage>) => any): Promise<ApiResponse<TaskQueuePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TaskQueueListInstance(version: V1, workspaceSid: string): TaskQueueListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as TaskQueueListInstance; + + instance.get = function get(sid, ): TaskQueueContext { + return new TaskQueueContextImpl(version, workspaceSid, sid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = `/Workspaces/${workspaceSid}/TaskQueues`; + + Object.defineProperty(instance, "bulkRealTimeStatistics", { + get: function bulkRealTimeStatistics() { + if (!instance._bulkRealTimeStatistics) { + instance._bulkRealTimeStatistics = TaskQueueBulkRealTimeStatisticsListInstance(instance._version, instance._solution.workspaceSid); + } + return instance._bulkRealTimeStatistics; + } + }); + + Object.defineProperty(instance, "statistics", { + get: function statistics() { + if (!instance._statistics) { + instance._statistics = TaskQueuesStatisticsListInstance(instance._version, instance._solution.workspaceSid); + } + return instance._statistics; + } + }); + + instance.create = function create(params: TaskQueueListInstanceCreateOptions, callback?: (error: Error | null, items: TaskQueueInstance) => any): Promise<TaskQueueInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["targetWorkers"] !== undefined) + data["TargetWorkers"] = params["targetWorkers"]; + if (params["maxReservedWorkers"] !== undefined) + data["MaxReservedWorkers"] = params["maxReservedWorkers"]; + if (params["taskOrder"] !== undefined) + data["TaskOrder"] = params["taskOrder"]; + if (params["reservationActivitySid"] !== undefined) + data["ReservationActivitySid"] = params["reservationActivitySid"]; + if (params["assignmentActivitySid"] !== undefined) + data["AssignmentActivitySid"] = params["assignmentActivitySid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TaskQueueInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TaskQueueListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<TaskQueueInstance>) => any): Promise<ApiResponse<TaskQueueInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["targetWorkers"] !== undefined) + data["TargetWorkers"] = params["targetWorkers"]; + if (params["maxReservedWorkers"] !== undefined) + data["MaxReservedWorkers"] = params["maxReservedWorkers"]; + if (params["taskOrder"] !== undefined) + data["TaskOrder"] = params["taskOrder"]; + if (params["reservationActivitySid"] !== undefined) + data["ReservationActivitySid"] = params["reservationActivitySid"]; + if (params["assignmentActivitySid"] !== undefined) + data["AssignmentActivitySid"] = params["assignmentActivitySid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TaskQueueResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TaskQueueInstance> => ({ + ...response, + body: new TaskQueueInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TaskQueueListInstancePageOptions | ((error: Error | null, items: TaskQueuePage) => any), callback?: (error: Error | null, items: TaskQueuePage) => any): Promise<TaskQueuePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["evaluateWorkerAttributes"] !== undefined) + data["EvaluateWorkerAttributes"] = params["evaluateWorkerAttributes"]; + if (params["workerSid"] !== undefined) + data["WorkerSid"] = params["workerSid"]; + if (params["ordering"] !== undefined) + data["Ordering"] = params["ordering"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TaskQueuePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TaskQueuePage) => any): Promise<TaskQueuePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TaskQueuePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TaskQueueListInstancePageOptions | ((error: Error | null, items: ApiResponse<TaskQueuePage>) => any), callback?: (error: Error | null, items: ApiResponse<TaskQueuePage>) => any): Promise<ApiResponse<TaskQueuePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["evaluateWorkerAttributes"] !== undefined) + data["EvaluateWorkerAttributes"] = params["evaluateWorkerAttributes"]; + if (params["workerSid"] !== undefined) + data["WorkerSid"] = params["workerSid"]; + if (params["ordering"] !== undefined) + data["Ordering"] = params["ordering"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TaskQueuePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TaskQueuePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TaskQueuePage>) => any): Promise<ApiResponse<TaskQueuePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TaskQueuePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TaskQueuePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TaskQueuePage extends Page<V1, TaskQueuePayload, TaskQueueResource, TaskQueueInstance> { +/** +* Initialize the TaskQueuePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TaskQueueSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TaskQueueInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TaskQueueResource): TaskQueueInstance { + + return new TaskQueueInstance( + this._version, + payload, + this._solution.workspaceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/taskQueue/taskQueueBulkRealTimeStatistics.ts b/rest/taskrouter/v1/workspace/taskQueue/taskQueueBulkRealTimeStatistics.ts new file mode 100644 index 000000000..78025d824 --- /dev/null +++ b/rest/taskrouter/v1/workspace/taskQueue/taskQueueBulkRealTimeStatistics.ts @@ -0,0 +1,244 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to create a TaskQueueBulkRealTimeStatisticsInstance + */ +export interface TaskQueueBulkRealTimeStatisticsListInstanceCreateOptions { + /** */ + "body"?: object; +} + + +export interface TaskQueueBulkRealTimeStatisticsSolution { + workspaceSid: string; +} + +export interface TaskQueueBulkRealTimeStatisticsListInstance { + _version: V1; + _solution: TaskQueueBulkRealTimeStatisticsSolution; + _uri: string; + + + + /** + * Create a TaskQueueBulkRealTimeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueBulkRealTimeStatisticsInstance + */ + create(callback?: (error: Error | null, item?: TaskQueueBulkRealTimeStatisticsInstance) => any): Promise<TaskQueueBulkRealTimeStatisticsInstance>; + /** + * Create a TaskQueueBulkRealTimeStatisticsInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueBulkRealTimeStatisticsInstance + */ + create(params: object, headers?: any, callback?: (error: Error | null, item?: TaskQueueBulkRealTimeStatisticsInstance) => any): Promise<TaskQueueBulkRealTimeStatisticsInstance>; + + /** + * Create a TaskQueueBulkRealTimeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueBulkRealTimeStatisticsInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueBulkRealTimeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueBulkRealTimeStatisticsInstance>>; + /** + * Create a TaskQueueBulkRealTimeStatisticsInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueBulkRealTimeStatisticsInstance with HTTP metadata + */ + createWithHttpInfo(params: object, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TaskQueueBulkRealTimeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueBulkRealTimeStatisticsInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TaskQueueBulkRealTimeStatisticsListInstance(version: V1, workspaceSid: string): TaskQueueBulkRealTimeStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = {} as TaskQueueBulkRealTimeStatisticsListInstance; + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = `/Workspaces/${workspaceSid}/TaskQueues/RealTimeStatistics`; + + instance.create = function create(params?: object | ((error: Error | null, items: TaskQueueBulkRealTimeStatisticsInstance) => any), headers?: any, callback?: (error: Error | null, items: TaskQueueBulkRealTimeStatisticsInstance) => any): Promise<TaskQueueBulkRealTimeStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TaskQueueBulkRealTimeStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: object | ((error: Error | null, items: ApiResponse<TaskQueueBulkRealTimeStatisticsInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<TaskQueueBulkRealTimeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueBulkRealTimeStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<object> as object; + } else { + params = params || {} as Partial<object> as object; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TaskQueueBulkRealTimeStatisticsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TaskQueueBulkRealTimeStatisticsInstance> => ({ + ...response, + body: new TaskQueueBulkRealTimeStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TaskQueueBulkRealTimeStatisticsPayload extends TaskQueueBulkRealTimeStatisticsResource {} + +interface TaskQueueBulkRealTimeStatisticsResource { + account_sid: string; + workspace_sid: string; + task_queue_data: Array<any>; + task_queue_response_count: number; + url: string; +} + +export class TaskQueueBulkRealTimeStatisticsInstance { + + constructor(protected _version: V1, payload: TaskQueueBulkRealTimeStatisticsResource, workspaceSid: string) { + + this.accountSid = (payload.account_sid); + this.workspaceSid = (payload.workspace_sid); + this.taskQueueData = (payload.task_queue_data); + this.taskQueueResponseCount = deserialize.integer(payload.task_queue_response_count); + this.url = (payload.url); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + */ + accountSid: string; + /** + * The SID of the Workspace that contains the TaskQueue. + */ + workspaceSid: string; + /** + * The real-time statistics for each requested TaskQueue SID. `task_queue_data` returns the following attributes: `task_queue_sid`: The SID of the TaskQueue from which these statistics were calculated. `total_available_workers`: The total number of Workers available for Tasks in the TaskQueue. `total_eligible_workers`: The total number of Workers eligible for Tasks in the TaskQueue, regardless of their Activity state. `total_tasks`: The total number of Tasks. `longest_task_waiting_age`: The age of the longest waiting Task. `longest_task_waiting_sid`: The SID of the longest waiting Task. `tasks_by_status`: The number of Tasks grouped by their current status. `tasks_by_priority`: The number of Tasks grouped by priority. `activity_statistics`: The number of current Workers grouped by Activity. + */ + taskQueueData: Array<any>; + /** + * The number of TaskQueue statistics received in task_queue_data. + */ + taskQueueResponseCount: number; + /** + * The absolute URL of the TaskQueue statistics resource. + */ + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + workspaceSid: this.workspaceSid, + taskQueueData: this.taskQueueData, + taskQueueResponseCount: this.taskQueueResponseCount, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/taskrouter/v1/workspace/taskQueue/taskQueueCumulativeStatistics.ts b/rest/taskrouter/v1/workspace/taskQueue/taskQueueCumulativeStatistics.ts new file mode 100644 index 000000000..28902119a --- /dev/null +++ b/rest/taskrouter/v1/workspace/taskQueue/taskQueueCumulativeStatistics.ts @@ -0,0 +1,497 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a TaskQueueCumulativeStatisticsInstance + */ +export interface TaskQueueCumulativeStatisticsContextFetchOptions { + /** Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** Only calculate statistics since this many minutes in the past. The default is 15 minutes. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; + /** A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. */ + "splitByWaitTime"?: string; +} + +export interface TaskQueueCumulativeStatisticsContext { + + /** + * Fetch a TaskQueueCumulativeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueCumulativeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: TaskQueueCumulativeStatisticsInstance) => any): Promise<TaskQueueCumulativeStatisticsInstance>; + /** + * Fetch a TaskQueueCumulativeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueCumulativeStatisticsInstance + */ + fetch(params: TaskQueueCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: TaskQueueCumulativeStatisticsInstance) => any): Promise<TaskQueueCumulativeStatisticsInstance>; + + /** + * Fetch a TaskQueueCumulativeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueCumulativeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueCumulativeStatisticsInstance>>; + /** + * Fetch a TaskQueueCumulativeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: TaskQueueCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<TaskQueueCumulativeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueCumulativeStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TaskQueueCumulativeStatisticsContextSolution { + "workspaceSid": string; + "taskQueueSid": string; +} + +export class TaskQueueCumulativeStatisticsContextImpl implements TaskQueueCumulativeStatisticsContext { + protected _solution: TaskQueueCumulativeStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, taskQueueSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(taskQueueSid)) { + throw new Error('Parameter \'taskQueueSid\' is not valid.'); + } + + this._solution = { workspaceSid, taskQueueSid, }; + this._uri = `/Workspaces/${workspaceSid}/TaskQueues/${taskQueueSid}/CumulativeStatistics`; + } + + fetch(params?: TaskQueueCumulativeStatisticsContextFetchOptions | ((error: Error | null, item?: TaskQueueCumulativeStatisticsInstance) => any),callback?: (error: Error | null, item?: TaskQueueCumulativeStatisticsInstance) => any): Promise<TaskQueueCumulativeStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new TaskQueueCumulativeStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.taskQueueSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: TaskQueueCumulativeStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<TaskQueueCumulativeStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TaskQueueCumulativeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueCumulativeStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TaskQueueCumulativeStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TaskQueueCumulativeStatisticsInstance> => ({ + ...response, + body: new TaskQueueCumulativeStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.taskQueueSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TaskQueueCumulativeStatisticsPayload extends TaskQueueCumulativeStatisticsResource {} + +interface TaskQueueCumulativeStatisticsResource { + account_sid: string; + avg_task_acceptance_time: number; + start_time: Date; + end_time: Date; + reservations_created: number; + reservations_accepted: number; + reservations_rejected: number; + reservations_timed_out: number; + reservations_canceled: number; + reservations_rescinded: number; + split_by_wait_time: any; + task_queue_sid: string; + wait_duration_until_accepted: any; + wait_duration_until_canceled: any; + wait_duration_in_queue_until_accepted: any; + tasks_canceled: number; + tasks_completed: number; + tasks_deleted: number; + tasks_entered: number; + tasks_moved: number; + workspace_sid: string; + url: string; +} + +export class TaskQueueCumulativeStatisticsInstance { + protected _solution: TaskQueueCumulativeStatisticsContextSolution; + protected _context?: TaskQueueCumulativeStatisticsContext; + + constructor(protected _version: V1, payload: TaskQueueCumulativeStatisticsResource, workspaceSid: string, taskQueueSid: string) { + + this.accountSid = (payload.account_sid); + this.avgTaskAcceptanceTime = deserialize.integer(payload.avg_task_acceptance_time); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.reservationsCreated = deserialize.integer(payload.reservations_created); + this.reservationsAccepted = deserialize.integer(payload.reservations_accepted); + this.reservationsRejected = deserialize.integer(payload.reservations_rejected); + this.reservationsTimedOut = deserialize.integer(payload.reservations_timed_out); + this.reservationsCanceled = deserialize.integer(payload.reservations_canceled); + this.reservationsRescinded = deserialize.integer(payload.reservations_rescinded); + this.splitByWaitTime = (payload.split_by_wait_time); + this.taskQueueSid = (payload.task_queue_sid); + this.waitDurationUntilAccepted = (payload.wait_duration_until_accepted); + this.waitDurationUntilCanceled = (payload.wait_duration_until_canceled); + this.waitDurationInQueueUntilAccepted = (payload.wait_duration_in_queue_until_accepted); + this.tasksCanceled = deserialize.integer(payload.tasks_canceled); + this.tasksCompleted = deserialize.integer(payload.tasks_completed); + this.tasksDeleted = deserialize.integer(payload.tasks_deleted); + this.tasksEntered = deserialize.integer(payload.tasks_entered); + this.tasksMoved = deserialize.integer(payload.tasks_moved); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, taskQueueSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + */ + accountSid: string; + /** + * The average time in seconds between Task creation and acceptance. + */ + avgTaskAcceptanceTime: number; + /** + * The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + startTime: Date; + /** + * The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + endTime: Date; + /** + * The total number of Reservations created for Tasks in the TaskQueue. + */ + reservationsCreated: number; + /** + * The total number of Reservations accepted for Tasks in the TaskQueue. + */ + reservationsAccepted: number; + /** + * The total number of Reservations rejected for Tasks in the TaskQueue. + */ + reservationsRejected: number; + /** + * The total number of Reservations that timed out for Tasks in the TaskQueue. + */ + reservationsTimedOut: number; + /** + * The total number of Reservations canceled for Tasks in the TaskQueue. + */ + reservationsCanceled: number; + /** + * The total number of Reservations rescinded. + */ + reservationsRescinded: number; + /** + * A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + */ + splitByWaitTime: any; + /** + * The SID of the TaskQueue from which these statistics were calculated. + */ + taskQueueSid: string; + /** + * The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks accepted while in the TaskQueue. Calculation is based on the time when the Tasks were created. For transfers, the wait duration is counted from the moment ***the Task was created***, and not from when the transfer was initiated. + */ + waitDurationUntilAccepted: any; + /** + * The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks canceled while in the TaskQueue. + */ + waitDurationUntilCanceled: any; + /** + * The relative wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks accepted while in the TaskQueue. Calculation is based on the time when the Tasks entered the TaskQueue. + */ + waitDurationInQueueUntilAccepted: any; + /** + * The total number of Tasks canceled in the TaskQueue. + */ + tasksCanceled: number; + /** + * The total number of Tasks completed in the TaskQueue. + */ + tasksCompleted: number; + /** + * The total number of Tasks deleted in the TaskQueue. + */ + tasksDeleted: number; + /** + * The total number of Tasks entered into the TaskQueue. + */ + tasksEntered: number; + /** + * The total number of Tasks that were moved from one queue to another. + */ + tasksMoved: number; + /** + * The SID of the Workspace that contains the TaskQueue. + */ + workspaceSid: string; + /** + * The absolute URL of the TaskQueue statistics resource. + */ + url: string; + + private get _proxy(): TaskQueueCumulativeStatisticsContext { + this._context = this._context || new TaskQueueCumulativeStatisticsContextImpl(this._version, this._solution.workspaceSid, this._solution.taskQueueSid); + return this._context; + } + + /** + * Fetch a TaskQueueCumulativeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueCumulativeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: TaskQueueCumulativeStatisticsInstance) => any): Promise<TaskQueueCumulativeStatisticsInstance>; + /** + * Fetch a TaskQueueCumulativeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueCumulativeStatisticsInstance + */ + fetch(params: TaskQueueCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: TaskQueueCumulativeStatisticsInstance) => any): Promise<TaskQueueCumulativeStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: TaskQueueCumulativeStatisticsInstance) => any): Promise<TaskQueueCumulativeStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a TaskQueueCumulativeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueCumulativeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueCumulativeStatisticsInstance>>; + /** + * Fetch a TaskQueueCumulativeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: TaskQueueCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<TaskQueueCumulativeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueCumulativeStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TaskQueueCumulativeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueCumulativeStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + avgTaskAcceptanceTime: this.avgTaskAcceptanceTime, + startTime: this.startTime, + endTime: this.endTime, + reservationsCreated: this.reservationsCreated, + reservationsAccepted: this.reservationsAccepted, + reservationsRejected: this.reservationsRejected, + reservationsTimedOut: this.reservationsTimedOut, + reservationsCanceled: this.reservationsCanceled, + reservationsRescinded: this.reservationsRescinded, + splitByWaitTime: this.splitByWaitTime, + taskQueueSid: this.taskQueueSid, + waitDurationUntilAccepted: this.waitDurationUntilAccepted, + waitDurationUntilCanceled: this.waitDurationUntilCanceled, + waitDurationInQueueUntilAccepted: this.waitDurationInQueueUntilAccepted, + tasksCanceled: this.tasksCanceled, + tasksCompleted: this.tasksCompleted, + tasksDeleted: this.tasksDeleted, + tasksEntered: this.tasksEntered, + tasksMoved: this.tasksMoved, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TaskQueueCumulativeStatisticsSolution { + workspaceSid: string; + taskQueueSid: string; +} + +export interface TaskQueueCumulativeStatisticsListInstance { + _version: V1; + _solution: TaskQueueCumulativeStatisticsSolution; + _uri: string; + + (): TaskQueueCumulativeStatisticsContext; + get(): TaskQueueCumulativeStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TaskQueueCumulativeStatisticsListInstance(version: V1, workspaceSid: string, taskQueueSid: string): TaskQueueCumulativeStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(taskQueueSid)) { + throw new Error('Parameter \'taskQueueSid\' is not valid.'); + } + + const instance = (() => instance.get()) as TaskQueueCumulativeStatisticsListInstance; + + instance.get = function get(): TaskQueueCumulativeStatisticsContext { + return new TaskQueueCumulativeStatisticsContextImpl(version, workspaceSid, taskQueueSid); + } + + instance._version = version; + instance._solution = { workspaceSid, taskQueueSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/taskQueue/taskQueueRealTimeStatistics.ts b/rest/taskrouter/v1/workspace/taskQueue/taskQueueRealTimeStatistics.ts new file mode 100644 index 000000000..a29154cb2 --- /dev/null +++ b/rest/taskrouter/v1/workspace/taskQueue/taskQueueRealTimeStatistics.ts @@ -0,0 +1,417 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a TaskQueueRealTimeStatisticsInstance + */ +export interface TaskQueueRealTimeStatisticsContextFetchOptions { + /** The TaskChannel for which to fetch statistics. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; +} + +export interface TaskQueueRealTimeStatisticsContext { + + /** + * Fetch a TaskQueueRealTimeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueRealTimeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: TaskQueueRealTimeStatisticsInstance) => any): Promise<TaskQueueRealTimeStatisticsInstance>; + /** + * Fetch a TaskQueueRealTimeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueRealTimeStatisticsInstance + */ + fetch(params: TaskQueueRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: TaskQueueRealTimeStatisticsInstance) => any): Promise<TaskQueueRealTimeStatisticsInstance>; + + /** + * Fetch a TaskQueueRealTimeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueRealTimeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueRealTimeStatisticsInstance>>; + /** + * Fetch a TaskQueueRealTimeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: TaskQueueRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<TaskQueueRealTimeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueRealTimeStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TaskQueueRealTimeStatisticsContextSolution { + "workspaceSid": string; + "taskQueueSid": string; +} + +export class TaskQueueRealTimeStatisticsContextImpl implements TaskQueueRealTimeStatisticsContext { + protected _solution: TaskQueueRealTimeStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, taskQueueSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(taskQueueSid)) { + throw new Error('Parameter \'taskQueueSid\' is not valid.'); + } + + this._solution = { workspaceSid, taskQueueSid, }; + this._uri = `/Workspaces/${workspaceSid}/TaskQueues/${taskQueueSid}/RealTimeStatistics`; + } + + fetch(params?: TaskQueueRealTimeStatisticsContextFetchOptions | ((error: Error | null, item?: TaskQueueRealTimeStatisticsInstance) => any),callback?: (error: Error | null, item?: TaskQueueRealTimeStatisticsInstance) => any): Promise<TaskQueueRealTimeStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new TaskQueueRealTimeStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.taskQueueSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: TaskQueueRealTimeStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<TaskQueueRealTimeStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TaskQueueRealTimeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueRealTimeStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TaskQueueRealTimeStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TaskQueueRealTimeStatisticsInstance> => ({ + ...response, + body: new TaskQueueRealTimeStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.taskQueueSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TaskQueueRealTimeStatisticsPayload extends TaskQueueRealTimeStatisticsResource {} + +interface TaskQueueRealTimeStatisticsResource { + account_sid: string; + activity_statistics: Array<any>; + longest_task_waiting_age: number; + longest_task_waiting_sid: string; + longest_relative_task_age_in_queue: number; + longest_relative_task_sid_in_queue: string; + task_queue_sid: string; + tasks_by_priority: any; + tasks_by_status: any; + total_available_workers: number; + total_eligible_workers: number; + total_tasks: number; + workspace_sid: string; + url: string; +} + +export class TaskQueueRealTimeStatisticsInstance { + protected _solution: TaskQueueRealTimeStatisticsContextSolution; + protected _context?: TaskQueueRealTimeStatisticsContext; + + constructor(protected _version: V1, payload: TaskQueueRealTimeStatisticsResource, workspaceSid: string, taskQueueSid: string) { + + this.accountSid = (payload.account_sid); + this.activityStatistics = (payload.activity_statistics); + this.longestTaskWaitingAge = deserialize.integer(payload.longest_task_waiting_age); + this.longestTaskWaitingSid = (payload.longest_task_waiting_sid); + this.longestRelativeTaskAgeInQueue = deserialize.integer(payload.longest_relative_task_age_in_queue); + this.longestRelativeTaskSidInQueue = (payload.longest_relative_task_sid_in_queue); + this.taskQueueSid = (payload.task_queue_sid); + this.tasksByPriority = (payload.tasks_by_priority); + this.tasksByStatus = (payload.tasks_by_status); + this.totalAvailableWorkers = deserialize.integer(payload.total_available_workers); + this.totalEligibleWorkers = deserialize.integer(payload.total_eligible_workers); + this.totalTasks = deserialize.integer(payload.total_tasks); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, taskQueueSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + */ + accountSid: string; + /** + * The number of current Workers by Activity. + */ + activityStatistics: Array<any>; + /** + * The age of the longest waiting Task. + */ + longestTaskWaitingAge: number; + /** + * The SID of the longest waiting Task. + */ + longestTaskWaitingSid: string; + /** + * The relative age in the TaskQueue for the longest waiting Task. Calculation is based on the time when the Task entered the TaskQueue. + */ + longestRelativeTaskAgeInQueue: number; + /** + * The Task SID of the Task waiting in the TaskQueue the longest. Calculation is based on the time when the Task entered the TaskQueue. + */ + longestRelativeTaskSidInQueue: string; + /** + * The SID of the TaskQueue from which these statistics were calculated. + */ + taskQueueSid: string; + /** + * The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + */ + tasksByPriority: any; + /** + * The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + */ + tasksByStatus: any; + /** + * The total number of Workers in the TaskQueue with an `available` status. Workers with an `available` status may already have active interactions or may have none. + */ + totalAvailableWorkers: number; + /** + * The total number of Workers eligible for Tasks in the TaskQueue, independent of their Activity state. + */ + totalEligibleWorkers: number; + /** + * The total number of Tasks. + */ + totalTasks: number; + /** + * The SID of the Workspace that contains the TaskQueue. + */ + workspaceSid: string; + /** + * The absolute URL of the TaskQueue statistics resource. + */ + url: string; + + private get _proxy(): TaskQueueRealTimeStatisticsContext { + this._context = this._context || new TaskQueueRealTimeStatisticsContextImpl(this._version, this._solution.workspaceSid, this._solution.taskQueueSid); + return this._context; + } + + /** + * Fetch a TaskQueueRealTimeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueRealTimeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: TaskQueueRealTimeStatisticsInstance) => any): Promise<TaskQueueRealTimeStatisticsInstance>; + /** + * Fetch a TaskQueueRealTimeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueRealTimeStatisticsInstance + */ + fetch(params: TaskQueueRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: TaskQueueRealTimeStatisticsInstance) => any): Promise<TaskQueueRealTimeStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: TaskQueueRealTimeStatisticsInstance) => any): Promise<TaskQueueRealTimeStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a TaskQueueRealTimeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueRealTimeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueRealTimeStatisticsInstance>>; + /** + * Fetch a TaskQueueRealTimeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: TaskQueueRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<TaskQueueRealTimeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueRealTimeStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TaskQueueRealTimeStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueRealTimeStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + activityStatistics: this.activityStatistics, + longestTaskWaitingAge: this.longestTaskWaitingAge, + longestTaskWaitingSid: this.longestTaskWaitingSid, + longestRelativeTaskAgeInQueue: this.longestRelativeTaskAgeInQueue, + longestRelativeTaskSidInQueue: this.longestRelativeTaskSidInQueue, + taskQueueSid: this.taskQueueSid, + tasksByPriority: this.tasksByPriority, + tasksByStatus: this.tasksByStatus, + totalAvailableWorkers: this.totalAvailableWorkers, + totalEligibleWorkers: this.totalEligibleWorkers, + totalTasks: this.totalTasks, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TaskQueueRealTimeStatisticsSolution { + workspaceSid: string; + taskQueueSid: string; +} + +export interface TaskQueueRealTimeStatisticsListInstance { + _version: V1; + _solution: TaskQueueRealTimeStatisticsSolution; + _uri: string; + + (): TaskQueueRealTimeStatisticsContext; + get(): TaskQueueRealTimeStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TaskQueueRealTimeStatisticsListInstance(version: V1, workspaceSid: string, taskQueueSid: string): TaskQueueRealTimeStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(taskQueueSid)) { + throw new Error('Parameter \'taskQueueSid\' is not valid.'); + } + + const instance = (() => instance.get()) as TaskQueueRealTimeStatisticsListInstance; + + instance.get = function get(): TaskQueueRealTimeStatisticsContext { + return new TaskQueueRealTimeStatisticsContextImpl(version, workspaceSid, taskQueueSid); + } + + instance._version = version; + instance._solution = { workspaceSid, taskQueueSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/taskQueue/taskQueueStatistics.ts b/rest/taskrouter/v1/workspace/taskQueue/taskQueueStatistics.ts new file mode 100644 index 000000000..4e71a48d6 --- /dev/null +++ b/rest/taskrouter/v1/workspace/taskQueue/taskQueueStatistics.ts @@ -0,0 +1,385 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a TaskQueueStatisticsInstance + */ +export interface TaskQueueStatisticsContextFetchOptions { + /** Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** Only calculate statistics since this many minutes in the past. The default is 15 minutes. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; + /** A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. */ + "splitByWaitTime"?: string; +} + +export interface TaskQueueStatisticsContext { + + /** + * Fetch a TaskQueueStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: TaskQueueStatisticsInstance) => any): Promise<TaskQueueStatisticsInstance>; + /** + * Fetch a TaskQueueStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueStatisticsInstance + */ + fetch(params: TaskQueueStatisticsContextFetchOptions, callback?: (error: Error | null, item?: TaskQueueStatisticsInstance) => any): Promise<TaskQueueStatisticsInstance>; + + /** + * Fetch a TaskQueueStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueStatisticsInstance>>; + /** + * Fetch a TaskQueueStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: TaskQueueStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<TaskQueueStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TaskQueueStatisticsContextSolution { + "workspaceSid": string; + "taskQueueSid": string; +} + +export class TaskQueueStatisticsContextImpl implements TaskQueueStatisticsContext { + protected _solution: TaskQueueStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, taskQueueSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(taskQueueSid)) { + throw new Error('Parameter \'taskQueueSid\' is not valid.'); + } + + this._solution = { workspaceSid, taskQueueSid, }; + this._uri = `/Workspaces/${workspaceSid}/TaskQueues/${taskQueueSid}/Statistics`; + } + + fetch(params?: TaskQueueStatisticsContextFetchOptions | ((error: Error | null, item?: TaskQueueStatisticsInstance) => any),callback?: (error: Error | null, item?: TaskQueueStatisticsInstance) => any): Promise<TaskQueueStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new TaskQueueStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.taskQueueSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: TaskQueueStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<TaskQueueStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TaskQueueStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TaskQueueStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TaskQueueStatisticsInstance> => ({ + ...response, + body: new TaskQueueStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.taskQueueSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TaskQueueStatisticsPayload extends TaskQueueStatisticsResource {} + +interface TaskQueueStatisticsResource { + account_sid: string; + cumulative: any; + realtime: any; + task_queue_sid: string; + workspace_sid: string; + url: string; +} + +export class TaskQueueStatisticsInstance { + protected _solution: TaskQueueStatisticsContextSolution; + protected _context?: TaskQueueStatisticsContext; + + constructor(protected _version: V1, payload: TaskQueueStatisticsResource, workspaceSid: string, taskQueueSid: string) { + + this.accountSid = (payload.account_sid); + this.cumulative = (payload.cumulative); + this.realtime = (payload.realtime); + this.taskQueueSid = (payload.task_queue_sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, taskQueueSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + */ + accountSid: string; + /** + * An object that contains the cumulative statistics for the TaskQueue. + */ + cumulative: any; + /** + * An object that contains the real-time statistics for the TaskQueue. + */ + realtime: any; + /** + * The SID of the TaskQueue from which these statistics were calculated. + */ + taskQueueSid: string; + /** + * The SID of the Workspace that contains the TaskQueue. + */ + workspaceSid: string; + /** + * The absolute URL of the TaskQueue statistics resource. + */ + url: string; + + private get _proxy(): TaskQueueStatisticsContext { + this._context = this._context || new TaskQueueStatisticsContextImpl(this._version, this._solution.workspaceSid, this._solution.taskQueueSid); + return this._context; + } + + /** + * Fetch a TaskQueueStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: TaskQueueStatisticsInstance) => any): Promise<TaskQueueStatisticsInstance>; + /** + * Fetch a TaskQueueStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueStatisticsInstance + */ + fetch(params: TaskQueueStatisticsContextFetchOptions, callback?: (error: Error | null, item?: TaskQueueStatisticsInstance) => any): Promise<TaskQueueStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: TaskQueueStatisticsInstance) => any): Promise<TaskQueueStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a TaskQueueStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TaskQueueStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueStatisticsInstance>>; + /** + * Fetch a TaskQueueStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TaskQueueStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: TaskQueueStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<TaskQueueStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TaskQueueStatisticsInstance>) => any): Promise<ApiResponse<TaskQueueStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + cumulative: this.cumulative, + realtime: this.realtime, + taskQueueSid: this.taskQueueSid, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TaskQueueStatisticsSolution { + workspaceSid: string; + taskQueueSid: string; +} + +export interface TaskQueueStatisticsListInstance { + _version: V1; + _solution: TaskQueueStatisticsSolution; + _uri: string; + + (): TaskQueueStatisticsContext; + get(): TaskQueueStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TaskQueueStatisticsListInstance(version: V1, workspaceSid: string, taskQueueSid: string): TaskQueueStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(taskQueueSid)) { + throw new Error('Parameter \'taskQueueSid\' is not valid.'); + } + + const instance = (() => instance.get()) as TaskQueueStatisticsListInstance; + + instance.get = function get(): TaskQueueStatisticsContext { + return new TaskQueueStatisticsContextImpl(version, workspaceSid, taskQueueSid); + } + + instance._version = version; + instance._solution = { workspaceSid, taskQueueSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/taskQueue/taskQueuesStatistics.ts b/rest/taskrouter/v1/workspace/taskQueue/taskQueuesStatistics.ts new file mode 100644 index 000000000..ac7de44f9 --- /dev/null +++ b/rest/taskrouter/v1/workspace/taskQueue/taskQueuesStatistics.ts @@ -0,0 +1,472 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface TaskQueuesStatisticsListInstanceEachOptions { + /** Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** The `friendly_name` of the TaskQueue statistics to read. */ + "friendlyName"?: string; + /** Only calculate statistics since this many minutes in the past. The default is 15 minutes. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; + /** A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. */ + "splitByWaitTime"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TaskQueuesStatisticsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TaskQueuesStatisticsListInstanceOptions { + /** Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** The `friendly_name` of the TaskQueue statistics to read. */ + "friendlyName"?: string; + /** Only calculate statistics since this many minutes in the past. The default is 15 minutes. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; + /** A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. */ + "splitByWaitTime"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TaskQueuesStatisticsListInstancePageOptions { + /** Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** The `friendly_name` of the TaskQueue statistics to read. */ + "friendlyName"?: string; + /** Only calculate statistics since this many minutes in the past. The default is 15 minutes. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; + /** A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. */ + "splitByWaitTime"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface TaskQueuesStatisticsSolution { + workspaceSid: string; +} + +export interface TaskQueuesStatisticsListInstance { + _version: V1; + _solution: TaskQueuesStatisticsSolution; + _uri: string; + + + + + /** + * Streams TaskQueuesStatisticsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueuesStatisticsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TaskQueuesStatisticsInstance, done: (err?: Error) => void) => void): void; + each(params: TaskQueuesStatisticsListInstanceEachOptions, callback?: (item: TaskQueuesStatisticsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TaskQueuesStatisticsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueuesStatisticsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TaskQueuesStatisticsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TaskQueuesStatisticsListInstanceEachOptions, callback?: (item: TaskQueuesStatisticsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TaskQueuesStatisticsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TaskQueuesStatisticsPage) => any): Promise<TaskQueuesStatisticsPage>; + /** + * Retrieve a single target page of TaskQueuesStatisticsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TaskQueuesStatisticsPage>) => any): Promise<ApiResponse<TaskQueuesStatisticsPage>>; + /** + * Lists TaskQueuesStatisticsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueuesStatisticsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TaskQueuesStatisticsInstance[]) => any): Promise<TaskQueuesStatisticsInstance[]>; + list(params: TaskQueuesStatisticsListInstanceOptions, callback?: (error: Error | null, items: TaskQueuesStatisticsInstance[]) => any): Promise<TaskQueuesStatisticsInstance[]>; + /** + * Lists TaskQueuesStatisticsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueuesStatisticsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TaskQueuesStatisticsInstance[]>) => any): Promise<ApiResponse<TaskQueuesStatisticsInstance[]>>; + listWithHttpInfo(params: TaskQueuesStatisticsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TaskQueuesStatisticsInstance[]>) => any): Promise<ApiResponse<TaskQueuesStatisticsInstance[]>>; + /** + * Retrieve a single page of TaskQueuesStatisticsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueuesStatisticsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TaskQueuesStatisticsPage) => any): Promise<TaskQueuesStatisticsPage>; + page(params: TaskQueuesStatisticsListInstancePageOptions, callback?: (error: Error | null, items: TaskQueuesStatisticsPage) => any): Promise<TaskQueuesStatisticsPage>; + /** + * Retrieve a single page of TaskQueuesStatisticsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TaskQueuesStatisticsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TaskQueuesStatisticsPage>) => any): Promise<ApiResponse<TaskQueuesStatisticsPage>>; + pageWithHttpInfo(params: TaskQueuesStatisticsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TaskQueuesStatisticsPage>) => any): Promise<ApiResponse<TaskQueuesStatisticsPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TaskQueuesStatisticsListInstance(version: V1, workspaceSid: string): TaskQueuesStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = {} as TaskQueuesStatisticsListInstance; + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = `/Workspaces/${workspaceSid}/TaskQueues/Statistics`; + + instance.page = function page(params?: TaskQueuesStatisticsListInstancePageOptions | ((error: Error | null, items: TaskQueuesStatisticsPage) => any), callback?: (error: Error | null, items: TaskQueuesStatisticsPage) => any): Promise<TaskQueuesStatisticsPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TaskQueuesStatisticsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TaskQueuesStatisticsPage) => any): Promise<TaskQueuesStatisticsPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TaskQueuesStatisticsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TaskQueuesStatisticsListInstancePageOptions | ((error: Error | null, items: ApiResponse<TaskQueuesStatisticsPage>) => any), callback?: (error: Error | null, items: ApiResponse<TaskQueuesStatisticsPage>) => any): Promise<ApiResponse<TaskQueuesStatisticsPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TaskQueuesStatisticsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TaskQueuesStatisticsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TaskQueuesStatisticsPage>) => any): Promise<ApiResponse<TaskQueuesStatisticsPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TaskQueuesStatisticsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TaskQueuesStatisticsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TaskQueuesStatisticsPayload extends TwilioResponsePayload { + task_queues_statistics: TaskQueuesStatisticsResource[]; +} + +interface TaskQueuesStatisticsResource { + account_sid: string; + cumulative: any; + realtime: any; + task_queue_sid: string; + workspace_sid: string; +} + +export class TaskQueuesStatisticsInstance { + + constructor(protected _version: V1, payload: TaskQueuesStatisticsResource, workspaceSid: string) { + + this.accountSid = (payload.account_sid); + this.cumulative = (payload.cumulative); + this.realtime = (payload.realtime); + this.taskQueueSid = (payload.task_queue_sid); + this.workspaceSid = (payload.workspace_sid); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + */ + accountSid: string; + /** + * An object that contains the cumulative statistics for the TaskQueues. + */ + cumulative: any; + /** + * An object that contains the real-time statistics for the TaskQueues. + */ + realtime: any; + /** + * The SID of the TaskQueue from which these statistics were calculated. + */ + taskQueueSid: string; + /** + * The SID of the Workspace that contains the TaskQueues. + */ + workspaceSid: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + cumulative: this.cumulative, + realtime: this.realtime, + taskQueueSid: this.taskQueueSid, + workspaceSid: this.workspaceSid, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class TaskQueuesStatisticsPage extends Page<V1, TaskQueuesStatisticsPayload, TaskQueuesStatisticsResource, TaskQueuesStatisticsInstance> { +/** +* Initialize the TaskQueuesStatisticsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TaskQueuesStatisticsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TaskQueuesStatisticsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TaskQueuesStatisticsResource): TaskQueuesStatisticsInstance { + + return new TaskQueuesStatisticsInstance( + this._version, + payload, + this._solution.workspaceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/worker.ts b/rest/taskrouter/v1/workspace/worker.ts new file mode 100644 index 000000000..bcb42abf2 --- /dev/null +++ b/rest/taskrouter/v1/workspace/worker.ts @@ -0,0 +1,1219 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { ReservationListInstance } from "./worker/reservation"; +import { WorkerChannelListInstance } from "./worker/workerChannel"; +import { WorkerStatisticsListInstance } from "./worker/workerStatistics"; +import { WorkersCumulativeStatisticsListInstance } from "./worker/workersCumulativeStatistics"; +import { WorkersRealTimeStatisticsListInstance } from "./worker/workersRealTimeStatistics"; +import { WorkersStatisticsListInstance } from "./worker/workersStatistics"; + + + +/** + * Options to pass to remove a WorkerInstance + */ +export interface WorkerContextRemoveOptions { + /** The If-Match HTTP request header */ + "ifMatch"?: string; +} + + +/** + * Options to pass to update a WorkerInstance + */ +export interface WorkerContextUpdateOptions { + /** The If-Match HTTP request header */ + "ifMatch"?: string; + /** The SID of a valid Activity that will describe the Worker\\\'s initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. */ + "activitySid"?: string; + /** The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. */ + "attributes"?: string; + /** A descriptive string that you create to describe the Worker. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** Whether to reject the Worker\\\'s pending reservations. This option is only valid if the Worker\\\'s new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. */ + "rejectPendingReservations"?: boolean; +} + +/** + * Options to pass to create a WorkerInstance + */ +export interface WorkerListInstanceCreateOptions { + /** A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. */ + "friendlyName": string; + /** The SID of a valid Activity that will describe the new Worker\\\'s initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker\\\'s initial state is the `default_activity_sid` configured on the Workspace. */ + "activitySid"?: string; + /** A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. */ + "attributes"?: string; +} + +/** + * Options to pass to each + */ +export interface WorkerListInstanceEachOptions { + /** The `activity_name` of the Worker resources to read. */ + "activityName"?: string; + /** The `activity_sid` of the Worker resources to read. */ + "activitySid"?: string; + /** Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. */ + "available"?: string; + /** The `friendly_name` of the Worker resources to read. */ + "friendlyName"?: string; + /** Filter by Workers that would match an expression. In addition to fields in the workers\' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` */ + "targetWorkersExpression"?: string; + /** The `friendly_name` of the TaskQueue that the Workers to read are eligible for. */ + "taskQueueName"?: string; + /** The SID of the TaskQueue that the Workers to read are eligible for. */ + "taskQueueSid"?: string; + /** Sorting parameter for Workers */ + "ordering"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: WorkerInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface WorkerListInstanceOptions { + /** The `activity_name` of the Worker resources to read. */ + "activityName"?: string; + /** The `activity_sid` of the Worker resources to read. */ + "activitySid"?: string; + /** Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. */ + "available"?: string; + /** The `friendly_name` of the Worker resources to read. */ + "friendlyName"?: string; + /** Filter by Workers that would match an expression. In addition to fields in the workers\' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` */ + "targetWorkersExpression"?: string; + /** The `friendly_name` of the TaskQueue that the Workers to read are eligible for. */ + "taskQueueName"?: string; + /** The SID of the TaskQueue that the Workers to read are eligible for. */ + "taskQueueSid"?: string; + /** Sorting parameter for Workers */ + "ordering"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface WorkerListInstancePageOptions { + /** The `activity_name` of the Worker resources to read. */ + "activityName"?: string; + /** The `activity_sid` of the Worker resources to read. */ + "activitySid"?: string; + /** Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. */ + "available"?: string; + /** The `friendly_name` of the Worker resources to read. */ + "friendlyName"?: string; + /** Filter by Workers that would match an expression. In addition to fields in the workers\' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` */ + "targetWorkersExpression"?: string; + /** The `friendly_name` of the TaskQueue that the Workers to read are eligible for. */ + "taskQueueName"?: string; + /** The SID of the TaskQueue that the Workers to read are eligible for. */ + "taskQueueSid"?: string; + /** Sorting parameter for Workers */ + "ordering"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface WorkerContext { + reservations: ReservationListInstance; + workerChannels: WorkerChannelListInstance; + statistics: WorkerStatisticsListInstance; + + /** + * Remove a WorkerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + /** + * Remove a WorkerInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance + */ + remove(params: WorkerContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + + /** + * Remove a WorkerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + /** + * Remove a WorkerInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance with HTTP metadata + */ + removeWithHttpInfo(params: WorkerContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + + /** + * Fetch a WorkerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance + */ + fetch(callback?: (error: Error | null, item?: WorkerInstance) => any): Promise<WorkerInstance> + + /** + * Fetch a WorkerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>> + + /** + * Update a WorkerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance + */ + update(callback?: (error: Error | null, item?: WorkerInstance) => any): Promise<WorkerInstance>; + /** + * Update a WorkerInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance + */ + update(params: WorkerContextUpdateOptions, callback?: (error: Error | null, item?: WorkerInstance) => any): Promise<WorkerInstance>; + + /** + * Update a WorkerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>>; + /** + * Update a WorkerInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance with HTTP metadata + */ + updateWithHttpInfo(params: WorkerContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkerContextSolution { + "workspaceSid": string; + "sid": string; +} + +export class WorkerContextImpl implements WorkerContext { + protected _solution: WorkerContextSolution; + protected _uri: string; + + protected _reservations?: ReservationListInstance; + protected _workerChannels?: WorkerChannelListInstance; + protected _statistics?: WorkerStatisticsListInstance; + + constructor(protected _version: V1, workspaceSid: string, sid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { workspaceSid, sid, }; + this._uri = `/Workspaces/${workspaceSid}/Workers/${sid}`; + } + + get reservations(): ReservationListInstance { + this._reservations = this._reservations || ReservationListInstance(this._version, this._solution.workspaceSid, this._solution.sid); + return this._reservations; + } + + get workerChannels(): WorkerChannelListInstance { + this._workerChannels = this._workerChannels || WorkerChannelListInstance(this._version, this._solution.workspaceSid, this._solution.sid); + return this._workerChannels; + } + + get statistics(): WorkerStatisticsListInstance { + this._statistics = this._statistics || WorkerStatisticsListInstance(this._version, this._solution.workspaceSid, this._solution.sid); + return this._statistics; + } + + remove(params?: WorkerContextRemoveOptions | ((error: Error | null, item?: boolean) => any),callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", params: data, headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(params?: WorkerContextRemoveOptions | ((error: Error | null, item?: ApiResponse<boolean>) => any),callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + + + + + const headers: any = {}; + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", params: data, headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: WorkerInstance) => any): Promise<WorkerInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WorkerInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkerResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<WorkerInstance> => ({ + ...response, + body: new WorkerInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WorkerContextUpdateOptions | ((error: Error | null, item?: WorkerInstance) => any),callback?: (error: Error | null, item?: WorkerInstance) => any): Promise<WorkerInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["activitySid"] !== undefined) + data["ActivitySid"] = params["activitySid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["rejectPendingReservations"] !== undefined) + data["RejectPendingReservations"] = serialize.bool(params["rejectPendingReservations"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WorkerInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WorkerContextUpdateOptions | ((error: Error | null, item?: ApiResponse<WorkerInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["activitySid"] !== undefined) + data["ActivitySid"] = params["activitySid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["rejectPendingReservations"] !== undefined) + data["RejectPendingReservations"] = serialize.bool(params["rejectPendingReservations"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<WorkerResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<WorkerInstance> => ({ + ...response, + body: new WorkerInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkerPayload extends TwilioResponsePayload { + workers: WorkerResource[]; +} + +interface WorkerResource { + account_sid: string; + activity_name: string; + activity_sid: string; + attributes: string; + available: boolean; + date_created: Date; + date_status_changed: Date; + date_updated: Date; + friendly_name: string; + sid: string; + workspace_sid: string; + url: string; + links: Record<string, string>; +} + +export class WorkerInstance { + protected _solution: WorkerContextSolution; + protected _context?: WorkerContext; + + constructor(protected _version: V1, payload: WorkerResource, workspaceSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.activityName = (payload.activity_name); + this.activitySid = (payload.activity_sid); + this.attributes = (payload.attributes); + this.available = (payload.available); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateStatusChanged = deserialize.iso8601DateTime(payload.date_status_changed); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { workspaceSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + */ + accountSid: string; + /** + * The `friendly_name` of the Worker\'s current Activity. + */ + activityName: string; + /** + * The SID of the Worker\'s current Activity. + */ + activitySid: string; + /** + * The JSON string that describes the Worker. For example: `{ \"email\": \"Bob@example.com\", \"phone\": \"+5095551234\" }`. **Note** If this property has been assigned a value, it will only be displayed in FETCH actions that return a single resource. Otherwise, this property will be null, even if it has a value. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. + */ + attributes: string; + /** + * Whether the Worker is available to perform tasks. + */ + available: boolean; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT of the last change to the Worker\'s activity specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Used to calculate Workflow statistics. + */ + dateStatusChanged: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. Friendly names are case insensitive, and unique within the TaskRouter Workspace. + */ + friendlyName: string; + /** + * The unique string that we created to identify the Worker resource. + */ + sid: string; + /** + * The SID of the Workspace that contains the Worker. + */ + workspaceSid: string; + /** + * The absolute URL of the Worker resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): WorkerContext { + this._context = this._context || new WorkerContextImpl(this._version, this._solution.workspaceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a WorkerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + /** + * Remove a WorkerInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance + */ + remove(params: WorkerContextRemoveOptions, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean>; + + remove(params?: any, callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + { + return this._proxy.remove(params, callback); + } + + /** + * Remove a WorkerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + /** + * Remove a WorkerInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance with HTTP metadata + */ + removeWithHttpInfo(params: WorkerContextRemoveOptions, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>>; + + removeWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + { + return this._proxy.removeWithHttpInfo(params, callback); + } + + /** + * Fetch a WorkerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance + */ + fetch(callback?: (error: Error | null, item?: WorkerInstance) => any): Promise<WorkerInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WorkerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WorkerInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance + */ + update(callback?: (error: Error | null, item?: WorkerInstance) => any): Promise<WorkerInstance>; + /** + * Update a WorkerInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance + */ + update(params: WorkerContextUpdateOptions, callback?: (error: Error | null, item?: WorkerInstance) => any): Promise<WorkerInstance>; + + update(params?: any, callback?: (error: Error | null, item?: WorkerInstance) => any): Promise<WorkerInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a WorkerInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>>; + /** + * Update a WorkerInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance with HTTP metadata + */ + updateWithHttpInfo(params: WorkerContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the reservations. + */ + reservations(): ReservationListInstance { + return this._proxy.reservations; + } + + /** + * Access the workerChannels. + */ + workerChannels(): WorkerChannelListInstance { + return this._proxy.workerChannels; + } + + /** + * Access the statistics. + */ + statistics(): WorkerStatisticsListInstance { + return this._proxy.statistics; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + activityName: this.activityName, + activitySid: this.activitySid, + attributes: this.attributes, + available: this.available, + dateCreated: this.dateCreated, + dateStatusChanged: this.dateStatusChanged, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + sid: this.sid, + workspaceSid: this.workspaceSid, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkerSolution { + workspaceSid: string; +} + +export interface WorkerListInstance { + _version: V1; + _solution: WorkerSolution; + _uri: string; + + (sid: string, ): WorkerContext; + get(sid: string, ): WorkerContext; + + _cumulativeStatistics?: WorkersCumulativeStatisticsListInstance; + cumulativeStatistics: WorkersCumulativeStatisticsListInstance; + _realTimeStatistics?: WorkersRealTimeStatisticsListInstance; + realTimeStatistics: WorkersRealTimeStatisticsListInstance; + _statistics?: WorkersStatisticsListInstance; + statistics: WorkersStatisticsListInstance; + + + + + + + + /** + * Create a WorkerInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance + */ + create(params: WorkerListInstanceCreateOptions, callback?: (error: Error | null, item?: WorkerInstance) => any): Promise<WorkerInstance>; + + /** + * Create a WorkerInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerInstance with HTTP metadata + */ + createWithHttpInfo(params: WorkerListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>>; + + + + + /** + * Streams WorkerInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: WorkerInstance, done: (err?: Error) => void) => void): void; + each(params: WorkerListInstanceEachOptions, callback?: (item: WorkerInstance, done: (err?: Error) => void) => void): void; + /** + * Streams WorkerInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: WorkerInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: WorkerListInstanceEachOptions, callback?: (item: WorkerInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of WorkerInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: WorkerPage) => any): Promise<WorkerPage>; + /** + * Retrieve a single target page of WorkerInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<WorkerPage>) => any): Promise<ApiResponse<WorkerPage>>; + /** + * Lists WorkerInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: WorkerInstance[]) => any): Promise<WorkerInstance[]>; + list(params: WorkerListInstanceOptions, callback?: (error: Error | null, items: WorkerInstance[]) => any): Promise<WorkerInstance[]>; + /** + * Lists WorkerInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<WorkerInstance[]>) => any): Promise<ApiResponse<WorkerInstance[]>>; + listWithHttpInfo(params: WorkerListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<WorkerInstance[]>) => any): Promise<ApiResponse<WorkerInstance[]>>; + /** + * Retrieve a single page of WorkerInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: WorkerPage) => any): Promise<WorkerPage>; + page(params: WorkerListInstancePageOptions, callback?: (error: Error | null, items: WorkerPage) => any): Promise<WorkerPage>; + /** + * Retrieve a single page of WorkerInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<WorkerPage>) => any): Promise<ApiResponse<WorkerPage>>; + pageWithHttpInfo(params: WorkerListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<WorkerPage>) => any): Promise<ApiResponse<WorkerPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkerListInstance(version: V1, workspaceSid: string): WorkerListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as WorkerListInstance; + + instance.get = function get(sid, ): WorkerContext { + return new WorkerContextImpl(version, workspaceSid, sid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = `/Workspaces/${workspaceSid}/Workers`; + + Object.defineProperty(instance, "cumulativeStatistics", { + get: function cumulativeStatistics() { + if (!instance._cumulativeStatistics) { + instance._cumulativeStatistics = WorkersCumulativeStatisticsListInstance(instance._version, instance._solution.workspaceSid); + } + return instance._cumulativeStatistics; + } + }); + + Object.defineProperty(instance, "realTimeStatistics", { + get: function realTimeStatistics() { + if (!instance._realTimeStatistics) { + instance._realTimeStatistics = WorkersRealTimeStatisticsListInstance(instance._version, instance._solution.workspaceSid); + } + return instance._realTimeStatistics; + } + }); + + Object.defineProperty(instance, "statistics", { + get: function statistics() { + if (!instance._statistics) { + instance._statistics = WorkersStatisticsListInstance(instance._version, instance._solution.workspaceSid); + } + return instance._statistics; + } + }); + + instance.create = function create(params: WorkerListInstanceCreateOptions, callback?: (error: Error | null, items: WorkerInstance) => any): Promise<WorkerInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["activitySid"] !== undefined) + data["ActivitySid"] = params["activitySid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WorkerInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: WorkerListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<WorkerInstance>) => any): Promise<ApiResponse<WorkerInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["activitySid"] !== undefined) + data["ActivitySid"] = params["activitySid"]; + if (params["attributes"] !== undefined) + data["Attributes"] = params["attributes"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<WorkerResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<WorkerInstance> => ({ + ...response, + body: new WorkerInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: WorkerListInstancePageOptions | ((error: Error | null, items: WorkerPage) => any), callback?: (error: Error | null, items: WorkerPage) => any): Promise<WorkerPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["activityName"] !== undefined) + data["ActivityName"] = params["activityName"]; + if (params["activitySid"] !== undefined) + data["ActivitySid"] = params["activitySid"]; + if (params["available"] !== undefined) + data["Available"] = params["available"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["targetWorkersExpression"] !== undefined) + data["TargetWorkersExpression"] = params["targetWorkersExpression"]; + if (params["taskQueueName"] !== undefined) + data["TaskQueueName"] = params["taskQueueName"]; + if (params["taskQueueSid"] !== undefined) + data["TaskQueueSid"] = params["taskQueueSid"]; + if (params["ordering"] !== undefined) + data["Ordering"] = params["ordering"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new WorkerPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: WorkerPage) => any): Promise<WorkerPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new WorkerPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: WorkerListInstancePageOptions | ((error: Error | null, items: ApiResponse<WorkerPage>) => any), callback?: (error: Error | null, items: ApiResponse<WorkerPage>) => any): Promise<ApiResponse<WorkerPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["activityName"] !== undefined) + data["ActivityName"] = params["activityName"]; + if (params["activitySid"] !== undefined) + data["ActivitySid"] = params["activitySid"]; + if (params["available"] !== undefined) + data["Available"] = params["available"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["targetWorkersExpression"] !== undefined) + data["TargetWorkersExpression"] = params["targetWorkersExpression"]; + if (params["taskQueueName"] !== undefined) + data["TaskQueueName"] = params["taskQueueName"]; + if (params["taskQueueSid"] !== undefined) + data["TaskQueueSid"] = params["taskQueueSid"]; + if (params["ordering"] !== undefined) + data["Ordering"] = params["ordering"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkerPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WorkerPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<WorkerPage>) => any): Promise<ApiResponse<WorkerPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<WorkerPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WorkerPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class WorkerPage extends Page<V1, WorkerPayload, WorkerResource, WorkerInstance> { +/** +* Initialize the WorkerPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: WorkerSolution) { + super(version, response, solution); + } + + /** + * Build an instance of WorkerInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: WorkerResource): WorkerInstance { + + return new WorkerInstance( + this._version, + payload, + this._solution.workspaceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/worker/reservation.ts b/rest/taskrouter/v1/workspace/worker/reservation.ts new file mode 100644 index 000000000..cc8176d55 --- /dev/null +++ b/rest/taskrouter/v1/workspace/worker/reservation.ts @@ -0,0 +1,1095 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export type ReservationCallStatus = 'initiated'|'ringing'|'answered'|'completed'; + +export type ReservationConferenceEvent = 'start'|'end'|'join'|'leave'|'mute'|'hold'|'speaker'; + +/** + * The current status of the reservation. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + */ +export type ReservationStatus = 'pending'|'accepted'|'rejected'|'timeout'|'canceled'|'rescinded'|'wrapping'|'completed'; + + + +/** + * Options to pass to update a ReservationInstance + */ +export interface ReservationContextUpdateOptions { + /** The If-Match HTTP request header */ + "ifMatch"?: string; + /** */ + "reservationStatus"?: ReservationStatus; + /** The new worker activity SID if rejecting a reservation. */ + "workerActivitySid"?: string; + /** The assignment instruction for the reservation. */ + "instruction"?: string; + /** The SID of the Activity resource to start after executing a Dequeue instruction. */ + "dequeuePostWorkActivitySid"?: string; + /** The caller ID of the call to the worker when executing a Dequeue instruction. */ + "dequeueFrom"?: string; + /** Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. */ + "dequeueRecord"?: string; + /** The timeout for call when executing a Dequeue instruction. */ + "dequeueTimeout"?: number; + /** The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. */ + "dequeueTo"?: string; + /** The callback URL for completed call event when executing a Dequeue instruction. */ + "dequeueStatusCallbackUrl"?: string; + /** The Caller ID of the outbound call when executing a Call instruction. */ + "callFrom"?: string; + /** Whether to record both legs of a call when executing a Call instruction. */ + "callRecord"?: string; + /** The timeout for a call when executing a Call instruction. */ + "callTimeout"?: number; + /** The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. */ + "callTo"?: string; + /** TwiML URI executed on answering the worker\\\'s leg as a result of the Call instruction. */ + "callUrl"?: string; + /** The URL to call for the completed call event when executing a Call instruction. */ + "callStatusCallbackUrl"?: string; + /** Whether to accept a reservation when executing a Call instruction. */ + "callAccept"?: boolean; + /** The Call SID of the call parked in the queue when executing a Redirect instruction. */ + "redirectCallSid"?: string; + /** Whether the reservation should be accepted when executing a Redirect instruction. */ + "redirectAccept"?: boolean; + /** TwiML URI to redirect the call to when executing the Redirect instruction. */ + "redirectUrl"?: string; + /** The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. */ + "to"?: string; + /** The caller ID of the call to the worker when executing a Conference instruction. */ + "from"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. */ + "statusCallbackMethod"?: string; + /** The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. */ + "statusCallbackEvent"?: Array<ReservationCallStatus>; + /** The timeout for a call when executing a Conference instruction. */ + "timeout"?: number; + /** Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. */ + "record"?: boolean; + /** Whether the agent is muted in the conference. Defaults to `false`. */ + "muted"?: boolean; + /** Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. */ + "beep"?: string; + /** Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. */ + "startConferenceOnEnter"?: boolean; + /** Whether to end the conference when the agent leaves. */ + "endConferenceOnExit"?: boolean; + /** The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). */ + "waitUrl"?: string; + /** The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. */ + "waitMethod"?: string; + /** Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. */ + "earlyMedia"?: boolean; + /** The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. */ + "maxParticipants"?: number; + /** The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. */ + "conferenceStatusCallback"?: string; + /** The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "conferenceStatusCallbackMethod"?: string; + /** The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. */ + "conferenceStatusCallbackEvent"?: Array<ReservationConferenceEvent>; + /** Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. */ + "conferenceRecord"?: string; + /** Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. */ + "conferenceTrim"?: string; + /** The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. */ + "recordingChannels"?: string; + /** The URL that we should call using the `recording_status_callback_method` when the recording status changes. */ + "recordingStatusCallback"?: string; + /** The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "recordingStatusCallbackMethod"?: string; + /** The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. */ + "conferenceRecordingStatusCallback"?: string; + /** The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. */ + "conferenceRecordingStatusCallbackMethod"?: string; + /** The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. */ + "region"?: string; + /** The SIP username used for authentication. */ + "sipAuthUsername"?: string; + /** The SIP password for authentication. */ + "sipAuthPassword"?: string; + /** The call progress events sent via webhooks as a result of a Dequeue instruction. */ + "dequeueStatusCallbackEvent"?: Array<string>; + /** The new worker activity SID after executing a Conference instruction. */ + "postWorkActivitySid"?: string; + /** Whether to end the conference when the customer leaves. */ + "endConferenceOnCustomerExit"?: boolean; + /** Whether to play a notification beep when the customer joins. */ + "beepOnCustomerEntrance"?: boolean; + /** The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. */ + "jitterBufferSize"?: string; +} + +/** + * Options to pass to each + */ +export interface ReservationListInstanceEachOptions { + /** Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. */ + "reservationStatus"?: ReservationStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ReservationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ReservationListInstanceOptions { + /** Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. */ + "reservationStatus"?: ReservationStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ReservationListInstancePageOptions { + /** Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. */ + "reservationStatus"?: ReservationStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ReservationContext { + + /** + * Fetch a ReservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + fetch(callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance> + + /** + * Fetch a ReservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>> + + /** + * Update a ReservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + update(callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance>; + /** + * Update a ReservationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + update(params: ReservationContextUpdateOptions, callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance>; + + /** + * Update a ReservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>>; + /** + * Update a ReservationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ReservationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ReservationContextSolution { + "workspaceSid": string; + "workerSid": string; + "sid": string; +} + +export class ReservationContextImpl implements ReservationContext { + protected _solution: ReservationContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, workerSid: string, sid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workerSid)) { + throw new Error('Parameter \'workerSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { workspaceSid, workerSid, sid, }; + this._uri = `/Workspaces/${workspaceSid}/Workers/${workerSid}/Reservations/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ReservationInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.workerSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ReservationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ReservationInstance> => ({ + ...response, + body: new ReservationInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.workerSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ReservationContextUpdateOptions | ((error: Error | null, item?: ReservationInstance) => any),callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["reservationStatus"] !== undefined) + data["ReservationStatus"] = params["reservationStatus"]; + if (params["workerActivitySid"] !== undefined) + data["WorkerActivitySid"] = params["workerActivitySid"]; + if (params["instruction"] !== undefined) + data["Instruction"] = params["instruction"]; + if (params["dequeuePostWorkActivitySid"] !== undefined) + data["DequeuePostWorkActivitySid"] = params["dequeuePostWorkActivitySid"]; + if (params["dequeueFrom"] !== undefined) + data["DequeueFrom"] = params["dequeueFrom"]; + if (params["dequeueRecord"] !== undefined) + data["DequeueRecord"] = params["dequeueRecord"]; + if (params["dequeueTimeout"] !== undefined) + data["DequeueTimeout"] = params["dequeueTimeout"]; + if (params["dequeueTo"] !== undefined) + data["DequeueTo"] = params["dequeueTo"]; + if (params["dequeueStatusCallbackUrl"] !== undefined) + data["DequeueStatusCallbackUrl"] = params["dequeueStatusCallbackUrl"]; + if (params["callFrom"] !== undefined) + data["CallFrom"] = params["callFrom"]; + if (params["callRecord"] !== undefined) + data["CallRecord"] = params["callRecord"]; + if (params["callTimeout"] !== undefined) + data["CallTimeout"] = params["callTimeout"]; + if (params["callTo"] !== undefined) + data["CallTo"] = params["callTo"]; + if (params["callUrl"] !== undefined) + data["CallUrl"] = params["callUrl"]; + if (params["callStatusCallbackUrl"] !== undefined) + data["CallStatusCallbackUrl"] = params["callStatusCallbackUrl"]; + if (params["callAccept"] !== undefined) + data["CallAccept"] = serialize.bool(params["callAccept"]); + if (params["redirectCallSid"] !== undefined) + data["RedirectCallSid"] = params["redirectCallSid"]; + if (params["redirectAccept"] !== undefined) + data["RedirectAccept"] = serialize.bool(params["redirectAccept"]); + if (params["redirectUrl"] !== undefined) + data["RedirectUrl"] = params["redirectUrl"]; + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["statusCallbackEvent"] !== undefined) + data["StatusCallbackEvent"] = serialize.map(params["statusCallbackEvent"], (e: ReservationCallStatus) => (e)); + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["record"] !== undefined) + data["Record"] = serialize.bool(params["record"]); + if (params["muted"] !== undefined) + data["Muted"] = serialize.bool(params["muted"]); + if (params["beep"] !== undefined) + data["Beep"] = params["beep"]; + if (params["startConferenceOnEnter"] !== undefined) + data["StartConferenceOnEnter"] = serialize.bool(params["startConferenceOnEnter"]); + if (params["endConferenceOnExit"] !== undefined) + data["EndConferenceOnExit"] = serialize.bool(params["endConferenceOnExit"]); + if (params["waitUrl"] !== undefined) + data["WaitUrl"] = params["waitUrl"]; + if (params["waitMethod"] !== undefined) + data["WaitMethod"] = params["waitMethod"]; + if (params["earlyMedia"] !== undefined) + data["EarlyMedia"] = serialize.bool(params["earlyMedia"]); + if (params["maxParticipants"] !== undefined) + data["MaxParticipants"] = params["maxParticipants"]; + if (params["conferenceStatusCallback"] !== undefined) + data["ConferenceStatusCallback"] = params["conferenceStatusCallback"]; + if (params["conferenceStatusCallbackMethod"] !== undefined) + data["ConferenceStatusCallbackMethod"] = params["conferenceStatusCallbackMethod"]; + if (params["conferenceStatusCallbackEvent"] !== undefined) + data["ConferenceStatusCallbackEvent"] = serialize.map(params["conferenceStatusCallbackEvent"], (e: ReservationConferenceEvent) => (e)); + if (params["conferenceRecord"] !== undefined) + data["ConferenceRecord"] = params["conferenceRecord"]; + if (params["conferenceTrim"] !== undefined) + data["ConferenceTrim"] = params["conferenceTrim"]; + if (params["recordingChannels"] !== undefined) + data["RecordingChannels"] = params["recordingChannels"]; + if (params["recordingStatusCallback"] !== undefined) + data["RecordingStatusCallback"] = params["recordingStatusCallback"]; + if (params["recordingStatusCallbackMethod"] !== undefined) + data["RecordingStatusCallbackMethod"] = params["recordingStatusCallbackMethod"]; + if (params["conferenceRecordingStatusCallback"] !== undefined) + data["ConferenceRecordingStatusCallback"] = params["conferenceRecordingStatusCallback"]; + if (params["conferenceRecordingStatusCallbackMethod"] !== undefined) + data["ConferenceRecordingStatusCallbackMethod"] = params["conferenceRecordingStatusCallbackMethod"]; + if (params["region"] !== undefined) + data["Region"] = params["region"]; + if (params["sipAuthUsername"] !== undefined) + data["SipAuthUsername"] = params["sipAuthUsername"]; + if (params["sipAuthPassword"] !== undefined) + data["SipAuthPassword"] = params["sipAuthPassword"]; + if (params["dequeueStatusCallbackEvent"] !== undefined) + data["DequeueStatusCallbackEvent"] = serialize.map(params["dequeueStatusCallbackEvent"], (e: string) => (e)); + if (params["postWorkActivitySid"] !== undefined) + data["PostWorkActivitySid"] = params["postWorkActivitySid"]; + if (params["endConferenceOnCustomerExit"] !== undefined) + data["EndConferenceOnCustomerExit"] = serialize.bool(params["endConferenceOnCustomerExit"]); + if (params["beepOnCustomerEntrance"] !== undefined) + data["BeepOnCustomerEntrance"] = serialize.bool(params["beepOnCustomerEntrance"]); + if (params["jitterBufferSize"] !== undefined) + data["JitterBufferSize"] = params["jitterBufferSize"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ReservationInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.workerSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ReservationContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ReservationInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["reservationStatus"] !== undefined) + data["ReservationStatus"] = params["reservationStatus"]; + if (params["workerActivitySid"] !== undefined) + data["WorkerActivitySid"] = params["workerActivitySid"]; + if (params["instruction"] !== undefined) + data["Instruction"] = params["instruction"]; + if (params["dequeuePostWorkActivitySid"] !== undefined) + data["DequeuePostWorkActivitySid"] = params["dequeuePostWorkActivitySid"]; + if (params["dequeueFrom"] !== undefined) + data["DequeueFrom"] = params["dequeueFrom"]; + if (params["dequeueRecord"] !== undefined) + data["DequeueRecord"] = params["dequeueRecord"]; + if (params["dequeueTimeout"] !== undefined) + data["DequeueTimeout"] = params["dequeueTimeout"]; + if (params["dequeueTo"] !== undefined) + data["DequeueTo"] = params["dequeueTo"]; + if (params["dequeueStatusCallbackUrl"] !== undefined) + data["DequeueStatusCallbackUrl"] = params["dequeueStatusCallbackUrl"]; + if (params["callFrom"] !== undefined) + data["CallFrom"] = params["callFrom"]; + if (params["callRecord"] !== undefined) + data["CallRecord"] = params["callRecord"]; + if (params["callTimeout"] !== undefined) + data["CallTimeout"] = params["callTimeout"]; + if (params["callTo"] !== undefined) + data["CallTo"] = params["callTo"]; + if (params["callUrl"] !== undefined) + data["CallUrl"] = params["callUrl"]; + if (params["callStatusCallbackUrl"] !== undefined) + data["CallStatusCallbackUrl"] = params["callStatusCallbackUrl"]; + if (params["callAccept"] !== undefined) + data["CallAccept"] = serialize.bool(params["callAccept"]); + if (params["redirectCallSid"] !== undefined) + data["RedirectCallSid"] = params["redirectCallSid"]; + if (params["redirectAccept"] !== undefined) + data["RedirectAccept"] = serialize.bool(params["redirectAccept"]); + if (params["redirectUrl"] !== undefined) + data["RedirectUrl"] = params["redirectUrl"]; + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["from"] !== undefined) + data["From"] = params["from"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["statusCallbackEvent"] !== undefined) + data["StatusCallbackEvent"] = serialize.map(params["statusCallbackEvent"], (e: ReservationCallStatus) => (e)); + if (params["timeout"] !== undefined) + data["Timeout"] = params["timeout"]; + if (params["record"] !== undefined) + data["Record"] = serialize.bool(params["record"]); + if (params["muted"] !== undefined) + data["Muted"] = serialize.bool(params["muted"]); + if (params["beep"] !== undefined) + data["Beep"] = params["beep"]; + if (params["startConferenceOnEnter"] !== undefined) + data["StartConferenceOnEnter"] = serialize.bool(params["startConferenceOnEnter"]); + if (params["endConferenceOnExit"] !== undefined) + data["EndConferenceOnExit"] = serialize.bool(params["endConferenceOnExit"]); + if (params["waitUrl"] !== undefined) + data["WaitUrl"] = params["waitUrl"]; + if (params["waitMethod"] !== undefined) + data["WaitMethod"] = params["waitMethod"]; + if (params["earlyMedia"] !== undefined) + data["EarlyMedia"] = serialize.bool(params["earlyMedia"]); + if (params["maxParticipants"] !== undefined) + data["MaxParticipants"] = params["maxParticipants"]; + if (params["conferenceStatusCallback"] !== undefined) + data["ConferenceStatusCallback"] = params["conferenceStatusCallback"]; + if (params["conferenceStatusCallbackMethod"] !== undefined) + data["ConferenceStatusCallbackMethod"] = params["conferenceStatusCallbackMethod"]; + if (params["conferenceStatusCallbackEvent"] !== undefined) + data["ConferenceStatusCallbackEvent"] = serialize.map(params["conferenceStatusCallbackEvent"], (e: ReservationConferenceEvent) => (e)); + if (params["conferenceRecord"] !== undefined) + data["ConferenceRecord"] = params["conferenceRecord"]; + if (params["conferenceTrim"] !== undefined) + data["ConferenceTrim"] = params["conferenceTrim"]; + if (params["recordingChannels"] !== undefined) + data["RecordingChannels"] = params["recordingChannels"]; + if (params["recordingStatusCallback"] !== undefined) + data["RecordingStatusCallback"] = params["recordingStatusCallback"]; + if (params["recordingStatusCallbackMethod"] !== undefined) + data["RecordingStatusCallbackMethod"] = params["recordingStatusCallbackMethod"]; + if (params["conferenceRecordingStatusCallback"] !== undefined) + data["ConferenceRecordingStatusCallback"] = params["conferenceRecordingStatusCallback"]; + if (params["conferenceRecordingStatusCallbackMethod"] !== undefined) + data["ConferenceRecordingStatusCallbackMethod"] = params["conferenceRecordingStatusCallbackMethod"]; + if (params["region"] !== undefined) + data["Region"] = params["region"]; + if (params["sipAuthUsername"] !== undefined) + data["SipAuthUsername"] = params["sipAuthUsername"]; + if (params["sipAuthPassword"] !== undefined) + data["SipAuthPassword"] = params["sipAuthPassword"]; + if (params["dequeueStatusCallbackEvent"] !== undefined) + data["DequeueStatusCallbackEvent"] = serialize.map(params["dequeueStatusCallbackEvent"], (e: string) => (e)); + if (params["postWorkActivitySid"] !== undefined) + data["PostWorkActivitySid"] = params["postWorkActivitySid"]; + if (params["endConferenceOnCustomerExit"] !== undefined) + data["EndConferenceOnCustomerExit"] = serialize.bool(params["endConferenceOnCustomerExit"]); + if (params["beepOnCustomerEntrance"] !== undefined) + data["BeepOnCustomerEntrance"] = serialize.bool(params["beepOnCustomerEntrance"]); + if (params["jitterBufferSize"] !== undefined) + data["JitterBufferSize"] = params["jitterBufferSize"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + if (params["ifMatch"] !== undefined) headers["If-Match"] = params["ifMatch"]; + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ReservationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ReservationInstance> => ({ + ...response, + body: new ReservationInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.workerSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ReservationPayload extends TwilioResponsePayload { + reservations: ReservationResource[]; +} + +interface ReservationResource { + account_sid: string; + date_created: Date; + date_updated: Date; + reservation_status: ReservationStatus; + sid: string; + task_sid: string; + worker_name: string; + worker_sid: string; + workspace_sid: string; + url: string; + links: Record<string, string>; +} + +export class ReservationInstance { + protected _solution: ReservationContextSolution; + protected _context?: ReservationContext; + + constructor(protected _version: V1, payload: ReservationResource, workspaceSid: string, workerSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.reservationStatus = payload.reservation_status; + this.sid = (payload.sid); + this.taskSid = (payload.task_sid); + this.workerName = (payload.worker_name); + this.workerSid = (payload.worker_sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { workspaceSid, workerSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the WorkerReservation resource. + */ + accountSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + reservationStatus: ReservationStatus; + /** + * The unique string that we created to identify the WorkerReservation resource. + */ + sid: string; + /** + * The SID of the reserved Task resource. + */ + taskSid: string; + /** + * The `friendly_name` of the Worker that is reserved. + */ + workerName: string; + /** + * The SID of the reserved Worker resource. + */ + workerSid: string; + /** + * The SID of the Workspace that this worker is contained within. + */ + workspaceSid: string; + /** + * The absolute URL of the WorkerReservation resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): ReservationContext { + this._context = this._context || new ReservationContextImpl(this._version, this._solution.workspaceSid, this._solution.workerSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a ReservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + fetch(callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ReservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ReservationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + update(callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance>; + /** + * Update a ReservationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance + */ + update(params: ReservationContextUpdateOptions, callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ReservationInstance) => any): Promise<ReservationInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ReservationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>>; + /** + * Update a ReservationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ReservationInstance with HTTP metadata + */ + updateWithHttpInfo(params: ReservationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ReservationInstance>) => any): Promise<ApiResponse<ReservationInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + reservationStatus: this.reservationStatus, + sid: this.sid, + taskSid: this.taskSid, + workerName: this.workerName, + workerSid: this.workerSid, + workspaceSid: this.workspaceSid, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ReservationSolution { + workspaceSid: string; + workerSid: string; +} + +export interface ReservationListInstance { + _version: V1; + _solution: ReservationSolution; + _uri: string; + + (sid: string, ): ReservationContext; + get(sid: string, ): ReservationContext; + + + + + + + + /** + * Streams ReservationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ReservationInstance, done: (err?: Error) => void) => void): void; + each(params: ReservationListInstanceEachOptions, callback?: (item: ReservationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ReservationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ReservationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ReservationListInstanceEachOptions, callback?: (item: ReservationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ReservationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage>; + /** + * Retrieve a single target page of ReservationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ReservationPage>) => any): Promise<ApiResponse<ReservationPage>>; + /** + * Lists ReservationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ReservationInstance[]) => any): Promise<ReservationInstance[]>; + list(params: ReservationListInstanceOptions, callback?: (error: Error | null, items: ReservationInstance[]) => any): Promise<ReservationInstance[]>; + /** + * Lists ReservationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ReservationInstance[]>) => any): Promise<ApiResponse<ReservationInstance[]>>; + listWithHttpInfo(params: ReservationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ReservationInstance[]>) => any): Promise<ApiResponse<ReservationInstance[]>>; + /** + * Retrieve a single page of ReservationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage>; + page(params: ReservationListInstancePageOptions, callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage>; + /** + * Retrieve a single page of ReservationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ReservationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ReservationPage>) => any): Promise<ApiResponse<ReservationPage>>; + pageWithHttpInfo(params: ReservationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ReservationPage>) => any): Promise<ApiResponse<ReservationPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ReservationListInstance(version: V1, workspaceSid: string, workerSid: string): ReservationListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workerSid)) { + throw new Error('Parameter \'workerSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ReservationListInstance; + + instance.get = function get(sid, ): ReservationContext { + return new ReservationContextImpl(version, workspaceSid, workerSid, sid); + } + + instance._version = version; + instance._solution = { workspaceSid, workerSid, }; + instance._uri = `/Workspaces/${workspaceSid}/Workers/${workerSid}/Reservations`; + + instance.page = function page(params?: ReservationListInstancePageOptions | ((error: Error | null, items: ReservationPage) => any), callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["reservationStatus"] !== undefined) + data["ReservationStatus"] = params["reservationStatus"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ReservationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ReservationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ReservationListInstancePageOptions | ((error: Error | null, items: ApiResponse<ReservationPage>) => any), callback?: (error: Error | null, items: ApiResponse<ReservationPage>) => any): Promise<ApiResponse<ReservationPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["reservationStatus"] !== undefined) + data["ReservationStatus"] = params["reservationStatus"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ReservationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ReservationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ReservationPage>) => any): Promise<ApiResponse<ReservationPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ReservationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ReservationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ReservationPage extends Page<V1, ReservationPayload, ReservationResource, ReservationInstance> { +/** +* Initialize the ReservationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ReservationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ReservationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ReservationResource): ReservationInstance { + + return new ReservationInstance( + this._version, + payload, + this._solution.workspaceSid, + this._solution.workerSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/worker/workerChannel.ts b/rest/taskrouter/v1/workspace/worker/workerChannel.ts new file mode 100644 index 000000000..b2d88ef9f --- /dev/null +++ b/rest/taskrouter/v1/workspace/worker/workerChannel.ts @@ -0,0 +1,789 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a WorkerChannelInstance + */ +export interface WorkerChannelContextUpdateOptions { + /** The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. */ + "capacity"?: number; + /** Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. */ + "available"?: boolean; +} + +/** + * Options to pass to each + */ +export interface WorkerChannelListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: WorkerChannelInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface WorkerChannelListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface WorkerChannelListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface WorkerChannelContext { + + /** + * Fetch a WorkerChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance + */ + fetch(callback?: (error: Error | null, item?: WorkerChannelInstance) => any): Promise<WorkerChannelInstance> + + /** + * Fetch a WorkerChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerChannelInstance>) => any): Promise<ApiResponse<WorkerChannelInstance>> + + /** + * Update a WorkerChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance + */ + update(callback?: (error: Error | null, item?: WorkerChannelInstance) => any): Promise<WorkerChannelInstance>; + /** + * Update a WorkerChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance + */ + update(params: WorkerChannelContextUpdateOptions, callback?: (error: Error | null, item?: WorkerChannelInstance) => any): Promise<WorkerChannelInstance>; + + /** + * Update a WorkerChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerChannelInstance>) => any): Promise<ApiResponse<WorkerChannelInstance>>; + /** + * Update a WorkerChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: WorkerChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkerChannelInstance>) => any): Promise<ApiResponse<WorkerChannelInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkerChannelContextSolution { + "workspaceSid": string; + "workerSid": string; + "sid": string; +} + +export class WorkerChannelContextImpl implements WorkerChannelContext { + protected _solution: WorkerChannelContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, workerSid: string, sid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workerSid)) { + throw new Error('Parameter \'workerSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { workspaceSid, workerSid, sid, }; + this._uri = `/Workspaces/${workspaceSid}/Workers/${workerSid}/Channels/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: WorkerChannelInstance) => any): Promise<WorkerChannelInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WorkerChannelInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.workerSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerChannelInstance>) => any): Promise<ApiResponse<WorkerChannelInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkerChannelResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<WorkerChannelInstance> => ({ + ...response, + body: new WorkerChannelInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.workerSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WorkerChannelContextUpdateOptions | ((error: Error | null, item?: WorkerChannelInstance) => any),callback?: (error: Error | null, item?: WorkerChannelInstance) => any): Promise<WorkerChannelInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["capacity"] !== undefined) + data["Capacity"] = params["capacity"]; + if (params["available"] !== undefined) + data["Available"] = serialize.bool(params["available"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WorkerChannelInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.workerSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WorkerChannelContextUpdateOptions | ((error: Error | null, item?: ApiResponse<WorkerChannelInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkerChannelInstance>) => any): Promise<ApiResponse<WorkerChannelInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["capacity"] !== undefined) + data["Capacity"] = params["capacity"]; + if (params["available"] !== undefined) + data["Available"] = serialize.bool(params["available"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<WorkerChannelResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<WorkerChannelInstance> => ({ + ...response, + body: new WorkerChannelInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.workerSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkerChannelPayload extends TwilioResponsePayload { + channels: WorkerChannelResource[]; +} + +interface WorkerChannelResource { + account_sid: string; + assigned_tasks: number; + available: boolean; + available_capacity_percentage: number; + configured_capacity: number; + date_created: Date; + date_updated: Date; + sid: string; + task_channel_sid: string; + task_channel_unique_name: string; + worker_sid: string; + workspace_sid: string; + url: string; +} + +export class WorkerChannelInstance { + protected _solution: WorkerChannelContextSolution; + protected _context?: WorkerChannelContext; + + constructor(protected _version: V1, payload: WorkerChannelResource, workspaceSid: string, workerSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.assignedTasks = deserialize.integer(payload.assigned_tasks); + this.available = (payload.available); + this.availableCapacityPercentage = deserialize.integer(payload.available_capacity_percentage); + this.configuredCapacity = deserialize.integer(payload.configured_capacity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.sid = (payload.sid); + this.taskChannelSid = (payload.task_channel_sid); + this.taskChannelUniqueName = (payload.task_channel_unique_name); + this.workerSid = (payload.worker_sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, workerSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + */ + accountSid: string; + /** + * The total number of Tasks assigned to Worker for the TaskChannel type. + */ + assignedTasks: number; + /** + * Whether the Worker should receive Tasks of the TaskChannel type. + */ + available: boolean; + /** + * The current percentage of capacity the TaskChannel has available. Can be a number between `0` and `100`. A value of `0` indicates that TaskChannel has no capacity available and a value of `100` means the Worker is available to receive any Tasks of this TaskChannel type. + */ + availableCapacityPercentage: number; + /** + * The current configured capacity for the WorkerChannel. TaskRouter will not create any reservations after the assigned Tasks for the Worker reaches the value. + */ + configuredCapacity: number; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The unique string that we created to identify the WorkerChannel resource. + */ + sid: string; + /** + * The SID of the TaskChannel. + */ + taskChannelSid: string; + /** + * The unique name of the TaskChannel, such as `voice` or `sms`. + */ + taskChannelUniqueName: string; + /** + * The SID of the Worker that contains the WorkerChannel. + */ + workerSid: string; + /** + * The SID of the Workspace that contains the WorkerChannel. + */ + workspaceSid: string; + /** + * The absolute URL of the WorkerChannel resource. + */ + url: string; + + private get _proxy(): WorkerChannelContext { + this._context = this._context || new WorkerChannelContextImpl(this._version, this._solution.workspaceSid, this._solution.workerSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a WorkerChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance + */ + fetch(callback?: (error: Error | null, item?: WorkerChannelInstance) => any): Promise<WorkerChannelInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WorkerChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerChannelInstance>) => any): Promise<ApiResponse<WorkerChannelInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WorkerChannelInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance + */ + update(callback?: (error: Error | null, item?: WorkerChannelInstance) => any): Promise<WorkerChannelInstance>; + /** + * Update a WorkerChannelInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance + */ + update(params: WorkerChannelContextUpdateOptions, callback?: (error: Error | null, item?: WorkerChannelInstance) => any): Promise<WorkerChannelInstance>; + + update(params?: any, callback?: (error: Error | null, item?: WorkerChannelInstance) => any): Promise<WorkerChannelInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a WorkerChannelInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerChannelInstance>) => any): Promise<ApiResponse<WorkerChannelInstance>>; + /** + * Update a WorkerChannelInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerChannelInstance with HTTP metadata + */ + updateWithHttpInfo(params: WorkerChannelContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkerChannelInstance>) => any): Promise<ApiResponse<WorkerChannelInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkerChannelInstance>) => any): Promise<ApiResponse<WorkerChannelInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + assignedTasks: this.assignedTasks, + available: this.available, + availableCapacityPercentage: this.availableCapacityPercentage, + configuredCapacity: this.configuredCapacity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + sid: this.sid, + taskChannelSid: this.taskChannelSid, + taskChannelUniqueName: this.taskChannelUniqueName, + workerSid: this.workerSid, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkerChannelSolution { + workspaceSid: string; + workerSid: string; +} + +export interface WorkerChannelListInstance { + _version: V1; + _solution: WorkerChannelSolution; + _uri: string; + + (sid: string, ): WorkerChannelContext; + get(sid: string, ): WorkerChannelContext; + + + + + + + + /** + * Streams WorkerChannelInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: WorkerChannelInstance, done: (err?: Error) => void) => void): void; + each(params: WorkerChannelListInstanceEachOptions, callback?: (item: WorkerChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Streams WorkerChannelInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerChannelListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: WorkerChannelInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: WorkerChannelListInstanceEachOptions, callback?: (item: WorkerChannelInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of WorkerChannelInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: WorkerChannelPage) => any): Promise<WorkerChannelPage>; + /** + * Retrieve a single target page of WorkerChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<WorkerChannelPage>) => any): Promise<ApiResponse<WorkerChannelPage>>; + /** + * Lists WorkerChannelInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: WorkerChannelInstance[]) => any): Promise<WorkerChannelInstance[]>; + list(params: WorkerChannelListInstanceOptions, callback?: (error: Error | null, items: WorkerChannelInstance[]) => any): Promise<WorkerChannelInstance[]>; + /** + * Lists WorkerChannelInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerChannelListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<WorkerChannelInstance[]>) => any): Promise<ApiResponse<WorkerChannelInstance[]>>; + listWithHttpInfo(params: WorkerChannelListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<WorkerChannelInstance[]>) => any): Promise<ApiResponse<WorkerChannelInstance[]>>; + /** + * Retrieve a single page of WorkerChannelInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: WorkerChannelPage) => any): Promise<WorkerChannelPage>; + page(params: WorkerChannelListInstancePageOptions, callback?: (error: Error | null, items: WorkerChannelPage) => any): Promise<WorkerChannelPage>; + /** + * Retrieve a single page of WorkerChannelInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkerChannelListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<WorkerChannelPage>) => any): Promise<ApiResponse<WorkerChannelPage>>; + pageWithHttpInfo(params: WorkerChannelListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<WorkerChannelPage>) => any): Promise<ApiResponse<WorkerChannelPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkerChannelListInstance(version: V1, workspaceSid: string, workerSid: string): WorkerChannelListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workerSid)) { + throw new Error('Parameter \'workerSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as WorkerChannelListInstance; + + instance.get = function get(sid, ): WorkerChannelContext { + return new WorkerChannelContextImpl(version, workspaceSid, workerSid, sid); + } + + instance._version = version; + instance._solution = { workspaceSid, workerSid, }; + instance._uri = `/Workspaces/${workspaceSid}/Workers/${workerSid}/Channels`; + + instance.page = function page(params?: WorkerChannelListInstancePageOptions | ((error: Error | null, items: WorkerChannelPage) => any), callback?: (error: Error | null, items: WorkerChannelPage) => any): Promise<WorkerChannelPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new WorkerChannelPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: WorkerChannelPage) => any): Promise<WorkerChannelPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new WorkerChannelPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: WorkerChannelListInstancePageOptions | ((error: Error | null, items: ApiResponse<WorkerChannelPage>) => any), callback?: (error: Error | null, items: ApiResponse<WorkerChannelPage>) => any): Promise<ApiResponse<WorkerChannelPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkerChannelPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WorkerChannelPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<WorkerChannelPage>) => any): Promise<ApiResponse<WorkerChannelPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<WorkerChannelPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WorkerChannelPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class WorkerChannelPage extends Page<V1, WorkerChannelPayload, WorkerChannelResource, WorkerChannelInstance> { +/** +* Initialize the WorkerChannelPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: WorkerChannelSolution) { + super(version, response, solution); + } + + /** + * Build an instance of WorkerChannelInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: WorkerChannelResource): WorkerChannelInstance { + + return new WorkerChannelInstance( + this._version, + payload, + this._solution.workspaceSid, + this._solution.workerSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/worker/workerStatistics.ts b/rest/taskrouter/v1/workspace/worker/workerStatistics.ts new file mode 100644 index 000000000..5812ad38c --- /dev/null +++ b/rest/taskrouter/v1/workspace/worker/workerStatistics.ts @@ -0,0 +1,372 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a WorkerStatisticsInstance + */ +export interface WorkerStatisticsContextFetchOptions { + /** Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** Only calculate statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; +} + +export interface WorkerStatisticsContext { + + /** + * Fetch a WorkerStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkerStatisticsInstance) => any): Promise<WorkerStatisticsInstance>; + /** + * Fetch a WorkerStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerStatisticsInstance + */ + fetch(params: WorkerStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkerStatisticsInstance) => any): Promise<WorkerStatisticsInstance>; + + /** + * Fetch a WorkerStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerStatisticsInstance>) => any): Promise<ApiResponse<WorkerStatisticsInstance>>; + /** + * Fetch a WorkerStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkerStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkerStatisticsInstance>) => any): Promise<ApiResponse<WorkerStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkerStatisticsContextSolution { + "workspaceSid": string; + "workerSid": string; +} + +export class WorkerStatisticsContextImpl implements WorkerStatisticsContext { + protected _solution: WorkerStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, workerSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workerSid)) { + throw new Error('Parameter \'workerSid\' is not valid.'); + } + + this._solution = { workspaceSid, workerSid, }; + this._uri = `/Workspaces/${workspaceSid}/Workers/${workerSid}/Statistics`; + } + + fetch(params?: WorkerStatisticsContextFetchOptions | ((error: Error | null, item?: WorkerStatisticsInstance) => any),callback?: (error: Error | null, item?: WorkerStatisticsInstance) => any): Promise<WorkerStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new WorkerStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.workerSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: WorkerStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<WorkerStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkerStatisticsInstance>) => any): Promise<ApiResponse<WorkerStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkerStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkerStatisticsInstance> => ({ + ...response, + body: new WorkerStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.workerSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkerStatisticsPayload extends WorkerStatisticsResource {} + +interface WorkerStatisticsResource { + account_sid: string; + cumulative: any; + worker_sid: string; + workspace_sid: string; + url: string; +} + +export class WorkerStatisticsInstance { + protected _solution: WorkerStatisticsContextSolution; + protected _context?: WorkerStatisticsContext; + + constructor(protected _version: V1, payload: WorkerStatisticsResource, workspaceSid: string, workerSid: string) { + + this.accountSid = (payload.account_sid); + this.cumulative = (payload.cumulative); + this.workerSid = (payload.worker_sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, workerSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + */ + accountSid: string; + /** + * An object that contains the cumulative statistics for the Worker. + */ + cumulative: any; + /** + * The SID of the Worker that contains the WorkerChannel. + */ + workerSid: string; + /** + * The SID of the Workspace that contains the WorkerChannel. + */ + workspaceSid: string; + /** + * The absolute URL of the WorkerChannel statistics resource. + */ + url: string; + + private get _proxy(): WorkerStatisticsContext { + this._context = this._context || new WorkerStatisticsContextImpl(this._version, this._solution.workspaceSid, this._solution.workerSid); + return this._context; + } + + /** + * Fetch a WorkerStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkerStatisticsInstance) => any): Promise<WorkerStatisticsInstance>; + /** + * Fetch a WorkerStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerStatisticsInstance + */ + fetch(params: WorkerStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkerStatisticsInstance) => any): Promise<WorkerStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: WorkerStatisticsInstance) => any): Promise<WorkerStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a WorkerStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkerStatisticsInstance>) => any): Promise<ApiResponse<WorkerStatisticsInstance>>; + /** + * Fetch a WorkerStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkerStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkerStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkerStatisticsInstance>) => any): Promise<ApiResponse<WorkerStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkerStatisticsInstance>) => any): Promise<ApiResponse<WorkerStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + cumulative: this.cumulative, + workerSid: this.workerSid, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkerStatisticsSolution { + workspaceSid: string; + workerSid: string; +} + +export interface WorkerStatisticsListInstance { + _version: V1; + _solution: WorkerStatisticsSolution; + _uri: string; + + (): WorkerStatisticsContext; + get(): WorkerStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkerStatisticsListInstance(version: V1, workspaceSid: string, workerSid: string): WorkerStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workerSid)) { + throw new Error('Parameter \'workerSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WorkerStatisticsListInstance; + + instance.get = function get(): WorkerStatisticsContext { + return new WorkerStatisticsContextImpl(version, workspaceSid, workerSid); + } + + instance._version = version; + instance._solution = { workspaceSid, workerSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/worker/workersCumulativeStatistics.ts b/rest/taskrouter/v1/workspace/worker/workersCumulativeStatistics.ts new file mode 100644 index 000000000..89dc4b784 --- /dev/null +++ b/rest/taskrouter/v1/workspace/worker/workersCumulativeStatistics.ts @@ -0,0 +1,411 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a WorkersCumulativeStatisticsInstance + */ +export interface WorkersCumulativeStatisticsContextFetchOptions { + /** Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "endDate"?: Date; + /** Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; +} + +export interface WorkersCumulativeStatisticsContext { + + /** + * Fetch a WorkersCumulativeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersCumulativeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkersCumulativeStatisticsInstance) => any): Promise<WorkersCumulativeStatisticsInstance>; + /** + * Fetch a WorkersCumulativeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersCumulativeStatisticsInstance + */ + fetch(params: WorkersCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkersCumulativeStatisticsInstance) => any): Promise<WorkersCumulativeStatisticsInstance>; + + /** + * Fetch a WorkersCumulativeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkersCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkersCumulativeStatisticsInstance>>; + /** + * Fetch a WorkersCumulativeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkersCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkersCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkersCumulativeStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkersCumulativeStatisticsContextSolution { + "workspaceSid": string; +} + +export class WorkersCumulativeStatisticsContextImpl implements WorkersCumulativeStatisticsContext { + protected _solution: WorkersCumulativeStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + this._solution = { workspaceSid, }; + this._uri = `/Workspaces/${workspaceSid}/Workers/CumulativeStatistics`; + } + + fetch(params?: WorkersCumulativeStatisticsContextFetchOptions | ((error: Error | null, item?: WorkersCumulativeStatisticsInstance) => any),callback?: (error: Error | null, item?: WorkersCumulativeStatisticsInstance) => any): Promise<WorkersCumulativeStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new WorkersCumulativeStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: WorkersCumulativeStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<WorkersCumulativeStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkersCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkersCumulativeStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkersCumulativeStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkersCumulativeStatisticsInstance> => ({ + ...response, + body: new WorkersCumulativeStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkersCumulativeStatisticsPayload extends WorkersCumulativeStatisticsResource {} + +interface WorkersCumulativeStatisticsResource { + account_sid: string; + start_time: Date; + end_time: Date; + activity_durations: Array<any>; + reservations_created: number; + reservations_accepted: number; + reservations_rejected: number; + reservations_timed_out: number; + reservations_canceled: number; + reservations_rescinded: number; + workspace_sid: string; + url: string; +} + +export class WorkersCumulativeStatisticsInstance { + protected _solution: WorkersCumulativeStatisticsContextSolution; + protected _context?: WorkersCumulativeStatisticsContext; + + constructor(protected _version: V1, payload: WorkersCumulativeStatisticsResource, workspaceSid: string) { + + this.accountSid = (payload.account_sid); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.activityDurations = (payload.activity_durations); + this.reservationsCreated = deserialize.integer(payload.reservations_created); + this.reservationsAccepted = deserialize.integer(payload.reservations_accepted); + this.reservationsRejected = deserialize.integer(payload.reservations_rejected); + this.reservationsTimedOut = deserialize.integer(payload.reservations_timed_out); + this.reservationsCanceled = deserialize.integer(payload.reservations_canceled); + this.reservationsRescinded = deserialize.integer(payload.reservations_rescinded); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + */ + accountSid: string; + /** + * The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + startTime: Date; + /** + * The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + endTime: Date; + /** + * The minimum, average, maximum, and total time (in seconds) that Workers spent in each Activity. + */ + activityDurations: Array<any>; + /** + * The total number of Reservations that were created. + */ + reservationsCreated: number; + /** + * The total number of Reservations that were accepted. + */ + reservationsAccepted: number; + /** + * The total number of Reservations that were rejected. + */ + reservationsRejected: number; + /** + * The total number of Reservations that were timed out. + */ + reservationsTimedOut: number; + /** + * The total number of Reservations that were canceled. + */ + reservationsCanceled: number; + /** + * The total number of Reservations that were rescinded. + */ + reservationsRescinded: number; + /** + * The SID of the Workspace that contains the Workers. + */ + workspaceSid: string; + /** + * The absolute URL of the Workers statistics resource. + */ + url: string; + + private get _proxy(): WorkersCumulativeStatisticsContext { + this._context = this._context || new WorkersCumulativeStatisticsContextImpl(this._version, this._solution.workspaceSid); + return this._context; + } + + /** + * Fetch a WorkersCumulativeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersCumulativeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkersCumulativeStatisticsInstance) => any): Promise<WorkersCumulativeStatisticsInstance>; + /** + * Fetch a WorkersCumulativeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersCumulativeStatisticsInstance + */ + fetch(params: WorkersCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkersCumulativeStatisticsInstance) => any): Promise<WorkersCumulativeStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: WorkersCumulativeStatisticsInstance) => any): Promise<WorkersCumulativeStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a WorkersCumulativeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkersCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkersCumulativeStatisticsInstance>>; + /** + * Fetch a WorkersCumulativeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkersCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkersCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkersCumulativeStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkersCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkersCumulativeStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + startTime: this.startTime, + endTime: this.endTime, + activityDurations: this.activityDurations, + reservationsCreated: this.reservationsCreated, + reservationsAccepted: this.reservationsAccepted, + reservationsRejected: this.reservationsRejected, + reservationsTimedOut: this.reservationsTimedOut, + reservationsCanceled: this.reservationsCanceled, + reservationsRescinded: this.reservationsRescinded, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkersCumulativeStatisticsSolution { + workspaceSid: string; +} + +export interface WorkersCumulativeStatisticsListInstance { + _version: V1; + _solution: WorkersCumulativeStatisticsSolution; + _uri: string; + + (): WorkersCumulativeStatisticsContext; + get(): WorkersCumulativeStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkersCumulativeStatisticsListInstance(version: V1, workspaceSid: string): WorkersCumulativeStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WorkersCumulativeStatisticsListInstance; + + instance.get = function get(): WorkersCumulativeStatisticsContext { + return new WorkersCumulativeStatisticsContextImpl(version, workspaceSid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/worker/workersRealTimeStatistics.ts b/rest/taskrouter/v1/workspace/worker/workersRealTimeStatistics.ts new file mode 100644 index 000000000..15e37e304 --- /dev/null +++ b/rest/taskrouter/v1/workspace/worker/workersRealTimeStatistics.ts @@ -0,0 +1,344 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a WorkersRealTimeStatisticsInstance + */ +export interface WorkersRealTimeStatisticsContextFetchOptions { + /** Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; +} + +export interface WorkersRealTimeStatisticsContext { + + /** + * Fetch a WorkersRealTimeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersRealTimeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkersRealTimeStatisticsInstance) => any): Promise<WorkersRealTimeStatisticsInstance>; + /** + * Fetch a WorkersRealTimeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersRealTimeStatisticsInstance + */ + fetch(params: WorkersRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkersRealTimeStatisticsInstance) => any): Promise<WorkersRealTimeStatisticsInstance>; + + /** + * Fetch a WorkersRealTimeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkersRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkersRealTimeStatisticsInstance>>; + /** + * Fetch a WorkersRealTimeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkersRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkersRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkersRealTimeStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkersRealTimeStatisticsContextSolution { + "workspaceSid": string; +} + +export class WorkersRealTimeStatisticsContextImpl implements WorkersRealTimeStatisticsContext { + protected _solution: WorkersRealTimeStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + this._solution = { workspaceSid, }; + this._uri = `/Workspaces/${workspaceSid}/Workers/RealTimeStatistics`; + } + + fetch(params?: WorkersRealTimeStatisticsContextFetchOptions | ((error: Error | null, item?: WorkersRealTimeStatisticsInstance) => any),callback?: (error: Error | null, item?: WorkersRealTimeStatisticsInstance) => any): Promise<WorkersRealTimeStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new WorkersRealTimeStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: WorkersRealTimeStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<WorkersRealTimeStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkersRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkersRealTimeStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkersRealTimeStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkersRealTimeStatisticsInstance> => ({ + ...response, + body: new WorkersRealTimeStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkersRealTimeStatisticsPayload extends WorkersRealTimeStatisticsResource {} + +interface WorkersRealTimeStatisticsResource { + account_sid: string; + activity_statistics: Array<any>; + total_workers: number; + workspace_sid: string; + url: string; +} + +export class WorkersRealTimeStatisticsInstance { + protected _solution: WorkersRealTimeStatisticsContextSolution; + protected _context?: WorkersRealTimeStatisticsContext; + + constructor(protected _version: V1, payload: WorkersRealTimeStatisticsResource, workspaceSid: string) { + + this.accountSid = (payload.account_sid); + this.activityStatistics = (payload.activity_statistics); + this.totalWorkers = deserialize.integer(payload.total_workers); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + */ + accountSid: string; + /** + * The number of current Workers by Activity. + */ + activityStatistics: Array<any>; + /** + * The total number of Workers. + */ + totalWorkers: number; + /** + * The SID of the Workspace that contains the Workers. + */ + workspaceSid: string; + /** + * The absolute URL of the Workers statistics resource. + */ + url: string; + + private get _proxy(): WorkersRealTimeStatisticsContext { + this._context = this._context || new WorkersRealTimeStatisticsContextImpl(this._version, this._solution.workspaceSid); + return this._context; + } + + /** + * Fetch a WorkersRealTimeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersRealTimeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkersRealTimeStatisticsInstance) => any): Promise<WorkersRealTimeStatisticsInstance>; + /** + * Fetch a WorkersRealTimeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersRealTimeStatisticsInstance + */ + fetch(params: WorkersRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkersRealTimeStatisticsInstance) => any): Promise<WorkersRealTimeStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: WorkersRealTimeStatisticsInstance) => any): Promise<WorkersRealTimeStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a WorkersRealTimeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkersRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkersRealTimeStatisticsInstance>>; + /** + * Fetch a WorkersRealTimeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkersRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkersRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkersRealTimeStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkersRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkersRealTimeStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + activityStatistics: this.activityStatistics, + totalWorkers: this.totalWorkers, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkersRealTimeStatisticsSolution { + workspaceSid: string; +} + +export interface WorkersRealTimeStatisticsListInstance { + _version: V1; + _solution: WorkersRealTimeStatisticsSolution; + _uri: string; + + (): WorkersRealTimeStatisticsContext; + get(): WorkersRealTimeStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkersRealTimeStatisticsListInstance(version: V1, workspaceSid: string): WorkersRealTimeStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WorkersRealTimeStatisticsListInstance; + + instance.get = function get(): WorkersRealTimeStatisticsContext { + return new WorkersRealTimeStatisticsContextImpl(version, workspaceSid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/worker/workersStatistics.ts b/rest/taskrouter/v1/workspace/worker/workersStatistics.ts new file mode 100644 index 000000000..963ebab24 --- /dev/null +++ b/rest/taskrouter/v1/workspace/worker/workersStatistics.ts @@ -0,0 +1,380 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a WorkersStatisticsInstance + */ +export interface WorkersStatisticsContextFetchOptions { + /** Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** The SID of the TaskQueue for which to fetch Worker statistics. */ + "taskQueueSid"?: string; + /** The `friendly_name` of the TaskQueue for which to fetch Worker statistics. */ + "taskQueueName"?: string; + /** Only include Workers with `friendly_name` values that match this parameter. */ + "friendlyName"?: string; + /** Only calculate statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; +} + +export interface WorkersStatisticsContext { + + /** + * Fetch a WorkersStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkersStatisticsInstance) => any): Promise<WorkersStatisticsInstance>; + /** + * Fetch a WorkersStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersStatisticsInstance + */ + fetch(params: WorkersStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkersStatisticsInstance) => any): Promise<WorkersStatisticsInstance>; + + /** + * Fetch a WorkersStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkersStatisticsInstance>) => any): Promise<ApiResponse<WorkersStatisticsInstance>>; + /** + * Fetch a WorkersStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkersStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkersStatisticsInstance>) => any): Promise<ApiResponse<WorkersStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkersStatisticsContextSolution { + "workspaceSid": string; +} + +export class WorkersStatisticsContextImpl implements WorkersStatisticsContext { + protected _solution: WorkersStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + this._solution = { workspaceSid, }; + this._uri = `/Workspaces/${workspaceSid}/Workers/Statistics`; + } + + fetch(params?: WorkersStatisticsContextFetchOptions | ((error: Error | null, item?: WorkersStatisticsInstance) => any),callback?: (error: Error | null, item?: WorkersStatisticsInstance) => any): Promise<WorkersStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["taskQueueSid"] !== undefined) + data["TaskQueueSid"] = params["taskQueueSid"]; + if (params["taskQueueName"] !== undefined) + data["TaskQueueName"] = params["taskQueueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new WorkersStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: WorkersStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<WorkersStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkersStatisticsInstance>) => any): Promise<ApiResponse<WorkersStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["taskQueueSid"] !== undefined) + data["TaskQueueSid"] = params["taskQueueSid"]; + if (params["taskQueueName"] !== undefined) + data["TaskQueueName"] = params["taskQueueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkersStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkersStatisticsInstance> => ({ + ...response, + body: new WorkersStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkersStatisticsPayload extends WorkersStatisticsResource {} + +interface WorkersStatisticsResource { + realtime: any; + cumulative: any; + account_sid: string; + workspace_sid: string; + url: string; +} + +export class WorkersStatisticsInstance { + protected _solution: WorkersStatisticsContextSolution; + protected _context?: WorkersStatisticsContext; + + constructor(protected _version: V1, payload: WorkersStatisticsResource, workspaceSid: string) { + + this.realtime = (payload.realtime); + this.cumulative = (payload.cumulative); + this.accountSid = (payload.account_sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, }; + } + + /** + * An object that contains the real-time statistics for the Worker. + */ + realtime: any; + /** + * An object that contains the cumulative statistics for the Worker. + */ + cumulative: any; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + */ + accountSid: string; + /** + * The SID of the Workspace that contains the Worker. + */ + workspaceSid: string; + /** + * The absolute URL of the Worker statistics resource. + */ + url: string; + + private get _proxy(): WorkersStatisticsContext { + this._context = this._context || new WorkersStatisticsContextImpl(this._version, this._solution.workspaceSid); + return this._context; + } + + /** + * Fetch a WorkersStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkersStatisticsInstance) => any): Promise<WorkersStatisticsInstance>; + /** + * Fetch a WorkersStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersStatisticsInstance + */ + fetch(params: WorkersStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkersStatisticsInstance) => any): Promise<WorkersStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: WorkersStatisticsInstance) => any): Promise<WorkersStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a WorkersStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkersStatisticsInstance>) => any): Promise<ApiResponse<WorkersStatisticsInstance>>; + /** + * Fetch a WorkersStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkersStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkersStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkersStatisticsInstance>) => any): Promise<ApiResponse<WorkersStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkersStatisticsInstance>) => any): Promise<ApiResponse<WorkersStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + realtime: this.realtime, + cumulative: this.cumulative, + accountSid: this.accountSid, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkersStatisticsSolution { + workspaceSid: string; +} + +export interface WorkersStatisticsListInstance { + _version: V1; + _solution: WorkersStatisticsSolution; + _uri: string; + + (): WorkersStatisticsContext; + get(): WorkersStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkersStatisticsListInstance(version: V1, workspaceSid: string): WorkersStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WorkersStatisticsListInstance; + + instance.get = function get(): WorkersStatisticsContext { + return new WorkersStatisticsContextImpl(version, workspaceSid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/workflow.ts b/rest/taskrouter/v1/workspace/workflow.ts new file mode 100644 index 000000000..e5b5e1d00 --- /dev/null +++ b/rest/taskrouter/v1/workspace/workflow.ts @@ -0,0 +1,1066 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { WorkflowCumulativeStatisticsListInstance } from "./workflow/workflowCumulativeStatistics"; +import { WorkflowRealTimeStatisticsListInstance } from "./workflow/workflowRealTimeStatistics"; +import { WorkflowStatisticsListInstance } from "./workflow/workflowStatistics"; + + + + + +/** + * Options to pass to update a WorkflowInstance + */ +export interface WorkflowContextUpdateOptions { + /** A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. */ + "friendlyName"?: string; + /** The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. */ + "assignmentCallbackUrl"?: string; + /** The URL that we should call when a call to the `assignment_callback_url` fails. */ + "fallbackAssignmentCallbackUrl"?: string; + /** A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. */ + "configuration"?: string; + /** How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. */ + "taskReservationTimeout"?: number; + /** Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. */ + "reEvaluateTasks"?: string; +} + +/** + * Options to pass to create a WorkflowInstance + */ +export interface WorkflowListInstanceCreateOptions { + /** A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. */ + "friendlyName": string; + /** A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. */ + "configuration": string; + /** The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. */ + "assignmentCallbackUrl"?: string; + /** The URL that we should call when a call to the `assignment_callback_url` fails. */ + "fallbackAssignmentCallbackUrl"?: string; + /** How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. */ + "taskReservationTimeout"?: number; +} + +/** + * Options to pass to each + */ +export interface WorkflowListInstanceEachOptions { + /** The `friendly_name` of the Workflow resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: WorkflowInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface WorkflowListInstanceOptions { + /** The `friendly_name` of the Workflow resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface WorkflowListInstancePageOptions { + /** The `friendly_name` of the Workflow resources to read. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface WorkflowContext { + cumulativeStatistics: WorkflowCumulativeStatisticsListInstance; + realTimeStatistics: WorkflowRealTimeStatisticsListInstance; + statistics: WorkflowStatisticsListInstance; + + /** + * Remove a WorkflowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a WorkflowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a WorkflowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance + */ + fetch(callback?: (error: Error | null, item?: WorkflowInstance) => any): Promise<WorkflowInstance> + + /** + * Fetch a WorkflowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>> + + /** + * Update a WorkflowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance + */ + update(callback?: (error: Error | null, item?: WorkflowInstance) => any): Promise<WorkflowInstance>; + /** + * Update a WorkflowInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance + */ + update(params: WorkflowContextUpdateOptions, callback?: (error: Error | null, item?: WorkflowInstance) => any): Promise<WorkflowInstance>; + + /** + * Update a WorkflowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>>; + /** + * Update a WorkflowInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance with HTTP metadata + */ + updateWithHttpInfo(params: WorkflowContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkflowContextSolution { + "workspaceSid": string; + "sid": string; +} + +export class WorkflowContextImpl implements WorkflowContext { + protected _solution: WorkflowContextSolution; + protected _uri: string; + + protected _cumulativeStatistics?: WorkflowCumulativeStatisticsListInstance; + protected _realTimeStatistics?: WorkflowRealTimeStatisticsListInstance; + protected _statistics?: WorkflowStatisticsListInstance; + + constructor(protected _version: V1, workspaceSid: string, sid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { workspaceSid, sid, }; + this._uri = `/Workspaces/${workspaceSid}/Workflows/${sid}`; + } + + get cumulativeStatistics(): WorkflowCumulativeStatisticsListInstance { + this._cumulativeStatistics = this._cumulativeStatistics || WorkflowCumulativeStatisticsListInstance(this._version, this._solution.workspaceSid, this._solution.sid); + return this._cumulativeStatistics; + } + + get realTimeStatistics(): WorkflowRealTimeStatisticsListInstance { + this._realTimeStatistics = this._realTimeStatistics || WorkflowRealTimeStatisticsListInstance(this._version, this._solution.workspaceSid, this._solution.sid); + return this._realTimeStatistics; + } + + get statistics(): WorkflowStatisticsListInstance { + this._statistics = this._statistics || WorkflowStatisticsListInstance(this._version, this._solution.workspaceSid, this._solution.sid); + return this._statistics; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: WorkflowInstance) => any): Promise<WorkflowInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WorkflowInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkflowResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<WorkflowInstance> => ({ + ...response, + body: new WorkflowInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WorkflowContextUpdateOptions | ((error: Error | null, item?: WorkflowInstance) => any),callback?: (error: Error | null, item?: WorkflowInstance) => any): Promise<WorkflowInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["assignmentCallbackUrl"] !== undefined) + data["AssignmentCallbackUrl"] = params["assignmentCallbackUrl"]; + if (params["fallbackAssignmentCallbackUrl"] !== undefined) + data["FallbackAssignmentCallbackUrl"] = params["fallbackAssignmentCallbackUrl"]; + if (params["configuration"] !== undefined) + data["Configuration"] = params["configuration"]; + if (params["taskReservationTimeout"] !== undefined) + data["TaskReservationTimeout"] = params["taskReservationTimeout"]; + if (params["reEvaluateTasks"] !== undefined) + data["ReEvaluateTasks"] = params["reEvaluateTasks"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WorkflowInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WorkflowContextUpdateOptions | ((error: Error | null, item?: ApiResponse<WorkflowInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["assignmentCallbackUrl"] !== undefined) + data["AssignmentCallbackUrl"] = params["assignmentCallbackUrl"]; + if (params["fallbackAssignmentCallbackUrl"] !== undefined) + data["FallbackAssignmentCallbackUrl"] = params["fallbackAssignmentCallbackUrl"]; + if (params["configuration"] !== undefined) + data["Configuration"] = params["configuration"]; + if (params["taskReservationTimeout"] !== undefined) + data["TaskReservationTimeout"] = params["taskReservationTimeout"]; + if (params["reEvaluateTasks"] !== undefined) + data["ReEvaluateTasks"] = params["reEvaluateTasks"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<WorkflowResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<WorkflowInstance> => ({ + ...response, + body: new WorkflowInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkflowPayload extends TwilioResponsePayload { + workflows: WorkflowResource[]; +} + +interface WorkflowResource { + account_sid: string; + assignment_callback_url: string; + configuration: string; + date_created: Date; + date_updated: Date; + document_content_type: string; + fallback_assignment_callback_url: string; + friendly_name: string; + sid: string; + task_reservation_timeout: number; + workspace_sid: string; + url: string; + links: Record<string, string>; +} + +export class WorkflowInstance { + protected _solution: WorkflowContextSolution; + protected _context?: WorkflowContext; + + constructor(protected _version: V1, payload: WorkflowResource, workspaceSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.assignmentCallbackUrl = (payload.assignment_callback_url); + this.configuration = (payload.configuration); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.documentContentType = (payload.document_content_type); + this.fallbackAssignmentCallbackUrl = (payload.fallback_assignment_callback_url); + this.friendlyName = (payload.friendly_name); + this.sid = (payload.sid); + this.taskReservationTimeout = deserialize.integer(payload.task_reservation_timeout); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { workspaceSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + */ + accountSid: string; + /** + * The URL that we call when a task managed by the Workflow is assigned to a Worker. See Assignment Callback URL for more information. + */ + assignmentCallbackUrl: string; + /** + * A JSON string that contains the Workflow\'s configuration. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + */ + configuration: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The MIME type of the document. + */ + documentContentType: string; + /** + * The URL that we call when a call to the `assignment_callback_url` fails. + */ + fallbackAssignmentCallbackUrl: string; + /** + * The string that you assigned to describe the Workflow resource. For example, `Customer Support` or `2014 Election Campaign`. + */ + friendlyName: string; + /** + * The unique string that we created to identify the Workflow resource. + */ + sid: string; + /** + * How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + */ + taskReservationTimeout: number; + /** + * The SID of the Workspace that contains the Workflow. + */ + workspaceSid: string; + /** + * The absolute URL of the Workflow resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): WorkflowContext { + this._context = this._context || new WorkflowContextImpl(this._version, this._solution.workspaceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a WorkflowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a WorkflowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a WorkflowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance + */ + fetch(callback?: (error: Error | null, item?: WorkflowInstance) => any): Promise<WorkflowInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WorkflowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WorkflowInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance + */ + update(callback?: (error: Error | null, item?: WorkflowInstance) => any): Promise<WorkflowInstance>; + /** + * Update a WorkflowInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance + */ + update(params: WorkflowContextUpdateOptions, callback?: (error: Error | null, item?: WorkflowInstance) => any): Promise<WorkflowInstance>; + + update(params?: any, callback?: (error: Error | null, item?: WorkflowInstance) => any): Promise<WorkflowInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a WorkflowInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>>; + /** + * Update a WorkflowInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance with HTTP metadata + */ + updateWithHttpInfo(params: WorkflowContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the cumulativeStatistics. + */ + cumulativeStatistics(): WorkflowCumulativeStatisticsListInstance { + return this._proxy.cumulativeStatistics; + } + + /** + * Access the realTimeStatistics. + */ + realTimeStatistics(): WorkflowRealTimeStatisticsListInstance { + return this._proxy.realTimeStatistics; + } + + /** + * Access the statistics. + */ + statistics(): WorkflowStatisticsListInstance { + return this._proxy.statistics; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + assignmentCallbackUrl: this.assignmentCallbackUrl, + configuration: this.configuration, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + documentContentType: this.documentContentType, + fallbackAssignmentCallbackUrl: this.fallbackAssignmentCallbackUrl, + friendlyName: this.friendlyName, + sid: this.sid, + taskReservationTimeout: this.taskReservationTimeout, + workspaceSid: this.workspaceSid, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkflowSolution { + workspaceSid: string; +} + +export interface WorkflowListInstance { + _version: V1; + _solution: WorkflowSolution; + _uri: string; + + (sid: string, ): WorkflowContext; + get(sid: string, ): WorkflowContext; + + + + + + + + + /** + * Create a WorkflowInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance + */ + create(params: WorkflowListInstanceCreateOptions, callback?: (error: Error | null, item?: WorkflowInstance) => any): Promise<WorkflowInstance>; + + /** + * Create a WorkflowInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowInstance with HTTP metadata + */ + createWithHttpInfo(params: WorkflowListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>>; + + + + + /** + * Streams WorkflowInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkflowListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: WorkflowInstance, done: (err?: Error) => void) => void): void; + each(params: WorkflowListInstanceEachOptions, callback?: (item: WorkflowInstance, done: (err?: Error) => void) => void): void; + /** + * Streams WorkflowInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkflowListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: WorkflowInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: WorkflowListInstanceEachOptions, callback?: (item: WorkflowInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of WorkflowInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: WorkflowPage) => any): Promise<WorkflowPage>; + /** + * Retrieve a single target page of WorkflowInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<WorkflowPage>) => any): Promise<ApiResponse<WorkflowPage>>; + /** + * Lists WorkflowInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkflowListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: WorkflowInstance[]) => any): Promise<WorkflowInstance[]>; + list(params: WorkflowListInstanceOptions, callback?: (error: Error | null, items: WorkflowInstance[]) => any): Promise<WorkflowInstance[]>; + /** + * Lists WorkflowInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkflowListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<WorkflowInstance[]>) => any): Promise<ApiResponse<WorkflowInstance[]>>; + listWithHttpInfo(params: WorkflowListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<WorkflowInstance[]>) => any): Promise<ApiResponse<WorkflowInstance[]>>; + /** + * Retrieve a single page of WorkflowInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkflowListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: WorkflowPage) => any): Promise<WorkflowPage>; + page(params: WorkflowListInstancePageOptions, callback?: (error: Error | null, items: WorkflowPage) => any): Promise<WorkflowPage>; + /** + * Retrieve a single page of WorkflowInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WorkflowListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<WorkflowPage>) => any): Promise<ApiResponse<WorkflowPage>>; + pageWithHttpInfo(params: WorkflowListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<WorkflowPage>) => any): Promise<ApiResponse<WorkflowPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkflowListInstance(version: V1, workspaceSid: string): WorkflowListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as WorkflowListInstance; + + instance.get = function get(sid, ): WorkflowContext { + return new WorkflowContextImpl(version, workspaceSid, sid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = `/Workspaces/${workspaceSid}/Workflows`; + + instance.create = function create(params: WorkflowListInstanceCreateOptions, callback?: (error: Error | null, items: WorkflowInstance) => any): Promise<WorkflowInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["configuration"] === null || params["configuration"] === undefined) { + throw new Error('Required parameter "params[\'configuration\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Configuration"] = params["configuration"]; + if (params["assignmentCallbackUrl"] !== undefined) + data["AssignmentCallbackUrl"] = params["assignmentCallbackUrl"]; + if (params["fallbackAssignmentCallbackUrl"] !== undefined) + data["FallbackAssignmentCallbackUrl"] = params["fallbackAssignmentCallbackUrl"]; + if (params["taskReservationTimeout"] !== undefined) + data["TaskReservationTimeout"] = params["taskReservationTimeout"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WorkflowInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: WorkflowListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<WorkflowInstance>) => any): Promise<ApiResponse<WorkflowInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["configuration"] === null || params["configuration"] === undefined) { + throw new Error('Required parameter "params[\'configuration\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Configuration"] = params["configuration"]; + if (params["assignmentCallbackUrl"] !== undefined) + data["AssignmentCallbackUrl"] = params["assignmentCallbackUrl"]; + if (params["fallbackAssignmentCallbackUrl"] !== undefined) + data["FallbackAssignmentCallbackUrl"] = params["fallbackAssignmentCallbackUrl"]; + if (params["taskReservationTimeout"] !== undefined) + data["TaskReservationTimeout"] = params["taskReservationTimeout"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<WorkflowResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<WorkflowInstance> => ({ + ...response, + body: new WorkflowInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: WorkflowListInstancePageOptions | ((error: Error | null, items: WorkflowPage) => any), callback?: (error: Error | null, items: WorkflowPage) => any): Promise<WorkflowPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new WorkflowPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: WorkflowPage) => any): Promise<WorkflowPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new WorkflowPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: WorkflowListInstancePageOptions | ((error: Error | null, items: ApiResponse<WorkflowPage>) => any), callback?: (error: Error | null, items: ApiResponse<WorkflowPage>) => any): Promise<ApiResponse<WorkflowPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkflowPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WorkflowPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<WorkflowPage>) => any): Promise<ApiResponse<WorkflowPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<WorkflowPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WorkflowPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class WorkflowPage extends Page<V1, WorkflowPayload, WorkflowResource, WorkflowInstance> { +/** +* Initialize the WorkflowPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: WorkflowSolution) { + super(version, response, solution); + } + + /** + * Build an instance of WorkflowInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: WorkflowResource): WorkflowInstance { + + return new WorkflowInstance( + this._version, + payload, + this._solution.workspaceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/taskrouter/v1/workspace/workflow/workflowCumulativeStatistics.ts b/rest/taskrouter/v1/workspace/workflow/workflowCumulativeStatistics.ts new file mode 100644 index 000000000..4127e4381 --- /dev/null +++ b/rest/taskrouter/v1/workspace/workflow/workflowCumulativeStatistics.ts @@ -0,0 +1,497 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a WorkflowCumulativeStatisticsInstance + */ +export interface WorkflowCumulativeStatisticsContextFetchOptions { + /** Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; + /** A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. */ + "splitByWaitTime"?: string; +} + +export interface WorkflowCumulativeStatisticsContext { + + /** + * Fetch a WorkflowCumulativeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowCumulativeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkflowCumulativeStatisticsInstance) => any): Promise<WorkflowCumulativeStatisticsInstance>; + /** + * Fetch a WorkflowCumulativeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowCumulativeStatisticsInstance + */ + fetch(params: WorkflowCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkflowCumulativeStatisticsInstance) => any): Promise<WorkflowCumulativeStatisticsInstance>; + + /** + * Fetch a WorkflowCumulativeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowCumulativeStatisticsInstance>>; + /** + * Fetch a WorkflowCumulativeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkflowCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkflowCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowCumulativeStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkflowCumulativeStatisticsContextSolution { + "workspaceSid": string; + "workflowSid": string; +} + +export class WorkflowCumulativeStatisticsContextImpl implements WorkflowCumulativeStatisticsContext { + protected _solution: WorkflowCumulativeStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, workflowSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workflowSid)) { + throw new Error('Parameter \'workflowSid\' is not valid.'); + } + + this._solution = { workspaceSid, workflowSid, }; + this._uri = `/Workspaces/${workspaceSid}/Workflows/${workflowSid}/CumulativeStatistics`; + } + + fetch(params?: WorkflowCumulativeStatisticsContextFetchOptions | ((error: Error | null, item?: WorkflowCumulativeStatisticsInstance) => any),callback?: (error: Error | null, item?: WorkflowCumulativeStatisticsInstance) => any): Promise<WorkflowCumulativeStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new WorkflowCumulativeStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.workflowSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: WorkflowCumulativeStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<WorkflowCumulativeStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkflowCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowCumulativeStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkflowCumulativeStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkflowCumulativeStatisticsInstance> => ({ + ...response, + body: new WorkflowCumulativeStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.workflowSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkflowCumulativeStatisticsPayload extends WorkflowCumulativeStatisticsResource {} + +interface WorkflowCumulativeStatisticsResource { + account_sid: string; + avg_task_acceptance_time: number; + start_time: Date; + end_time: Date; + reservations_created: number; + reservations_accepted: number; + reservations_rejected: number; + reservations_timed_out: number; + reservations_canceled: number; + reservations_rescinded: number; + split_by_wait_time: any; + wait_duration_until_accepted: any; + wait_duration_until_canceled: any; + tasks_canceled: number; + tasks_completed: number; + tasks_entered: number; + tasks_deleted: number; + tasks_moved: number; + tasks_timed_out_in_workflow: number; + workflow_sid: string; + workspace_sid: string; + url: string; +} + +export class WorkflowCumulativeStatisticsInstance { + protected _solution: WorkflowCumulativeStatisticsContextSolution; + protected _context?: WorkflowCumulativeStatisticsContext; + + constructor(protected _version: V1, payload: WorkflowCumulativeStatisticsResource, workspaceSid: string, workflowSid: string) { + + this.accountSid = (payload.account_sid); + this.avgTaskAcceptanceTime = deserialize.integer(payload.avg_task_acceptance_time); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.reservationsCreated = deserialize.integer(payload.reservations_created); + this.reservationsAccepted = deserialize.integer(payload.reservations_accepted); + this.reservationsRejected = deserialize.integer(payload.reservations_rejected); + this.reservationsTimedOut = deserialize.integer(payload.reservations_timed_out); + this.reservationsCanceled = deserialize.integer(payload.reservations_canceled); + this.reservationsRescinded = deserialize.integer(payload.reservations_rescinded); + this.splitByWaitTime = (payload.split_by_wait_time); + this.waitDurationUntilAccepted = (payload.wait_duration_until_accepted); + this.waitDurationUntilCanceled = (payload.wait_duration_until_canceled); + this.tasksCanceled = deserialize.integer(payload.tasks_canceled); + this.tasksCompleted = deserialize.integer(payload.tasks_completed); + this.tasksEntered = deserialize.integer(payload.tasks_entered); + this.tasksDeleted = deserialize.integer(payload.tasks_deleted); + this.tasksMoved = deserialize.integer(payload.tasks_moved); + this.tasksTimedOutInWorkflow = deserialize.integer(payload.tasks_timed_out_in_workflow); + this.workflowSid = (payload.workflow_sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, workflowSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + */ + accountSid: string; + /** + * The average time in seconds between Task creation and acceptance. + */ + avgTaskAcceptanceTime: number; + /** + * The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + startTime: Date; + /** + * The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + endTime: Date; + /** + * The total number of Reservations that were created for Workers. + */ + reservationsCreated: number; + /** + * The total number of Reservations accepted by Workers. + */ + reservationsAccepted: number; + /** + * The total number of Reservations that were rejected. + */ + reservationsRejected: number; + /** + * The total number of Reservations that were timed out. + */ + reservationsTimedOut: number; + /** + * The total number of Reservations that were canceled. + */ + reservationsCanceled: number; + /** + * The total number of Reservations that were rescinded. + */ + reservationsRescinded: number; + /** + * A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + */ + splitByWaitTime: any; + /** + * The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were accepted. + */ + waitDurationUntilAccepted: any; + /** + * The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were canceled. + */ + waitDurationUntilCanceled: any; + /** + * The total number of Tasks that were canceled. + */ + tasksCanceled: number; + /** + * The total number of Tasks that were completed. + */ + tasksCompleted: number; + /** + * The total number of Tasks that entered the Workflow. + */ + tasksEntered: number; + /** + * The total number of Tasks that were deleted. + */ + tasksDeleted: number; + /** + * The total number of Tasks that were moved from one queue to another. + */ + tasksMoved: number; + /** + * The total number of Tasks that were timed out of their Workflows (and deleted). + */ + tasksTimedOutInWorkflow: number; + /** + * Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value. + */ + workflowSid: string; + /** + * The SID of the Workspace that contains the Workflow. + */ + workspaceSid: string; + /** + * The absolute URL of the Workflow statistics resource. + */ + url: string; + + private get _proxy(): WorkflowCumulativeStatisticsContext { + this._context = this._context || new WorkflowCumulativeStatisticsContextImpl(this._version, this._solution.workspaceSid, this._solution.workflowSid); + return this._context; + } + + /** + * Fetch a WorkflowCumulativeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowCumulativeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkflowCumulativeStatisticsInstance) => any): Promise<WorkflowCumulativeStatisticsInstance>; + /** + * Fetch a WorkflowCumulativeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowCumulativeStatisticsInstance + */ + fetch(params: WorkflowCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkflowCumulativeStatisticsInstance) => any): Promise<WorkflowCumulativeStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: WorkflowCumulativeStatisticsInstance) => any): Promise<WorkflowCumulativeStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a WorkflowCumulativeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowCumulativeStatisticsInstance>>; + /** + * Fetch a WorkflowCumulativeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkflowCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkflowCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowCumulativeStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkflowCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowCumulativeStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + avgTaskAcceptanceTime: this.avgTaskAcceptanceTime, + startTime: this.startTime, + endTime: this.endTime, + reservationsCreated: this.reservationsCreated, + reservationsAccepted: this.reservationsAccepted, + reservationsRejected: this.reservationsRejected, + reservationsTimedOut: this.reservationsTimedOut, + reservationsCanceled: this.reservationsCanceled, + reservationsRescinded: this.reservationsRescinded, + splitByWaitTime: this.splitByWaitTime, + waitDurationUntilAccepted: this.waitDurationUntilAccepted, + waitDurationUntilCanceled: this.waitDurationUntilCanceled, + tasksCanceled: this.tasksCanceled, + tasksCompleted: this.tasksCompleted, + tasksEntered: this.tasksEntered, + tasksDeleted: this.tasksDeleted, + tasksMoved: this.tasksMoved, + tasksTimedOutInWorkflow: this.tasksTimedOutInWorkflow, + workflowSid: this.workflowSid, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkflowCumulativeStatisticsSolution { + workspaceSid: string; + workflowSid: string; +} + +export interface WorkflowCumulativeStatisticsListInstance { + _version: V1; + _solution: WorkflowCumulativeStatisticsSolution; + _uri: string; + + (): WorkflowCumulativeStatisticsContext; + get(): WorkflowCumulativeStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkflowCumulativeStatisticsListInstance(version: V1, workspaceSid: string, workflowSid: string): WorkflowCumulativeStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workflowSid)) { + throw new Error('Parameter \'workflowSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WorkflowCumulativeStatisticsListInstance; + + instance.get = function get(): WorkflowCumulativeStatisticsContext { + return new WorkflowCumulativeStatisticsContextImpl(version, workspaceSid, workflowSid); + } + + instance._version = version; + instance._solution = { workspaceSid, workflowSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/workflow/workflowRealTimeStatistics.ts b/rest/taskrouter/v1/workspace/workflow/workflowRealTimeStatistics.ts new file mode 100644 index 000000000..71e0a09d5 --- /dev/null +++ b/rest/taskrouter/v1/workspace/workflow/workflowRealTimeStatistics.ts @@ -0,0 +1,382 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a WorkflowRealTimeStatisticsInstance + */ +export interface WorkflowRealTimeStatisticsContextFetchOptions { + /** Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; +} + +export interface WorkflowRealTimeStatisticsContext { + + /** + * Fetch a WorkflowRealTimeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowRealTimeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkflowRealTimeStatisticsInstance) => any): Promise<WorkflowRealTimeStatisticsInstance>; + /** + * Fetch a WorkflowRealTimeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowRealTimeStatisticsInstance + */ + fetch(params: WorkflowRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkflowRealTimeStatisticsInstance) => any): Promise<WorkflowRealTimeStatisticsInstance>; + + /** + * Fetch a WorkflowRealTimeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowRealTimeStatisticsInstance>>; + /** + * Fetch a WorkflowRealTimeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkflowRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkflowRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowRealTimeStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkflowRealTimeStatisticsContextSolution { + "workspaceSid": string; + "workflowSid": string; +} + +export class WorkflowRealTimeStatisticsContextImpl implements WorkflowRealTimeStatisticsContext { + protected _solution: WorkflowRealTimeStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, workflowSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workflowSid)) { + throw new Error('Parameter \'workflowSid\' is not valid.'); + } + + this._solution = { workspaceSid, workflowSid, }; + this._uri = `/Workspaces/${workspaceSid}/Workflows/${workflowSid}/RealTimeStatistics`; + } + + fetch(params?: WorkflowRealTimeStatisticsContextFetchOptions | ((error: Error | null, item?: WorkflowRealTimeStatisticsInstance) => any),callback?: (error: Error | null, item?: WorkflowRealTimeStatisticsInstance) => any): Promise<WorkflowRealTimeStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new WorkflowRealTimeStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.workflowSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: WorkflowRealTimeStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<WorkflowRealTimeStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkflowRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowRealTimeStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkflowRealTimeStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkflowRealTimeStatisticsInstance> => ({ + ...response, + body: new WorkflowRealTimeStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.workflowSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkflowRealTimeStatisticsPayload extends WorkflowRealTimeStatisticsResource {} + +interface WorkflowRealTimeStatisticsResource { + account_sid: string; + longest_task_waiting_age: number; + longest_task_waiting_sid: string; + tasks_by_priority: any; + tasks_by_status: any; + total_tasks: number; + workflow_sid: string; + workspace_sid: string; + url: string; +} + +export class WorkflowRealTimeStatisticsInstance { + protected _solution: WorkflowRealTimeStatisticsContextSolution; + protected _context?: WorkflowRealTimeStatisticsContext; + + constructor(protected _version: V1, payload: WorkflowRealTimeStatisticsResource, workspaceSid: string, workflowSid: string) { + + this.accountSid = (payload.account_sid); + this.longestTaskWaitingAge = deserialize.integer(payload.longest_task_waiting_age); + this.longestTaskWaitingSid = (payload.longest_task_waiting_sid); + this.tasksByPriority = (payload.tasks_by_priority); + this.tasksByStatus = (payload.tasks_by_status); + this.totalTasks = deserialize.integer(payload.total_tasks); + this.workflowSid = (payload.workflow_sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, workflowSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + */ + accountSid: string; + /** + * The age of the longest waiting Task. + */ + longestTaskWaitingAge: number; + /** + * The SID of the longest waiting Task. + */ + longestTaskWaitingSid: string; + /** + * The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + */ + tasksByPriority: any; + /** + * The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + */ + tasksByStatus: any; + /** + * The total number of Tasks. + */ + totalTasks: number; + /** + * Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + */ + workflowSid: string; + /** + * The SID of the Workspace that contains the Workflow. + */ + workspaceSid: string; + /** + * The absolute URL of the Workflow statistics resource. + */ + url: string; + + private get _proxy(): WorkflowRealTimeStatisticsContext { + this._context = this._context || new WorkflowRealTimeStatisticsContextImpl(this._version, this._solution.workspaceSid, this._solution.workflowSid); + return this._context; + } + + /** + * Fetch a WorkflowRealTimeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowRealTimeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkflowRealTimeStatisticsInstance) => any): Promise<WorkflowRealTimeStatisticsInstance>; + /** + * Fetch a WorkflowRealTimeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowRealTimeStatisticsInstance + */ + fetch(params: WorkflowRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkflowRealTimeStatisticsInstance) => any): Promise<WorkflowRealTimeStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: WorkflowRealTimeStatisticsInstance) => any): Promise<WorkflowRealTimeStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a WorkflowRealTimeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowRealTimeStatisticsInstance>>; + /** + * Fetch a WorkflowRealTimeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkflowRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkflowRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowRealTimeStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkflowRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkflowRealTimeStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + longestTaskWaitingAge: this.longestTaskWaitingAge, + longestTaskWaitingSid: this.longestTaskWaitingSid, + tasksByPriority: this.tasksByPriority, + tasksByStatus: this.tasksByStatus, + totalTasks: this.totalTasks, + workflowSid: this.workflowSid, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkflowRealTimeStatisticsSolution { + workspaceSid: string; + workflowSid: string; +} + +export interface WorkflowRealTimeStatisticsListInstance { + _version: V1; + _solution: WorkflowRealTimeStatisticsSolution; + _uri: string; + + (): WorkflowRealTimeStatisticsContext; + get(): WorkflowRealTimeStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkflowRealTimeStatisticsListInstance(version: V1, workspaceSid: string, workflowSid: string): WorkflowRealTimeStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workflowSid)) { + throw new Error('Parameter \'workflowSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WorkflowRealTimeStatisticsListInstance; + + instance.get = function get(): WorkflowRealTimeStatisticsContext { + return new WorkflowRealTimeStatisticsContextImpl(version, workspaceSid, workflowSid); + } + + instance._version = version; + instance._solution = { workspaceSid, workflowSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/workflow/workflowStatistics.ts b/rest/taskrouter/v1/workspace/workflow/workflowStatistics.ts new file mode 100644 index 000000000..3fedc55a4 --- /dev/null +++ b/rest/taskrouter/v1/workspace/workflow/workflowStatistics.ts @@ -0,0 +1,385 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a WorkflowStatisticsInstance + */ +export interface WorkflowStatisticsContextFetchOptions { + /** Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; + /** A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. */ + "splitByWaitTime"?: string; +} + +export interface WorkflowStatisticsContext { + + /** + * Fetch a WorkflowStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkflowStatisticsInstance) => any): Promise<WorkflowStatisticsInstance>; + /** + * Fetch a WorkflowStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowStatisticsInstance + */ + fetch(params: WorkflowStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkflowStatisticsInstance) => any): Promise<WorkflowStatisticsInstance>; + + /** + * Fetch a WorkflowStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowStatisticsInstance>) => any): Promise<ApiResponse<WorkflowStatisticsInstance>>; + /** + * Fetch a WorkflowStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkflowStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkflowStatisticsInstance>) => any): Promise<ApiResponse<WorkflowStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkflowStatisticsContextSolution { + "workspaceSid": string; + "workflowSid": string; +} + +export class WorkflowStatisticsContextImpl implements WorkflowStatisticsContext { + protected _solution: WorkflowStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string, workflowSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workflowSid)) { + throw new Error('Parameter \'workflowSid\' is not valid.'); + } + + this._solution = { workspaceSid, workflowSid, }; + this._uri = `/Workspaces/${workspaceSid}/Workflows/${workflowSid}/Statistics`; + } + + fetch(params?: WorkflowStatisticsContextFetchOptions | ((error: Error | null, item?: WorkflowStatisticsInstance) => any),callback?: (error: Error | null, item?: WorkflowStatisticsInstance) => any): Promise<WorkflowStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new WorkflowStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid, instance._solution.workflowSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: WorkflowStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<WorkflowStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkflowStatisticsInstance>) => any): Promise<ApiResponse<WorkflowStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkflowStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkflowStatisticsInstance> => ({ + ...response, + body: new WorkflowStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid, instance._solution.workflowSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkflowStatisticsPayload extends WorkflowStatisticsResource {} + +interface WorkflowStatisticsResource { + account_sid: string; + cumulative: any; + realtime: any; + workflow_sid: string; + workspace_sid: string; + url: string; +} + +export class WorkflowStatisticsInstance { + protected _solution: WorkflowStatisticsContextSolution; + protected _context?: WorkflowStatisticsContext; + + constructor(protected _version: V1, payload: WorkflowStatisticsResource, workspaceSid: string, workflowSid: string) { + + this.accountSid = (payload.account_sid); + this.cumulative = (payload.cumulative); + this.realtime = (payload.realtime); + this.workflowSid = (payload.workflow_sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, workflowSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + */ + accountSid: string; + /** + * An object that contains the cumulative statistics for the Workflow. + */ + cumulative: any; + /** + * An object that contains the real-time statistics for the Workflow. + */ + realtime: any; + /** + * Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + */ + workflowSid: string; + /** + * The SID of the Workspace that contains the Workflow. + */ + workspaceSid: string; + /** + * The absolute URL of the Workflow statistics resource. + */ + url: string; + + private get _proxy(): WorkflowStatisticsContext { + this._context = this._context || new WorkflowStatisticsContextImpl(this._version, this._solution.workspaceSid, this._solution.workflowSid); + return this._context; + } + + /** + * Fetch a WorkflowStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkflowStatisticsInstance) => any): Promise<WorkflowStatisticsInstance>; + /** + * Fetch a WorkflowStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowStatisticsInstance + */ + fetch(params: WorkflowStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkflowStatisticsInstance) => any): Promise<WorkflowStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: WorkflowStatisticsInstance) => any): Promise<WorkflowStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a WorkflowStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkflowStatisticsInstance>) => any): Promise<ApiResponse<WorkflowStatisticsInstance>>; + /** + * Fetch a WorkflowStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkflowStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkflowStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkflowStatisticsInstance>) => any): Promise<ApiResponse<WorkflowStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkflowStatisticsInstance>) => any): Promise<ApiResponse<WorkflowStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + cumulative: this.cumulative, + realtime: this.realtime, + workflowSid: this.workflowSid, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkflowStatisticsSolution { + workspaceSid: string; + workflowSid: string; +} + +export interface WorkflowStatisticsListInstance { + _version: V1; + _solution: WorkflowStatisticsSolution; + _uri: string; + + (): WorkflowStatisticsContext; + get(): WorkflowStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkflowStatisticsListInstance(version: V1, workspaceSid: string, workflowSid: string): WorkflowStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + if (!isValidPathParam(workflowSid)) { + throw new Error('Parameter \'workflowSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WorkflowStatisticsListInstance; + + instance.get = function get(): WorkflowStatisticsContext { + return new WorkflowStatisticsContextImpl(version, workspaceSid, workflowSid); + } + + instance._version = version; + instance._solution = { workspaceSid, workflowSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/workspaceCumulativeStatistics.ts b/rest/taskrouter/v1/workspace/workspaceCumulativeStatistics.ts new file mode 100644 index 000000000..99af3e2ef --- /dev/null +++ b/rest/taskrouter/v1/workspace/workspaceCumulativeStatistics.ts @@ -0,0 +1,480 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a WorkspaceCumulativeStatisticsInstance + */ +export interface WorkspaceCumulativeStatisticsContextFetchOptions { + /** Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; + /** A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. */ + "splitByWaitTime"?: string; +} + +export interface WorkspaceCumulativeStatisticsContext { + + /** + * Fetch a WorkspaceCumulativeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceCumulativeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkspaceCumulativeStatisticsInstance) => any): Promise<WorkspaceCumulativeStatisticsInstance>; + /** + * Fetch a WorkspaceCumulativeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceCumulativeStatisticsInstance + */ + fetch(params: WorkspaceCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkspaceCumulativeStatisticsInstance) => any): Promise<WorkspaceCumulativeStatisticsInstance>; + + /** + * Fetch a WorkspaceCumulativeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceCumulativeStatisticsInstance>>; + /** + * Fetch a WorkspaceCumulativeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkspaceCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkspaceCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceCumulativeStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkspaceCumulativeStatisticsContextSolution { + "workspaceSid": string; +} + +export class WorkspaceCumulativeStatisticsContextImpl implements WorkspaceCumulativeStatisticsContext { + protected _solution: WorkspaceCumulativeStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + this._solution = { workspaceSid, }; + this._uri = `/Workspaces/${workspaceSid}/CumulativeStatistics`; + } + + fetch(params?: WorkspaceCumulativeStatisticsContextFetchOptions | ((error: Error | null, item?: WorkspaceCumulativeStatisticsInstance) => any),callback?: (error: Error | null, item?: WorkspaceCumulativeStatisticsInstance) => any): Promise<WorkspaceCumulativeStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new WorkspaceCumulativeStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: WorkspaceCumulativeStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<WorkspaceCumulativeStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkspaceCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceCumulativeStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkspaceCumulativeStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkspaceCumulativeStatisticsInstance> => ({ + ...response, + body: new WorkspaceCumulativeStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkspaceCumulativeStatisticsPayload extends WorkspaceCumulativeStatisticsResource {} + +interface WorkspaceCumulativeStatisticsResource { + account_sid: string; + avg_task_acceptance_time: number; + start_time: Date; + end_time: Date; + reservations_created: number; + reservations_accepted: number; + reservations_rejected: number; + reservations_timed_out: number; + reservations_canceled: number; + reservations_rescinded: number; + split_by_wait_time: any; + wait_duration_until_accepted: any; + wait_duration_until_canceled: any; + tasks_canceled: number; + tasks_completed: number; + tasks_created: number; + tasks_deleted: number; + tasks_moved: number; + tasks_timed_out_in_workflow: number; + workspace_sid: string; + url: string; +} + +export class WorkspaceCumulativeStatisticsInstance { + protected _solution: WorkspaceCumulativeStatisticsContextSolution; + protected _context?: WorkspaceCumulativeStatisticsContext; + + constructor(protected _version: V1, payload: WorkspaceCumulativeStatisticsResource, workspaceSid: string) { + + this.accountSid = (payload.account_sid); + this.avgTaskAcceptanceTime = deserialize.integer(payload.avg_task_acceptance_time); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.reservationsCreated = deserialize.integer(payload.reservations_created); + this.reservationsAccepted = deserialize.integer(payload.reservations_accepted); + this.reservationsRejected = deserialize.integer(payload.reservations_rejected); + this.reservationsTimedOut = deserialize.integer(payload.reservations_timed_out); + this.reservationsCanceled = deserialize.integer(payload.reservations_canceled); + this.reservationsRescinded = deserialize.integer(payload.reservations_rescinded); + this.splitByWaitTime = (payload.split_by_wait_time); + this.waitDurationUntilAccepted = (payload.wait_duration_until_accepted); + this.waitDurationUntilCanceled = (payload.wait_duration_until_canceled); + this.tasksCanceled = deserialize.integer(payload.tasks_canceled); + this.tasksCompleted = deserialize.integer(payload.tasks_completed); + this.tasksCreated = deserialize.integer(payload.tasks_created); + this.tasksDeleted = deserialize.integer(payload.tasks_deleted); + this.tasksMoved = deserialize.integer(payload.tasks_moved); + this.tasksTimedOutInWorkflow = deserialize.integer(payload.tasks_timed_out_in_workflow); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + */ + accountSid: string; + /** + * The average time in seconds between Task creation and acceptance. + */ + avgTaskAcceptanceTime: number; + /** + * The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + startTime: Date; + /** + * The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + endTime: Date; + /** + * The total number of Reservations that were created for Workers. + */ + reservationsCreated: number; + /** + * The total number of Reservations accepted by Workers. + */ + reservationsAccepted: number; + /** + * The total number of Reservations that were rejected. + */ + reservationsRejected: number; + /** + * The total number of Reservations that were timed out. + */ + reservationsTimedOut: number; + /** + * The total number of Reservations that were canceled. + */ + reservationsCanceled: number; + /** + * The total number of Reservations that were rescinded. + */ + reservationsRescinded: number; + /** + * A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + */ + splitByWaitTime: any; + /** + * The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were accepted. + */ + waitDurationUntilAccepted: any; + /** + * The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were canceled. + */ + waitDurationUntilCanceled: any; + /** + * The total number of Tasks that were canceled. + */ + tasksCanceled: number; + /** + * The total number of Tasks that were completed. + */ + tasksCompleted: number; + /** + * The total number of Tasks created. + */ + tasksCreated: number; + /** + * The total number of Tasks that were deleted. + */ + tasksDeleted: number; + /** + * The total number of Tasks that were moved from one queue to another. + */ + tasksMoved: number; + /** + * The total number of Tasks that were timed out of their Workflows (and deleted). + */ + tasksTimedOutInWorkflow: number; + /** + * The SID of the Workspace. + */ + workspaceSid: string; + /** + * The absolute URL of the Workspace statistics resource. + */ + url: string; + + private get _proxy(): WorkspaceCumulativeStatisticsContext { + this._context = this._context || new WorkspaceCumulativeStatisticsContextImpl(this._version, this._solution.workspaceSid); + return this._context; + } + + /** + * Fetch a WorkspaceCumulativeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceCumulativeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkspaceCumulativeStatisticsInstance) => any): Promise<WorkspaceCumulativeStatisticsInstance>; + /** + * Fetch a WorkspaceCumulativeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceCumulativeStatisticsInstance + */ + fetch(params: WorkspaceCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkspaceCumulativeStatisticsInstance) => any): Promise<WorkspaceCumulativeStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: WorkspaceCumulativeStatisticsInstance) => any): Promise<WorkspaceCumulativeStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a WorkspaceCumulativeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceCumulativeStatisticsInstance>>; + /** + * Fetch a WorkspaceCumulativeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceCumulativeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkspaceCumulativeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkspaceCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceCumulativeStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkspaceCumulativeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceCumulativeStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + avgTaskAcceptanceTime: this.avgTaskAcceptanceTime, + startTime: this.startTime, + endTime: this.endTime, + reservationsCreated: this.reservationsCreated, + reservationsAccepted: this.reservationsAccepted, + reservationsRejected: this.reservationsRejected, + reservationsTimedOut: this.reservationsTimedOut, + reservationsCanceled: this.reservationsCanceled, + reservationsRescinded: this.reservationsRescinded, + splitByWaitTime: this.splitByWaitTime, + waitDurationUntilAccepted: this.waitDurationUntilAccepted, + waitDurationUntilCanceled: this.waitDurationUntilCanceled, + tasksCanceled: this.tasksCanceled, + tasksCompleted: this.tasksCompleted, + tasksCreated: this.tasksCreated, + tasksDeleted: this.tasksDeleted, + tasksMoved: this.tasksMoved, + tasksTimedOutInWorkflow: this.tasksTimedOutInWorkflow, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkspaceCumulativeStatisticsSolution { + workspaceSid: string; +} + +export interface WorkspaceCumulativeStatisticsListInstance { + _version: V1; + _solution: WorkspaceCumulativeStatisticsSolution; + _uri: string; + + (): WorkspaceCumulativeStatisticsContext; + get(): WorkspaceCumulativeStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkspaceCumulativeStatisticsListInstance(version: V1, workspaceSid: string): WorkspaceCumulativeStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WorkspaceCumulativeStatisticsListInstance; + + instance.get = function get(): WorkspaceCumulativeStatisticsContext { + return new WorkspaceCumulativeStatisticsContextImpl(version, workspaceSid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/workspaceRealTimeStatistics.ts b/rest/taskrouter/v1/workspace/workspaceRealTimeStatistics.ts new file mode 100644 index 000000000..18cbd8293 --- /dev/null +++ b/rest/taskrouter/v1/workspace/workspaceRealTimeStatistics.ts @@ -0,0 +1,379 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a WorkspaceRealTimeStatisticsInstance + */ +export interface WorkspaceRealTimeStatisticsContextFetchOptions { + /** Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; +} + +export interface WorkspaceRealTimeStatisticsContext { + + /** + * Fetch a WorkspaceRealTimeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceRealTimeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkspaceRealTimeStatisticsInstance) => any): Promise<WorkspaceRealTimeStatisticsInstance>; + /** + * Fetch a WorkspaceRealTimeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceRealTimeStatisticsInstance + */ + fetch(params: WorkspaceRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkspaceRealTimeStatisticsInstance) => any): Promise<WorkspaceRealTimeStatisticsInstance>; + + /** + * Fetch a WorkspaceRealTimeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceRealTimeStatisticsInstance>>; + /** + * Fetch a WorkspaceRealTimeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkspaceRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkspaceRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceRealTimeStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkspaceRealTimeStatisticsContextSolution { + "workspaceSid": string; +} + +export class WorkspaceRealTimeStatisticsContextImpl implements WorkspaceRealTimeStatisticsContext { + protected _solution: WorkspaceRealTimeStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + this._solution = { workspaceSid, }; + this._uri = `/Workspaces/${workspaceSid}/RealTimeStatistics`; + } + + fetch(params?: WorkspaceRealTimeStatisticsContextFetchOptions | ((error: Error | null, item?: WorkspaceRealTimeStatisticsInstance) => any),callback?: (error: Error | null, item?: WorkspaceRealTimeStatisticsInstance) => any): Promise<WorkspaceRealTimeStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new WorkspaceRealTimeStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: WorkspaceRealTimeStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<WorkspaceRealTimeStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkspaceRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceRealTimeStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkspaceRealTimeStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkspaceRealTimeStatisticsInstance> => ({ + ...response, + body: new WorkspaceRealTimeStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkspaceRealTimeStatisticsPayload extends WorkspaceRealTimeStatisticsResource {} + +interface WorkspaceRealTimeStatisticsResource { + account_sid: string; + activity_statistics: Array<any>; + longest_task_waiting_age: number; + longest_task_waiting_sid: string; + tasks_by_priority: any; + tasks_by_status: any; + total_tasks: number; + total_workers: number; + workspace_sid: string; + url: string; +} + +export class WorkspaceRealTimeStatisticsInstance { + protected _solution: WorkspaceRealTimeStatisticsContextSolution; + protected _context?: WorkspaceRealTimeStatisticsContext; + + constructor(protected _version: V1, payload: WorkspaceRealTimeStatisticsResource, workspaceSid: string) { + + this.accountSid = (payload.account_sid); + this.activityStatistics = (payload.activity_statistics); + this.longestTaskWaitingAge = deserialize.integer(payload.longest_task_waiting_age); + this.longestTaskWaitingSid = (payload.longest_task_waiting_sid); + this.tasksByPriority = (payload.tasks_by_priority); + this.tasksByStatus = (payload.tasks_by_status); + this.totalTasks = deserialize.integer(payload.total_tasks); + this.totalWorkers = deserialize.integer(payload.total_workers); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + */ + accountSid: string; + /** + * The number of current Workers by Activity. + */ + activityStatistics: Array<any>; + /** + * The age of the longest waiting Task. + */ + longestTaskWaitingAge: number; + /** + * The SID of the longest waiting Task. + */ + longestTaskWaitingSid: string; + /** + * The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + */ + tasksByPriority: any; + /** + * The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + */ + tasksByStatus: any; + /** + * The total number of Tasks. + */ + totalTasks: number; + /** + * The total number of Workers in the Workspace. + */ + totalWorkers: number; + /** + * The SID of the Workspace. + */ + workspaceSid: string; + /** + * The absolute URL of the Workspace statistics resource. + */ + url: string; + + private get _proxy(): WorkspaceRealTimeStatisticsContext { + this._context = this._context || new WorkspaceRealTimeStatisticsContextImpl(this._version, this._solution.workspaceSid); + return this._context; + } + + /** + * Fetch a WorkspaceRealTimeStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceRealTimeStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkspaceRealTimeStatisticsInstance) => any): Promise<WorkspaceRealTimeStatisticsInstance>; + /** + * Fetch a WorkspaceRealTimeStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceRealTimeStatisticsInstance + */ + fetch(params: WorkspaceRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkspaceRealTimeStatisticsInstance) => any): Promise<WorkspaceRealTimeStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: WorkspaceRealTimeStatisticsInstance) => any): Promise<WorkspaceRealTimeStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a WorkspaceRealTimeStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceRealTimeStatisticsInstance>>; + /** + * Fetch a WorkspaceRealTimeStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceRealTimeStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkspaceRealTimeStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkspaceRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceRealTimeStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkspaceRealTimeStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceRealTimeStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + activityStatistics: this.activityStatistics, + longestTaskWaitingAge: this.longestTaskWaitingAge, + longestTaskWaitingSid: this.longestTaskWaitingSid, + tasksByPriority: this.tasksByPriority, + tasksByStatus: this.tasksByStatus, + totalTasks: this.totalTasks, + totalWorkers: this.totalWorkers, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkspaceRealTimeStatisticsSolution { + workspaceSid: string; +} + +export interface WorkspaceRealTimeStatisticsListInstance { + _version: V1; + _solution: WorkspaceRealTimeStatisticsSolution; + _uri: string; + + (): WorkspaceRealTimeStatisticsContext; + get(): WorkspaceRealTimeStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkspaceRealTimeStatisticsListInstance(version: V1, workspaceSid: string): WorkspaceRealTimeStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WorkspaceRealTimeStatisticsListInstance; + + instance.get = function get(): WorkspaceRealTimeStatisticsContext { + return new WorkspaceRealTimeStatisticsContextImpl(version, workspaceSid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/taskrouter/v1/workspace/workspaceStatistics.ts b/rest/taskrouter/v1/workspace/workspaceStatistics.ts new file mode 100644 index 000000000..bb357cf6b --- /dev/null +++ b/rest/taskrouter/v1/workspace/workspaceStatistics.ts @@ -0,0 +1,368 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Taskrouter + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to fetch a WorkspaceStatisticsInstance + */ +export interface WorkspaceStatisticsContextFetchOptions { + /** Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. */ + "minutes"?: number; + /** Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. */ + "startDate"?: Date; + /** Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. */ + "endDate"?: Date; + /** Only calculate statistics on this TaskChannel. Can be the TaskChannel\'s SID or its `unique_name`, such as `voice`, `sms`, or `default`. */ + "taskChannel"?: string; + /** A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. */ + "splitByWaitTime"?: string; +} + +export interface WorkspaceStatisticsContext { + + /** + * Fetch a WorkspaceStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkspaceStatisticsInstance) => any): Promise<WorkspaceStatisticsInstance>; + /** + * Fetch a WorkspaceStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceStatisticsInstance + */ + fetch(params: WorkspaceStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkspaceStatisticsInstance) => any): Promise<WorkspaceStatisticsInstance>; + + /** + * Fetch a WorkspaceStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceStatisticsInstance>>; + /** + * Fetch a WorkspaceStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkspaceStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkspaceStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceStatisticsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WorkspaceStatisticsContextSolution { + "workspaceSid": string; +} + +export class WorkspaceStatisticsContextImpl implements WorkspaceStatisticsContext { + protected _solution: WorkspaceStatisticsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, workspaceSid: string) { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + this._solution = { workspaceSid, }; + this._uri = `/Workspaces/${workspaceSid}/Statistics`; + } + + fetch(params?: WorkspaceStatisticsContextFetchOptions | ((error: Error | null, item?: WorkspaceStatisticsInstance) => any),callback?: (error: Error | null, item?: WorkspaceStatisticsInstance) => any): Promise<WorkspaceStatisticsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new WorkspaceStatisticsInstance(operationVersion, payload, instance._solution.workspaceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: WorkspaceStatisticsContextFetchOptions | ((error: Error | null, item?: ApiResponse<WorkspaceStatisticsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WorkspaceStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceStatisticsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["minutes"] !== undefined) + data["Minutes"] = params["minutes"]; + if (params["startDate"] !== undefined) + data["StartDate"] = serialize.iso8601DateTime(params["startDate"]); + if (params["endDate"] !== undefined) + data["EndDate"] = serialize.iso8601DateTime(params["endDate"]); + if (params["taskChannel"] !== undefined) + data["TaskChannel"] = params["taskChannel"]; + if (params["splitByWaitTime"] !== undefined) + data["SplitByWaitTime"] = params["splitByWaitTime"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WorkspaceStatisticsResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WorkspaceStatisticsInstance> => ({ + ...response, + body: new WorkspaceStatisticsInstance(operationVersion, response.body, instance._solution.workspaceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WorkspaceStatisticsPayload extends WorkspaceStatisticsResource {} + +interface WorkspaceStatisticsResource { + realtime: any; + cumulative: any; + account_sid: string; + workspace_sid: string; + url: string; +} + +export class WorkspaceStatisticsInstance { + protected _solution: WorkspaceStatisticsContextSolution; + protected _context?: WorkspaceStatisticsContext; + + constructor(protected _version: V1, payload: WorkspaceStatisticsResource, workspaceSid: string) { + + this.realtime = (payload.realtime); + this.cumulative = (payload.cumulative); + this.accountSid = (payload.account_sid); + this.workspaceSid = (payload.workspace_sid); + this.url = (payload.url); + + this._solution = { workspaceSid, }; + } + + /** + * An object that contains the real-time statistics for the Workspace. + */ + realtime: any; + /** + * An object that contains the cumulative statistics for the Workspace. + */ + cumulative: any; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + */ + accountSid: string; + /** + * The SID of the Workspace. + */ + workspaceSid: string; + /** + * The absolute URL of the Workspace statistics resource. + */ + url: string; + + private get _proxy(): WorkspaceStatisticsContext { + this._context = this._context || new WorkspaceStatisticsContextImpl(this._version, this._solution.workspaceSid); + return this._context; + } + + /** + * Fetch a WorkspaceStatisticsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceStatisticsInstance + */ + fetch(callback?: (error: Error | null, item?: WorkspaceStatisticsInstance) => any): Promise<WorkspaceStatisticsInstance>; + /** + * Fetch a WorkspaceStatisticsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceStatisticsInstance + */ + fetch(params: WorkspaceStatisticsContextFetchOptions, callback?: (error: Error | null, item?: WorkspaceStatisticsInstance) => any): Promise<WorkspaceStatisticsInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: WorkspaceStatisticsInstance) => any): Promise<WorkspaceStatisticsInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a WorkspaceStatisticsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WorkspaceStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceStatisticsInstance>>; + /** + * Fetch a WorkspaceStatisticsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WorkspaceStatisticsInstance with HTTP metadata + */ + fetchWithHttpInfo(params: WorkspaceStatisticsContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<WorkspaceStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceStatisticsInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WorkspaceStatisticsInstance>) => any): Promise<ApiResponse<WorkspaceStatisticsInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + realtime: this.realtime, + cumulative: this.cumulative, + accountSid: this.accountSid, + workspaceSid: this.workspaceSid, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WorkspaceStatisticsSolution { + workspaceSid: string; +} + +export interface WorkspaceStatisticsListInstance { + _version: V1; + _solution: WorkspaceStatisticsSolution; + _uri: string; + + (): WorkspaceStatisticsContext; + get(): WorkspaceStatisticsContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WorkspaceStatisticsListInstance(version: V1, workspaceSid: string): WorkspaceStatisticsListInstance { + if (!isValidPathParam(workspaceSid)) { + throw new Error('Parameter \'workspaceSid\' is not valid.'); + } + + const instance = (() => instance.get()) as WorkspaceStatisticsListInstance; + + instance.get = function get(): WorkspaceStatisticsContext { + return new WorkspaceStatisticsContextImpl(version, workspaceSid); + } + + instance._version = version; + instance._solution = { workspaceSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/trunking/V1.ts b/rest/trunking/V1.ts new file mode 100644 index 000000000..3320470b6 --- /dev/null +++ b/rest/trunking/V1.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trunking + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import TrunkingBase from "../TrunkingBase"; +import Version from "../../base/Version"; +import { TrunkListInstance } from "./v1/trunk"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Trunking + * + * @param domain - The Twilio (Twilio.Trunking) domain + */ + constructor(domain: TrunkingBase) { + super(domain, "v1"); + } + + /** trunks - { Twilio.Trunking.V1.TrunkListInstance } resource */ + protected _trunks?: TrunkListInstance; + + /** Getter for trunks resource */ + get trunks(): TrunkListInstance { + this._trunks = this._trunks || TrunkListInstance(this); + return this._trunks; + } + +} diff --git a/rest/trunking/v1/trunk.ts b/rest/trunking/v1/trunk.ts new file mode 100644 index 000000000..8030d4e11 --- /dev/null +++ b/rest/trunking/v1/trunk.ts @@ -0,0 +1,1150 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trunking + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { CredentialListListInstance } from "./trunk/credentialList"; +import { IpAccessControlListListInstance } from "./trunk/ipAccessControlList"; +import { OriginationUrlListInstance } from "./trunk/originationUrl"; +import { PhoneNumberListInstance } from "./trunk/phoneNumber"; +import { RecordingListInstance } from "./trunk/recording"; + + +/** + * Caller Id for transfer target. Can be: `from-transferee` (default) or `from-transferor`. + */ +export type TrunkTransferCallerId = 'from-transferee'|'from-transferor'; + +/** + * The call transfer settings for the trunk. Can be: `enable-all`, `sip-only` and `disable-all`. See [Transfer](https://www.twilio.com/docs/sip-trunking/call-transfer) for more information. + */ +export type TrunkTransferSetting = 'disable-all'|'enable-all'|'sip-only'; + + + + +/** + * Options to pass to update a TrunkInstance + */ +export interface TrunkContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. */ + "domainName"?: string; + /** The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. */ + "disasterRecoveryUrl"?: string; + /** The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. */ + "disasterRecoveryMethod"?: string; + /** */ + "transferMode"?: TrunkTransferSetting; + /** Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. */ + "secure"?: boolean; + /** Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. */ + "cnamLookupEnabled"?: boolean; + /** */ + "transferCallerId"?: TrunkTransferCallerId; +} + +/** + * Options to pass to create a TrunkInstance + */ +export interface TrunkListInstanceCreateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. */ + "domainName"?: string; + /** The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. */ + "disasterRecoveryUrl"?: string; + /** The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. */ + "disasterRecoveryMethod"?: string; + /** */ + "transferMode"?: TrunkTransferSetting; + /** Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. */ + "secure"?: boolean; + /** Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. */ + "cnamLookupEnabled"?: boolean; + /** */ + "transferCallerId"?: TrunkTransferCallerId; +} + +/** + * Options to pass to each + */ +export interface TrunkListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TrunkInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TrunkListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TrunkListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TrunkContext { + credentialsLists: CredentialListListInstance; + ipAccessControlLists: IpAccessControlListListInstance; + originationUrls: OriginationUrlListInstance; + phoneNumbers: PhoneNumberListInstance; + recordings: RecordingListInstance; + + /** + * Remove a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + fetch(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance> + + /** + * Fetch a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> + + /** + * Update a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + update(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance>; + /** + * Update a TrunkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + update(params: TrunkContextUpdateOptions, callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance>; + + /** + * Update a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>>; + /** + * Update a TrunkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + updateWithHttpInfo(params: TrunkContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TrunkContextSolution { + "sid": string; +} + +export class TrunkContextImpl implements TrunkContext { + protected _solution: TrunkContextSolution; + protected _uri: string; + + protected _credentialsLists?: CredentialListListInstance; + protected _ipAccessControlLists?: IpAccessControlListListInstance; + protected _originationUrls?: OriginationUrlListInstance; + protected _phoneNumbers?: PhoneNumberListInstance; + protected _recordings?: RecordingListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Trunks/${sid}`; + } + + get credentialsLists(): CredentialListListInstance { + this._credentialsLists = this._credentialsLists || CredentialListListInstance(this._version, this._solution.sid); + return this._credentialsLists; + } + + get ipAccessControlLists(): IpAccessControlListListInstance { + this._ipAccessControlLists = this._ipAccessControlLists || IpAccessControlListListInstance(this._version, this._solution.sid); + return this._ipAccessControlLists; + } + + get originationUrls(): OriginationUrlListInstance { + this._originationUrls = this._originationUrls || OriginationUrlListInstance(this._version, this._solution.sid); + return this._originationUrls; + } + + get phoneNumbers(): PhoneNumberListInstance { + this._phoneNumbers = this._phoneNumbers || PhoneNumberListInstance(this._version, this._solution.sid); + return this._phoneNumbers; + } + + get recordings(): RecordingListInstance { + this._recordings = this._recordings || RecordingListInstance(this._version, this._solution.sid); + return this._recordings; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TrunkInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TrunkResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TrunkInstance> => ({ + ...response, + body: new TrunkInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: TrunkContextUpdateOptions | ((error: Error | null, item?: TrunkInstance) => any),callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["domainName"] !== undefined) + data["DomainName"] = params["domainName"]; + if (params["disasterRecoveryUrl"] !== undefined) + data["DisasterRecoveryUrl"] = params["disasterRecoveryUrl"]; + if (params["disasterRecoveryMethod"] !== undefined) + data["DisasterRecoveryMethod"] = params["disasterRecoveryMethod"]; + if (params["transferMode"] !== undefined) + data["TransferMode"] = params["transferMode"]; + if (params["secure"] !== undefined) + data["Secure"] = serialize.bool(params["secure"]); + if (params["cnamLookupEnabled"] !== undefined) + data["CnamLookupEnabled"] = serialize.bool(params["cnamLookupEnabled"]); + if (params["transferCallerId"] !== undefined) + data["TransferCallerId"] = params["transferCallerId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TrunkInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: TrunkContextUpdateOptions | ((error: Error | null, item?: ApiResponse<TrunkInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["domainName"] !== undefined) + data["DomainName"] = params["domainName"]; + if (params["disasterRecoveryUrl"] !== undefined) + data["DisasterRecoveryUrl"] = params["disasterRecoveryUrl"]; + if (params["disasterRecoveryMethod"] !== undefined) + data["DisasterRecoveryMethod"] = params["disasterRecoveryMethod"]; + if (params["transferMode"] !== undefined) + data["TransferMode"] = params["transferMode"]; + if (params["secure"] !== undefined) + data["Secure"] = serialize.bool(params["secure"]); + if (params["cnamLookupEnabled"] !== undefined) + data["CnamLookupEnabled"] = serialize.bool(params["cnamLookupEnabled"]); + if (params["transferCallerId"] !== undefined) + data["TransferCallerId"] = params["transferCallerId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<TrunkResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TrunkInstance> => ({ + ...response, + body: new TrunkInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TrunkPayload extends TwilioResponsePayload { + trunks: TrunkResource[]; +} + +interface TrunkResource { + account_sid: string; + domain_name: string; + disaster_recovery_method: string; + disaster_recovery_url: string; + friendly_name: string; + secure: boolean; + recording: any; + transfer_mode: TrunkTransferSetting; + transfer_caller_id: TrunkTransferCallerId; + cnam_lookup_enabled: boolean; + auth_type: string; + symmetric_rtp_enabled: boolean; + auth_type_set: Array<string>; + date_created: Date; + date_updated: Date; + sid: string; + url: string; + links: Record<string, string>; +} + +export class TrunkInstance { + protected _solution: TrunkContextSolution; + protected _context?: TrunkContext; + + constructor(protected _version: V1, payload: TrunkResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.domainName = (payload.domain_name); + this.disasterRecoveryMethod = (payload.disaster_recovery_method); + this.disasterRecoveryUrl = (payload.disaster_recovery_url); + this.friendlyName = (payload.friendly_name); + this.secure = (payload.secure); + this.recording = (payload.recording); + this.transferMode = payload.transfer_mode; + this.transferCallerId = payload.transfer_caller_id; + this.cnamLookupEnabled = (payload.cnam_lookup_enabled); + this.authType = (payload.auth_type); + this.symmetricRtpEnabled = (payload.symmetric_rtp_enabled); + this.authTypeSet = (payload.auth_type_set); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.sid = (payload.sid); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Trunk resource. + */ + accountSid: string; + /** + * The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + */ + domainName: string; + /** + * The HTTP method we use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + */ + disasterRecoveryMethod: string; + /** + * The URL we call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from this URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + */ + disasterRecoveryUrl: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + */ + secure: boolean; + /** + * The recording settings for the trunk. Can be: `do-not-record`, `record-from-ringing`, `record-from-answer`. If set to `record-from-ringing` or `record-from-answer`, all calls going through the trunk will be recorded. The only way to change recording parameters is on a sub-resource of a Trunk after it has been created. e.g.`/Trunks/[Trunk_SID]/Recording -XPOST -d\'Mode=record-from-answer\'`. See [Recording](https://www.twilio.com/docs/sip-trunking#recording) for more information. + */ + recording: any; + transferMode: TrunkTransferSetting; + transferCallerId: TrunkTransferCallerId; + /** + * Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + */ + cnamLookupEnabled: boolean; + /** + * The types of authentication mapped to the domain. Can be: `IP_ACL` and `CREDENTIAL_LIST`. If both are mapped, the values are returned in a comma delimited list. If empty, the domain will not receive any traffic. + */ + authType: string; + /** + * Whether Symmetric RTP is enabled for the trunk. When Symmetric RTP is disabled, Twilio will send RTP to the destination negotiated in the SDP. Disabling Symmetric RTP is considered to be more secure and therefore recommended. See [Symmetric RTP](https://www.twilio.com/docs/sip-trunking#symmetric-rtp) for more information. + */ + symmetricRtpEnabled: boolean; + /** + * Reserved. + */ + authTypeSet: Array<string>; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The unique string that we created to identify the Trunk resource. + */ + sid: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): TrunkContext { + this._context = this._context || new TrunkContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + fetch(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + update(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance>; + /** + * Update a TrunkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + update(params: TrunkContextUpdateOptions, callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance>; + + update(params?: any, callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>>; + /** + * Update a TrunkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + updateWithHttpInfo(params: TrunkContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the credentialsLists. + */ + credentialsLists(): CredentialListListInstance { + return this._proxy.credentialsLists; + } + + /** + * Access the ipAccessControlLists. + */ + ipAccessControlLists(): IpAccessControlListListInstance { + return this._proxy.ipAccessControlLists; + } + + /** + * Access the originationUrls. + */ + originationUrls(): OriginationUrlListInstance { + return this._proxy.originationUrls; + } + + /** + * Access the phoneNumbers. + */ + phoneNumbers(): PhoneNumberListInstance { + return this._proxy.phoneNumbers; + } + + /** + * Access the recordings. + */ + recordings(): RecordingListInstance { + return this._proxy.recordings; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + domainName: this.domainName, + disasterRecoveryMethod: this.disasterRecoveryMethod, + disasterRecoveryUrl: this.disasterRecoveryUrl, + friendlyName: this.friendlyName, + secure: this.secure, + recording: this.recording, + transferMode: this.transferMode, + transferCallerId: this.transferCallerId, + cnamLookupEnabled: this.cnamLookupEnabled, + authType: this.authType, + symmetricRtpEnabled: this.symmetricRtpEnabled, + authTypeSet: this.authTypeSet, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + sid: this.sid, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TrunkSolution { +} + +export interface TrunkListInstance { + _version: V1; + _solution: TrunkSolution; + _uri: string; + + (sid: string, ): TrunkContext; + get(sid: string, ): TrunkContext; + + + + + + + + + /** + * Create a TrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + create(callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance>; + /** + * Create a TrunkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance + */ + create(params: TrunkListInstanceCreateOptions, callback?: (error: Error | null, item?: TrunkInstance) => any): Promise<TrunkInstance>; + + /** + * Create a TrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>>; + /** + * Create a TrunkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrunkInstance with HTTP metadata + */ + createWithHttpInfo(params: TrunkListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>>; + + + + + /** + * Streams TrunkInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrunkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TrunkInstance, done: (err?: Error) => void) => void): void; + each(params: TrunkListInstanceEachOptions, callback?: (item: TrunkInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TrunkInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrunkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TrunkInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TrunkListInstanceEachOptions, callback?: (item: TrunkInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TrunkInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TrunkPage) => any): Promise<TrunkPage>; + /** + * Retrieve a single target page of TrunkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TrunkPage>) => any): Promise<ApiResponse<TrunkPage>>; + /** + * Lists TrunkInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrunkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TrunkInstance[]) => any): Promise<TrunkInstance[]>; + list(params: TrunkListInstanceOptions, callback?: (error: Error | null, items: TrunkInstance[]) => any): Promise<TrunkInstance[]>; + /** + * Lists TrunkInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrunkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TrunkInstance[]>) => any): Promise<ApiResponse<TrunkInstance[]>>; + listWithHttpInfo(params: TrunkListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TrunkInstance[]>) => any): Promise<ApiResponse<TrunkInstance[]>>; + /** + * Retrieve a single page of TrunkInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrunkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TrunkPage) => any): Promise<TrunkPage>; + page(params: TrunkListInstancePageOptions, callback?: (error: Error | null, items: TrunkPage) => any): Promise<TrunkPage>; + /** + * Retrieve a single page of TrunkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrunkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TrunkPage>) => any): Promise<ApiResponse<TrunkPage>>; + pageWithHttpInfo(params: TrunkListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TrunkPage>) => any): Promise<ApiResponse<TrunkPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TrunkListInstance(version: V1): TrunkListInstance { + const instance = ((sid, ) => instance.get(sid, )) as TrunkListInstance; + + instance.get = function get(sid, ): TrunkContext { + return new TrunkContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Trunks`; + + instance.create = function create(params?: TrunkListInstanceCreateOptions | ((error: Error | null, items: TrunkInstance) => any), callback?: (error: Error | null, items: TrunkInstance) => any): Promise<TrunkInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["domainName"] !== undefined) + data["DomainName"] = params["domainName"]; + if (params["disasterRecoveryUrl"] !== undefined) + data["DisasterRecoveryUrl"] = params["disasterRecoveryUrl"]; + if (params["disasterRecoveryMethod"] !== undefined) + data["DisasterRecoveryMethod"] = params["disasterRecoveryMethod"]; + if (params["transferMode"] !== undefined) + data["TransferMode"] = params["transferMode"]; + if (params["secure"] !== undefined) + data["Secure"] = serialize.bool(params["secure"]); + if (params["cnamLookupEnabled"] !== undefined) + data["CnamLookupEnabled"] = serialize.bool(params["cnamLookupEnabled"]); + if (params["transferCallerId"] !== undefined) + data["TransferCallerId"] = params["transferCallerId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TrunkInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: TrunkListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<TrunkInstance>) => any), callback?: (error: Error | null, items: ApiResponse<TrunkInstance>) => any): Promise<ApiResponse<TrunkInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["domainName"] !== undefined) + data["DomainName"] = params["domainName"]; + if (params["disasterRecoveryUrl"] !== undefined) + data["DisasterRecoveryUrl"] = params["disasterRecoveryUrl"]; + if (params["disasterRecoveryMethod"] !== undefined) + data["DisasterRecoveryMethod"] = params["disasterRecoveryMethod"]; + if (params["transferMode"] !== undefined) + data["TransferMode"] = params["transferMode"]; + if (params["secure"] !== undefined) + data["Secure"] = serialize.bool(params["secure"]); + if (params["cnamLookupEnabled"] !== undefined) + data["CnamLookupEnabled"] = serialize.bool(params["cnamLookupEnabled"]); + if (params["transferCallerId"] !== undefined) + data["TransferCallerId"] = params["transferCallerId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TrunkResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TrunkInstance> => ({ + ...response, + body: new TrunkInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TrunkListInstancePageOptions | ((error: Error | null, items: TrunkPage) => any), callback?: (error: Error | null, items: TrunkPage) => any): Promise<TrunkPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TrunkPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TrunkPage) => any): Promise<TrunkPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TrunkPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TrunkListInstancePageOptions | ((error: Error | null, items: ApiResponse<TrunkPage>) => any), callback?: (error: Error | null, items: ApiResponse<TrunkPage>) => any): Promise<ApiResponse<TrunkPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TrunkPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TrunkPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TrunkPage>) => any): Promise<ApiResponse<TrunkPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TrunkPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TrunkPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TrunkPage extends Page<V1, TrunkPayload, TrunkResource, TrunkInstance> { +/** +* Initialize the TrunkPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TrunkSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TrunkInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TrunkResource): TrunkInstance { + + return new TrunkInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trunking/v1/trunk/credentialList.ts b/rest/trunking/v1/trunk/credentialList.ts new file mode 100644 index 000000000..49a37ded7 --- /dev/null +++ b/rest/trunking/v1/trunk/credentialList.ts @@ -0,0 +1,746 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trunking + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a CredentialListInstance + */ +export interface CredentialListListInstanceCreateOptions { + /** The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. */ + "credentialListSid": string; +} + +/** + * Options to pass to each + */ +export interface CredentialListListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CredentialListInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CredentialListListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CredentialListListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CredentialListContext { + + /** + * Remove a CredentialListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a CredentialListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a CredentialListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise<CredentialListInstance> + + /** + * Fetch a CredentialListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CredentialListInstance>) => any): Promise<ApiResponse<CredentialListInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CredentialListContextSolution { + "trunkSid": string; + "sid": string; +} + +export class CredentialListContextImpl implements CredentialListContext { + protected _solution: CredentialListContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, trunkSid: string, sid: string) { + if (!isValidPathParam(trunkSid)) { + throw new Error('Parameter \'trunkSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { trunkSid, sid, }; + this._uri = `/Trunks/${trunkSid}/CredentialLists/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise<CredentialListInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CredentialListInstance(operationVersion, payload, instance._solution.trunkSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CredentialListInstance>) => any): Promise<ApiResponse<CredentialListInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CredentialListResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CredentialListInstance> => ({ + ...response, + body: new CredentialListInstance(operationVersion, response.body, instance._solution.trunkSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CredentialListPayload extends TwilioResponsePayload { + credential_lists: CredentialListResource[]; +} + +interface CredentialListResource { + account_sid: string; + sid: string; + trunk_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CredentialListInstance { + protected _solution: CredentialListContextSolution; + protected _context?: CredentialListContext; + + constructor(protected _version: V1, payload: CredentialListResource, trunkSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.trunkSid = (payload.trunk_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { trunkSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialList resource. + */ + accountSid: string; + /** + * The unique string that we created to identify the CredentialList resource. + */ + sid: string; + /** + * The SID of the Trunk the credential list in associated with. + */ + trunkSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): CredentialListContext { + this._context = this._context || new CredentialListContextImpl(this._version, this._solution.trunkSid, this._solution.sid); + return this._context; + } + + /** + * Remove a CredentialListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CredentialListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CredentialListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance + */ + fetch(callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise<CredentialListInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CredentialListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CredentialListInstance>) => any): Promise<ApiResponse<CredentialListInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + trunkSid: this.trunkSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CredentialListSolution { + trunkSid: string; +} + +export interface CredentialListListInstance { + _version: V1; + _solution: CredentialListSolution; + _uri: string; + + (sid: string, ): CredentialListContext; + get(sid: string, ): CredentialListContext; + + + + + + + /** + * Create a CredentialListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance + */ + create(params: CredentialListListInstanceCreateOptions, callback?: (error: Error | null, item?: CredentialListInstance) => any): Promise<CredentialListInstance>; + + /** + * Create a CredentialListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CredentialListInstance with HTTP metadata + */ + createWithHttpInfo(params: CredentialListListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CredentialListInstance>) => any): Promise<ApiResponse<CredentialListInstance>>; + + + + + /** + * Streams CredentialListInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CredentialListInstance, done: (err?: Error) => void) => void): void; + each(params: CredentialListListInstanceEachOptions, callback?: (item: CredentialListInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CredentialListInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CredentialListInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CredentialListListInstanceEachOptions, callback?: (item: CredentialListInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CredentialListInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialListPage) => any): Promise<CredentialListPage>; + /** + * Retrieve a single target page of CredentialListInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CredentialListPage>) => any): Promise<ApiResponse<CredentialListPage>>; + /** + * Lists CredentialListInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CredentialListInstance[]) => any): Promise<CredentialListInstance[]>; + list(params: CredentialListListInstanceOptions, callback?: (error: Error | null, items: CredentialListInstance[]) => any): Promise<CredentialListInstance[]>; + /** + * Lists CredentialListInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CredentialListInstance[]>) => any): Promise<ApiResponse<CredentialListInstance[]>>; + listWithHttpInfo(params: CredentialListListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CredentialListInstance[]>) => any): Promise<ApiResponse<CredentialListInstance[]>>; + /** + * Retrieve a single page of CredentialListInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CredentialListPage) => any): Promise<CredentialListPage>; + page(params: CredentialListListInstancePageOptions, callback?: (error: Error | null, items: CredentialListPage) => any): Promise<CredentialListPage>; + /** + * Retrieve a single page of CredentialListInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CredentialListListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CredentialListPage>) => any): Promise<ApiResponse<CredentialListPage>>; + pageWithHttpInfo(params: CredentialListListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CredentialListPage>) => any): Promise<ApiResponse<CredentialListPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CredentialListListInstance(version: V1, trunkSid: string): CredentialListListInstance { + if (!isValidPathParam(trunkSid)) { + throw new Error('Parameter \'trunkSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as CredentialListListInstance; + + instance.get = function get(sid, ): CredentialListContext { + return new CredentialListContextImpl(version, trunkSid, sid); + } + + instance._version = version; + instance._solution = { trunkSid, }; + instance._uri = `/Trunks/${trunkSid}/CredentialLists`; + + instance.create = function create(params: CredentialListListInstanceCreateOptions, callback?: (error: Error | null, items: CredentialListInstance) => any): Promise<CredentialListInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["credentialListSid"] === null || params["credentialListSid"] === undefined) { + throw new Error('Required parameter "params[\'credentialListSid\']" missing.'); + } + + let data: any = {}; + + + + data["CredentialListSid"] = params["credentialListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CredentialListInstance(operationVersion, payload, instance._solution.trunkSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CredentialListListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<CredentialListInstance>) => any): Promise<ApiResponse<CredentialListInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["credentialListSid"] === null || params["credentialListSid"] === undefined) { + throw new Error('Required parameter "params[\'credentialListSid\']" missing.'); + } + + let data: any = {}; + + + + data["CredentialListSid"] = params["credentialListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CredentialListResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CredentialListInstance> => ({ + ...response, + body: new CredentialListInstance(operationVersion, response.body, instance._solution.trunkSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CredentialListListInstancePageOptions | ((error: Error | null, items: CredentialListPage) => any), callback?: (error: Error | null, items: CredentialListPage) => any): Promise<CredentialListPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CredentialListPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CredentialListPage) => any): Promise<CredentialListPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CredentialListPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CredentialListListInstancePageOptions | ((error: Error | null, items: ApiResponse<CredentialListPage>) => any), callback?: (error: Error | null, items: ApiResponse<CredentialListPage>) => any): Promise<ApiResponse<CredentialListPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CredentialListPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialListPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CredentialListPage>) => any): Promise<ApiResponse<CredentialListPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CredentialListPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CredentialListPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CredentialListPage extends Page<V1, CredentialListPayload, CredentialListResource, CredentialListInstance> { +/** +* Initialize the CredentialListPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CredentialListSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CredentialListInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CredentialListResource): CredentialListInstance { + + return new CredentialListInstance( + this._version, + payload, + this._solution.trunkSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trunking/v1/trunk/ipAccessControlList.ts b/rest/trunking/v1/trunk/ipAccessControlList.ts new file mode 100644 index 000000000..903dd8705 --- /dev/null +++ b/rest/trunking/v1/trunk/ipAccessControlList.ts @@ -0,0 +1,746 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trunking + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a IpAccessControlListInstance + */ +export interface IpAccessControlListListInstanceCreateOptions { + /** The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. */ + "ipAccessControlListSid": string; +} + +/** + * Options to pass to each + */ +export interface IpAccessControlListListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: IpAccessControlListInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface IpAccessControlListListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface IpAccessControlListListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface IpAccessControlListContext { + + /** + * Remove a IpAccessControlListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a IpAccessControlListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a IpAccessControlListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance + */ + fetch(callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise<IpAccessControlListInstance> + + /** + * Fetch a IpAccessControlListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpAccessControlListInstance>) => any): Promise<ApiResponse<IpAccessControlListInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface IpAccessControlListContextSolution { + "trunkSid": string; + "sid": string; +} + +export class IpAccessControlListContextImpl implements IpAccessControlListContext { + protected _solution: IpAccessControlListContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, trunkSid: string, sid: string) { + if (!isValidPathParam(trunkSid)) { + throw new Error('Parameter \'trunkSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { trunkSid, sid, }; + this._uri = `/Trunks/${trunkSid}/IpAccessControlLists/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise<IpAccessControlListInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new IpAccessControlListInstance(operationVersion, payload, instance._solution.trunkSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpAccessControlListInstance>) => any): Promise<ApiResponse<IpAccessControlListInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<IpAccessControlListResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<IpAccessControlListInstance> => ({ + ...response, + body: new IpAccessControlListInstance(operationVersion, response.body, instance._solution.trunkSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface IpAccessControlListPayload extends TwilioResponsePayload { + ip_access_control_lists: IpAccessControlListResource[]; +} + +interface IpAccessControlListResource { + account_sid: string; + sid: string; + trunk_sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class IpAccessControlListInstance { + protected _solution: IpAccessControlListContextSolution; + protected _context?: IpAccessControlListContext; + + constructor(protected _version: V1, payload: IpAccessControlListResource, trunkSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.trunkSid = (payload.trunk_sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { trunkSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlList resource. + */ + accountSid: string; + /** + * The unique string that we created to identify the IpAccessControlList resource. + */ + sid: string; + /** + * The SID of the Trunk the resource is associated with. + */ + trunkSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): IpAccessControlListContext { + this._context = this._context || new IpAccessControlListContextImpl(this._version, this._solution.trunkSid, this._solution.sid); + return this._context; + } + + /** + * Remove a IpAccessControlListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a IpAccessControlListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a IpAccessControlListInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance + */ + fetch(callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise<IpAccessControlListInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a IpAccessControlListInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpAccessControlListInstance>) => any): Promise<ApiResponse<IpAccessControlListInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + trunkSid: this.trunkSid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface IpAccessControlListSolution { + trunkSid: string; +} + +export interface IpAccessControlListListInstance { + _version: V1; + _solution: IpAccessControlListSolution; + _uri: string; + + (sid: string, ): IpAccessControlListContext; + get(sid: string, ): IpAccessControlListContext; + + + + + + + /** + * Create a IpAccessControlListInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance + */ + create(params: IpAccessControlListListInstanceCreateOptions, callback?: (error: Error | null, item?: IpAccessControlListInstance) => any): Promise<IpAccessControlListInstance>; + + /** + * Create a IpAccessControlListInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpAccessControlListInstance with HTTP metadata + */ + createWithHttpInfo(params: IpAccessControlListListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<IpAccessControlListInstance>) => any): Promise<ApiResponse<IpAccessControlListInstance>>; + + + + + /** + * Streams IpAccessControlListInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: IpAccessControlListInstance, done: (err?: Error) => void) => void): void; + each(params: IpAccessControlListListInstanceEachOptions, callback?: (item: IpAccessControlListInstance, done: (err?: Error) => void) => void): void; + /** + * Streams IpAccessControlListInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: IpAccessControlListInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: IpAccessControlListListInstanceEachOptions, callback?: (item: IpAccessControlListInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of IpAccessControlListInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: IpAccessControlListPage) => any): Promise<IpAccessControlListPage>; + /** + * Retrieve a single target page of IpAccessControlListInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<IpAccessControlListPage>) => any): Promise<ApiResponse<IpAccessControlListPage>>; + /** + * Lists IpAccessControlListInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: IpAccessControlListInstance[]) => any): Promise<IpAccessControlListInstance[]>; + list(params: IpAccessControlListListInstanceOptions, callback?: (error: Error | null, items: IpAccessControlListInstance[]) => any): Promise<IpAccessControlListInstance[]>; + /** + * Lists IpAccessControlListInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<IpAccessControlListInstance[]>) => any): Promise<ApiResponse<IpAccessControlListInstance[]>>; + listWithHttpInfo(params: IpAccessControlListListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<IpAccessControlListInstance[]>) => any): Promise<ApiResponse<IpAccessControlListInstance[]>>; + /** + * Retrieve a single page of IpAccessControlListInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: IpAccessControlListPage) => any): Promise<IpAccessControlListPage>; + page(params: IpAccessControlListListInstancePageOptions, callback?: (error: Error | null, items: IpAccessControlListPage) => any): Promise<IpAccessControlListPage>; + /** + * Retrieve a single page of IpAccessControlListInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpAccessControlListListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<IpAccessControlListPage>) => any): Promise<ApiResponse<IpAccessControlListPage>>; + pageWithHttpInfo(params: IpAccessControlListListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<IpAccessControlListPage>) => any): Promise<ApiResponse<IpAccessControlListPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function IpAccessControlListListInstance(version: V1, trunkSid: string): IpAccessControlListListInstance { + if (!isValidPathParam(trunkSid)) { + throw new Error('Parameter \'trunkSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as IpAccessControlListListInstance; + + instance.get = function get(sid, ): IpAccessControlListContext { + return new IpAccessControlListContextImpl(version, trunkSid, sid); + } + + instance._version = version; + instance._solution = { trunkSid, }; + instance._uri = `/Trunks/${trunkSid}/IpAccessControlLists`; + + instance.create = function create(params: IpAccessControlListListInstanceCreateOptions, callback?: (error: Error | null, items: IpAccessControlListInstance) => any): Promise<IpAccessControlListInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["ipAccessControlListSid"] === null || params["ipAccessControlListSid"] === undefined) { + throw new Error('Required parameter "params[\'ipAccessControlListSid\']" missing.'); + } + + let data: any = {}; + + + + data["IpAccessControlListSid"] = params["ipAccessControlListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IpAccessControlListInstance(operationVersion, payload, instance._solution.trunkSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: IpAccessControlListListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<IpAccessControlListInstance>) => any): Promise<ApiResponse<IpAccessControlListInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["ipAccessControlListSid"] === null || params["ipAccessControlListSid"] === undefined) { + throw new Error('Required parameter "params[\'ipAccessControlListSid\']" missing.'); + } + + let data: any = {}; + + + + data["IpAccessControlListSid"] = params["ipAccessControlListSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<IpAccessControlListResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<IpAccessControlListInstance> => ({ + ...response, + body: new IpAccessControlListInstance(operationVersion, response.body, instance._solution.trunkSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: IpAccessControlListListInstancePageOptions | ((error: Error | null, items: IpAccessControlListPage) => any), callback?: (error: Error | null, items: IpAccessControlListPage) => any): Promise<IpAccessControlListPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new IpAccessControlListPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: IpAccessControlListPage) => any): Promise<IpAccessControlListPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new IpAccessControlListPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: IpAccessControlListListInstancePageOptions | ((error: Error | null, items: ApiResponse<IpAccessControlListPage>) => any), callback?: (error: Error | null, items: ApiResponse<IpAccessControlListPage>) => any): Promise<ApiResponse<IpAccessControlListPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<IpAccessControlListPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpAccessControlListPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<IpAccessControlListPage>) => any): Promise<ApiResponse<IpAccessControlListPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<IpAccessControlListPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpAccessControlListPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class IpAccessControlListPage extends Page<V1, IpAccessControlListPayload, IpAccessControlListResource, IpAccessControlListInstance> { +/** +* Initialize the IpAccessControlListPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: IpAccessControlListSolution) { + super(version, response, solution); + } + + /** + * Build an instance of IpAccessControlListInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: IpAccessControlListResource): IpAccessControlListInstance { + + return new IpAccessControlListInstance( + this._version, + payload, + this._solution.trunkSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trunking/v1/trunk/originationUrl.ts b/rest/trunking/v1/trunk/originationUrl.ts new file mode 100644 index 000000000..cf4dba493 --- /dev/null +++ b/rest/trunking/v1/trunk/originationUrl.ts @@ -0,0 +1,1015 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trunking + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a OriginationUrlInstance + */ +export interface OriginationUrlContextUpdateOptions { + /** The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. */ + "weight"?: number; + /** The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. */ + "priority"?: number; + /** Whether the URL is enabled. The default is `true`. */ + "enabled"?: boolean; + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName"?: string; + /** The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. */ + "sipUrl"?: string; +} + +/** + * Options to pass to create a OriginationUrlInstance + */ +export interface OriginationUrlListInstanceCreateOptions { + /** The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. */ + "weight": number; + /** The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. */ + "priority": number; + /** Whether the URL is enabled. The default is `true`. */ + "enabled": boolean; + /** A descriptive string that you create to describe the resource. It can be up to 64 characters long. */ + "friendlyName": string; + /** The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. */ + "sipUrl": string; +} + +/** + * Options to pass to each + */ +export interface OriginationUrlListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: OriginationUrlInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface OriginationUrlListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface OriginationUrlListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface OriginationUrlContext { + + /** + * Remove a OriginationUrlInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a OriginationUrlInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a OriginationUrlInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance + */ + fetch(callback?: (error: Error | null, item?: OriginationUrlInstance) => any): Promise<OriginationUrlInstance> + + /** + * Fetch a OriginationUrlInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>> + + /** + * Update a OriginationUrlInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance + */ + update(callback?: (error: Error | null, item?: OriginationUrlInstance) => any): Promise<OriginationUrlInstance>; + /** + * Update a OriginationUrlInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance + */ + update(params: OriginationUrlContextUpdateOptions, callback?: (error: Error | null, item?: OriginationUrlInstance) => any): Promise<OriginationUrlInstance>; + + /** + * Update a OriginationUrlInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>>; + /** + * Update a OriginationUrlInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance with HTTP metadata + */ + updateWithHttpInfo(params: OriginationUrlContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface OriginationUrlContextSolution { + "trunkSid": string; + "sid": string; +} + +export class OriginationUrlContextImpl implements OriginationUrlContext { + protected _solution: OriginationUrlContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, trunkSid: string, sid: string) { + if (!isValidPathParam(trunkSid)) { + throw new Error('Parameter \'trunkSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { trunkSid, sid, }; + this._uri = `/Trunks/${trunkSid}/OriginationUrls/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: OriginationUrlInstance) => any): Promise<OriginationUrlInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new OriginationUrlInstance(operationVersion, payload, instance._solution.trunkSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<OriginationUrlResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<OriginationUrlInstance> => ({ + ...response, + body: new OriginationUrlInstance(operationVersion, response.body, instance._solution.trunkSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: OriginationUrlContextUpdateOptions | ((error: Error | null, item?: OriginationUrlInstance) => any),callback?: (error: Error | null, item?: OriginationUrlInstance) => any): Promise<OriginationUrlInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["weight"] !== undefined) + data["Weight"] = params["weight"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["sipUrl"] !== undefined) + data["SipUrl"] = params["sipUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new OriginationUrlInstance(operationVersion, payload, instance._solution.trunkSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: OriginationUrlContextUpdateOptions | ((error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["weight"] !== undefined) + data["Weight"] = params["weight"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["sipUrl"] !== undefined) + data["SipUrl"] = params["sipUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<OriginationUrlResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<OriginationUrlInstance> => ({ + ...response, + body: new OriginationUrlInstance(operationVersion, response.body, instance._solution.trunkSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface OriginationUrlPayload extends TwilioResponsePayload { + origination_urls: OriginationUrlResource[]; +} + +interface OriginationUrlResource { + account_sid: string; + sid: string; + trunk_sid: string; + weight: number; + enabled: boolean; + sip_url: string; + friendly_name: string; + priority: number; + date_created: Date; + date_updated: Date; + url: string; +} + +export class OriginationUrlInstance { + protected _solution: OriginationUrlContextSolution; + protected _context?: OriginationUrlContext; + + constructor(protected _version: V1, payload: OriginationUrlResource, trunkSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.trunkSid = (payload.trunk_sid); + this.weight = deserialize.integer(payload.weight); + this.enabled = (payload.enabled); + this.sipUrl = (payload.sip_url); + this.friendlyName = (payload.friendly_name); + this.priority = deserialize.integer(payload.priority); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { trunkSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OriginationUrl resource. + */ + accountSid: string; + /** + * The unique string that we created to identify the OriginationUrl resource. + */ + sid: string; + /** + * The SID of the Trunk that owns the Origination URL. + */ + trunkSid: string; + /** + * The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + */ + weight: number; + /** + * Whether the URL is enabled. The default is `true`. + */ + enabled: boolean; + /** + * The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + */ + sipUrl: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + */ + priority: number; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): OriginationUrlContext { + this._context = this._context || new OriginationUrlContextImpl(this._version, this._solution.trunkSid, this._solution.sid); + return this._context; + } + + /** + * Remove a OriginationUrlInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a OriginationUrlInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a OriginationUrlInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance + */ + fetch(callback?: (error: Error | null, item?: OriginationUrlInstance) => any): Promise<OriginationUrlInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a OriginationUrlInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a OriginationUrlInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance + */ + update(callback?: (error: Error | null, item?: OriginationUrlInstance) => any): Promise<OriginationUrlInstance>; + /** + * Update a OriginationUrlInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance + */ + update(params: OriginationUrlContextUpdateOptions, callback?: (error: Error | null, item?: OriginationUrlInstance) => any): Promise<OriginationUrlInstance>; + + update(params?: any, callback?: (error: Error | null, item?: OriginationUrlInstance) => any): Promise<OriginationUrlInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a OriginationUrlInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>>; + /** + * Update a OriginationUrlInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance with HTTP metadata + */ + updateWithHttpInfo(params: OriginationUrlContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + trunkSid: this.trunkSid, + weight: this.weight, + enabled: this.enabled, + sipUrl: this.sipUrl, + friendlyName: this.friendlyName, + priority: this.priority, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface OriginationUrlSolution { + trunkSid: string; +} + +export interface OriginationUrlListInstance { + _version: V1; + _solution: OriginationUrlSolution; + _uri: string; + + (sid: string, ): OriginationUrlContext; + get(sid: string, ): OriginationUrlContext; + + + + + + + + + /** + * Create a OriginationUrlInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance + */ + create(params: OriginationUrlListInstanceCreateOptions, callback?: (error: Error | null, item?: OriginationUrlInstance) => any): Promise<OriginationUrlInstance>; + + /** + * Create a OriginationUrlInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed OriginationUrlInstance with HTTP metadata + */ + createWithHttpInfo(params: OriginationUrlListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>>; + + + + + /** + * Streams OriginationUrlInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OriginationUrlListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: OriginationUrlInstance, done: (err?: Error) => void) => void): void; + each(params: OriginationUrlListInstanceEachOptions, callback?: (item: OriginationUrlInstance, done: (err?: Error) => void) => void): void; + /** + * Streams OriginationUrlInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OriginationUrlListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: OriginationUrlInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: OriginationUrlListInstanceEachOptions, callback?: (item: OriginationUrlInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of OriginationUrlInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: OriginationUrlPage) => any): Promise<OriginationUrlPage>; + /** + * Retrieve a single target page of OriginationUrlInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<OriginationUrlPage>) => any): Promise<ApiResponse<OriginationUrlPage>>; + /** + * Lists OriginationUrlInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OriginationUrlListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: OriginationUrlInstance[]) => any): Promise<OriginationUrlInstance[]>; + list(params: OriginationUrlListInstanceOptions, callback?: (error: Error | null, items: OriginationUrlInstance[]) => any): Promise<OriginationUrlInstance[]>; + /** + * Lists OriginationUrlInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OriginationUrlListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<OriginationUrlInstance[]>) => any): Promise<ApiResponse<OriginationUrlInstance[]>>; + listWithHttpInfo(params: OriginationUrlListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<OriginationUrlInstance[]>) => any): Promise<ApiResponse<OriginationUrlInstance[]>>; + /** + * Retrieve a single page of OriginationUrlInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OriginationUrlListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: OriginationUrlPage) => any): Promise<OriginationUrlPage>; + page(params: OriginationUrlListInstancePageOptions, callback?: (error: Error | null, items: OriginationUrlPage) => any): Promise<OriginationUrlPage>; + /** + * Retrieve a single page of OriginationUrlInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { OriginationUrlListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<OriginationUrlPage>) => any): Promise<ApiResponse<OriginationUrlPage>>; + pageWithHttpInfo(params: OriginationUrlListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<OriginationUrlPage>) => any): Promise<ApiResponse<OriginationUrlPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function OriginationUrlListInstance(version: V1, trunkSid: string): OriginationUrlListInstance { + if (!isValidPathParam(trunkSid)) { + throw new Error('Parameter \'trunkSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as OriginationUrlListInstance; + + instance.get = function get(sid, ): OriginationUrlContext { + return new OriginationUrlContextImpl(version, trunkSid, sid); + } + + instance._version = version; + instance._solution = { trunkSid, }; + instance._uri = `/Trunks/${trunkSid}/OriginationUrls`; + + instance.create = function create(params: OriginationUrlListInstanceCreateOptions, callback?: (error: Error | null, items: OriginationUrlInstance) => any): Promise<OriginationUrlInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["weight"] === null || params["weight"] === undefined) { + throw new Error('Required parameter "params[\'weight\']" missing.'); + } + + if (params["priority"] === null || params["priority"] === undefined) { + throw new Error('Required parameter "params[\'priority\']" missing.'); + } + + if (params["enabled"] === null || params["enabled"] === undefined) { + throw new Error('Required parameter "params[\'enabled\']" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["sipUrl"] === null || params["sipUrl"] === undefined) { + throw new Error('Required parameter "params[\'sipUrl\']" missing.'); + } + + let data: any = {}; + + + + data["Weight"] = params["weight"]; + + data["Priority"] = params["priority"]; + + data["Enabled"] = serialize.bool(params["enabled"]); + + data["FriendlyName"] = params["friendlyName"]; + + data["SipUrl"] = params["sipUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new OriginationUrlInstance(operationVersion, payload, instance._solution.trunkSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: OriginationUrlListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<OriginationUrlInstance>) => any): Promise<ApiResponse<OriginationUrlInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["weight"] === null || params["weight"] === undefined) { + throw new Error('Required parameter "params[\'weight\']" missing.'); + } + + if (params["priority"] === null || params["priority"] === undefined) { + throw new Error('Required parameter "params[\'priority\']" missing.'); + } + + if (params["enabled"] === null || params["enabled"] === undefined) { + throw new Error('Required parameter "params[\'enabled\']" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["sipUrl"] === null || params["sipUrl"] === undefined) { + throw new Error('Required parameter "params[\'sipUrl\']" missing.'); + } + + let data: any = {}; + + + + data["Weight"] = params["weight"]; + + data["Priority"] = params["priority"]; + + data["Enabled"] = serialize.bool(params["enabled"]); + + data["FriendlyName"] = params["friendlyName"]; + + data["SipUrl"] = params["sipUrl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<OriginationUrlResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<OriginationUrlInstance> => ({ + ...response, + body: new OriginationUrlInstance(operationVersion, response.body, instance._solution.trunkSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: OriginationUrlListInstancePageOptions | ((error: Error | null, items: OriginationUrlPage) => any), callback?: (error: Error | null, items: OriginationUrlPage) => any): Promise<OriginationUrlPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new OriginationUrlPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: OriginationUrlPage) => any): Promise<OriginationUrlPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new OriginationUrlPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: OriginationUrlListInstancePageOptions | ((error: Error | null, items: ApiResponse<OriginationUrlPage>) => any), callback?: (error: Error | null, items: ApiResponse<OriginationUrlPage>) => any): Promise<ApiResponse<OriginationUrlPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<OriginationUrlPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OriginationUrlPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<OriginationUrlPage>) => any): Promise<ApiResponse<OriginationUrlPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<OriginationUrlPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new OriginationUrlPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class OriginationUrlPage extends Page<V1, OriginationUrlPayload, OriginationUrlResource, OriginationUrlInstance> { +/** +* Initialize the OriginationUrlPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: OriginationUrlSolution) { + super(version, response, solution); + } + + /** + * Build an instance of OriginationUrlInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: OriginationUrlResource): OriginationUrlInstance { + + return new OriginationUrlInstance( + this._version, + payload, + this._solution.trunkSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trunking/v1/trunk/phoneNumber.ts b/rest/trunking/v1/trunk/phoneNumber.ts new file mode 100644 index 000000000..5e5b8026b --- /dev/null +++ b/rest/trunking/v1/trunk/phoneNumber.ts @@ -0,0 +1,879 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trunking + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { PhoneNumberCapabilities } from "../../../../interfaces"; + + +/** + * Whether the phone number requires an [Address](https://www.twilio.com/docs/usage/api/address) registered with Twilio and, if so, what type. Can be: `none`, `any`, `local`, or `foreign`. + */ +export type PhoneNumberAddressRequirement = 'none'|'any'|'local'|'foreign'; + + + + +/** + * Options to pass to create a PhoneNumberInstance + */ +export interface PhoneNumberListInstanceCreateOptions { + /** The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. */ + "phoneNumberSid": string; +} + +/** + * Options to pass to each + */ +export interface PhoneNumberListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PhoneNumberListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PhoneNumberListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PhoneNumberContext { + + /** + * Remove a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PhoneNumberContextSolution { + "trunkSid": string; + "sid": string; +} + +export class PhoneNumberContextImpl implements PhoneNumberContext { + protected _solution: PhoneNumberContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, trunkSid: string, sid: string) { + if (!isValidPathParam(trunkSid)) { + throw new Error('Parameter \'trunkSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { trunkSid, sid, }; + this._uri = `/Trunks/${trunkSid}/PhoneNumbers/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.trunkSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.trunkSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PhoneNumberPayload extends TwilioResponsePayload { + phone_numbers: PhoneNumberResource[]; +} + +interface PhoneNumberResource { + account_sid: string; + address_requirements: PhoneNumberAddressRequirement; + api_version: string; + beta: boolean; + capabilities: PhoneNumberCapabilities; + date_created: Date; + date_updated: Date; + friendly_name: string; + links: Record<string, string>; + phone_number: string; + sid: string; + sms_application_sid: string; + sms_fallback_method: string; + sms_fallback_url: string; + sms_method: string; + sms_url: string; + status_callback: string; + status_callback_method: string; + trunk_sid: string; + url: string; + voice_application_sid: string; + voice_caller_id_lookup: boolean; + voice_fallback_method: string; + voice_fallback_url: string; + voice_method: string; + voice_url: string; +} + +export class PhoneNumberInstance { + protected _solution: PhoneNumberContextSolution; + protected _context?: PhoneNumberContext; + + constructor(protected _version: V1, payload: PhoneNumberResource, trunkSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.addressRequirements = payload.address_requirements; + this.apiVersion = (payload.api_version); + this.beta = (payload.beta); + this.capabilities = (payload.capabilities); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.links = (payload.links); + this.phoneNumber = (payload.phone_number); + this.sid = (payload.sid); + this.smsApplicationSid = (payload.sms_application_sid); + this.smsFallbackMethod = (payload.sms_fallback_method); + this.smsFallbackUrl = (payload.sms_fallback_url); + this.smsMethod = (payload.sms_method); + this.smsUrl = (payload.sms_url); + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.trunkSid = (payload.trunk_sid); + this.url = (payload.url); + this.voiceApplicationSid = (payload.voice_application_sid); + this.voiceCallerIdLookup = (payload.voice_caller_id_lookup); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceMethod = (payload.voice_method); + this.voiceUrl = (payload.voice_url); + + this._solution = { trunkSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. + */ + accountSid: string; + addressRequirements: PhoneNumberAddressRequirement; + /** + * The API version used to start a new TwiML session. + */ + apiVersion: string; + /** + * Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + */ + beta: boolean; + capabilities: PhoneNumberCapabilities; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + /** + * The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + */ + phoneNumber: string; + /** + * The unique string that we created to identify the PhoneNumber resource. + */ + sid: string; + /** + * The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + */ + smsApplicationSid: string; + /** + * The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + */ + smsFallbackMethod: string; + /** + * The URL that we call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML from `sms_url`. + */ + smsFallbackUrl: string; + /** + * The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + */ + smsMethod: string; + /** + * The URL we call using the `sms_method` when the phone number receives an incoming SMS message. + */ + smsUrl: string; + /** + * The URL we call using the `status_callback_method` to send status information to your application. + */ + statusCallback: string; + /** + * The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + */ + statusCallbackMethod: string; + /** + * The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice URLs and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + */ + trunkSid: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice URLs and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + */ + voiceApplicationSid: string; + /** + * Whether we look up the caller\'s caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + */ + voiceCallerIdLookup: boolean; + /** + * The HTTP method that we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + */ + voiceFallbackMethod: string; + /** + * The URL that we call using the `voice_fallback_method` when an error occurs retrieving or executing the TwiML requested by `url`. + */ + voiceFallbackUrl: string; + /** + * The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + */ + voiceMethod: string; + /** + * The URL we call using the `voice_method` when the phone number receives a call. The `voice_url` is not be used if a `voice_application_sid` or a `trunk_sid` is set. + */ + voiceUrl: string; + + private get _proxy(): PhoneNumberContext { + this._context = this._context || new PhoneNumberContextImpl(this._version, this._solution.trunkSid, this._solution.sid); + return this._context; + } + + /** + * Remove a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a PhoneNumberInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + fetch(callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PhoneNumberInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + addressRequirements: this.addressRequirements, + apiVersion: this.apiVersion, + beta: this.beta, + capabilities: this.capabilities, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + links: this.links, + phoneNumber: this.phoneNumber, + sid: this.sid, + smsApplicationSid: this.smsApplicationSid, + smsFallbackMethod: this.smsFallbackMethod, + smsFallbackUrl: this.smsFallbackUrl, + smsMethod: this.smsMethod, + smsUrl: this.smsUrl, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + trunkSid: this.trunkSid, + url: this.url, + voiceApplicationSid: this.voiceApplicationSid, + voiceCallerIdLookup: this.voiceCallerIdLookup, + voiceFallbackMethod: this.voiceFallbackMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceMethod: this.voiceMethod, + voiceUrl: this.voiceUrl, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PhoneNumberSolution { + trunkSid: string; +} + +export interface PhoneNumberListInstance { + _version: V1; + _solution: PhoneNumberSolution; + _uri: string; + + (sid: string, ): PhoneNumberContext; + get(sid: string, ): PhoneNumberContext; + + + + + + + /** + * Create a PhoneNumberInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance + */ + create(params: PhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, item?: PhoneNumberInstance) => any): Promise<PhoneNumberInstance>; + + /** + * Create a PhoneNumberInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PhoneNumberInstance with HTTP metadata + */ + createWithHttpInfo(params: PhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>>; + + + + + /** + * Streams PhoneNumberInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + each(params: PhoneNumberListInstanceEachOptions, callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PhoneNumberInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PhoneNumberListInstanceEachOptions, callback?: (item: PhoneNumberInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PhoneNumberInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage>; + /** + * Retrieve a single target page of PhoneNumberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>>; + /** + * Lists PhoneNumberInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PhoneNumberInstance[]) => any): Promise<PhoneNumberInstance[]>; + list(params: PhoneNumberListInstanceOptions, callback?: (error: Error | null, items: PhoneNumberInstance[]) => any): Promise<PhoneNumberInstance[]>; + /** + * Lists PhoneNumberInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PhoneNumberInstance[]>) => any): Promise<ApiResponse<PhoneNumberInstance[]>>; + listWithHttpInfo(params: PhoneNumberListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<PhoneNumberInstance[]>) => any): Promise<ApiResponse<PhoneNumberInstance[]>>; + /** + * Retrieve a single page of PhoneNumberInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage>; + page(params: PhoneNumberListInstancePageOptions, callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage>; + /** + * Retrieve a single page of PhoneNumberInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PhoneNumberListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>>; + pageWithHttpInfo(params: PhoneNumberListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PhoneNumberListInstance(version: V1, trunkSid: string): PhoneNumberListInstance { + if (!isValidPathParam(trunkSid)) { + throw new Error('Parameter \'trunkSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as PhoneNumberListInstance; + + instance.get = function get(sid, ): PhoneNumberContext { + return new PhoneNumberContextImpl(version, trunkSid, sid); + } + + instance._version = version; + instance._solution = { trunkSid, }; + instance._uri = `/Trunks/${trunkSid}/PhoneNumbers`; + + instance.create = function create(params: PhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, items: PhoneNumberInstance) => any): Promise<PhoneNumberInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumberSid"] === null || params["phoneNumberSid"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumberSid\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumberSid"] = params["phoneNumberSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new PhoneNumberInstance(operationVersion, payload, instance._solution.trunkSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: PhoneNumberListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<PhoneNumberInstance>) => any): Promise<ApiResponse<PhoneNumberInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumberSid"] === null || params["phoneNumberSid"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumberSid\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumberSid"] = params["phoneNumberSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<PhoneNumberResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<PhoneNumberInstance> => ({ + ...response, + body: new PhoneNumberInstance(operationVersion, response.body, instance._solution.trunkSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: PhoneNumberListInstancePageOptions | ((error: Error | null, items: PhoneNumberPage) => any), callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PhoneNumberPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PhoneNumberPage) => any): Promise<PhoneNumberPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PhoneNumberPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PhoneNumberListInstancePageOptions | ((error: Error | null, items: ApiResponse<PhoneNumberPage>) => any), callback?: (error: Error | null, items: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<PhoneNumberPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PhoneNumberPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<PhoneNumberPage>) => any): Promise<ApiResponse<PhoneNumberPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<PhoneNumberPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PhoneNumberPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PhoneNumberPage extends Page<V1, PhoneNumberPayload, PhoneNumberResource, PhoneNumberInstance> { +/** +* Initialize the PhoneNumberPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: PhoneNumberSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PhoneNumberInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PhoneNumberResource): PhoneNumberInstance { + + return new PhoneNumberInstance( + this._version, + payload, + this._solution.trunkSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trunking/v1/trunk/recording.ts b/rest/trunking/v1/trunk/recording.ts new file mode 100644 index 000000000..b5c9bced5 --- /dev/null +++ b/rest/trunking/v1/trunk/recording.ts @@ -0,0 +1,417 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trunking + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The recording mode for the trunk. Can be do-not-record (default), record-from-ringing, record-from-answer, record-from-ringing-dual, or record-from-answer-dual. + */ +export type RecordingRecordingMode = 'do-not-record'|'record-from-ringing'|'record-from-answer'|'record-from-ringing-dual'|'record-from-answer-dual'; + +/** + * The recording trim setting for the trunk. Can be do-not-trim (default) or trim-silence. + */ +export type RecordingRecordingTrim = 'trim-silence'|'do-not-trim'; + + + +/** + * Options to pass to update a RecordingInstance + */ +export interface RecordingContextUpdateOptions { + /** */ + "mode"?: RecordingRecordingMode; + /** */ + "trim"?: RecordingRecordingTrim; +} + +export interface RecordingContext { + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> + + /** + * Update a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance>; + /** + * Update a RecordingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance>; + + /** + * Update a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>>; + /** + * Update a RecordingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RecordingContextSolution { + "trunkSid": string; +} + +export class RecordingContextImpl implements RecordingContext { + protected _solution: RecordingContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, trunkSid: string) { + if (!isValidPathParam(trunkSid)) { + throw new Error('Parameter \'trunkSid\' is not valid.'); + } + + this._solution = { trunkSid, }; + this._uri = `/Trunks/${trunkSid}/Recording`; + } + + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.trunkSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RecordingResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<RecordingInstance> => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.trunkSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: RecordingContextUpdateOptions | ((error: Error | null, item?: RecordingInstance) => any),callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["mode"] !== undefined) + data["Mode"] = params["mode"]; + if (params["trim"] !== undefined) + data["Trim"] = params["trim"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.trunkSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: RecordingContextUpdateOptions | ((error: Error | null, item?: ApiResponse<RecordingInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["mode"] !== undefined) + data["Mode"] = params["mode"]; + if (params["trim"] !== undefined) + data["Trim"] = params["trim"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<RecordingResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RecordingInstance> => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.trunkSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RecordingPayload extends RecordingResource {} + +interface RecordingResource { + mode: RecordingRecordingMode; + trim: RecordingRecordingTrim; +} + +export class RecordingInstance { + protected _solution: RecordingContextSolution; + protected _context?: RecordingContext; + + constructor(protected _version: V1, payload: RecordingResource, trunkSid: string) { + + this.mode = payload.mode; + this.trim = payload.trim; + + this._solution = { trunkSid, }; + } + + mode: RecordingRecordingMode; + trim: RecordingRecordingTrim; + + private get _proxy(): RecordingContext { + this._context = this._context || new RecordingContextImpl(this._version, this._solution.trunkSid); + return this._context; + } + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance>; + /** + * Update a RecordingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance>; + + update(params?: any, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>>; + /** + * Update a RecordingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(params: RecordingContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + mode: this.mode, + trim: this.trim, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RecordingSolution { + trunkSid: string; +} + +export interface RecordingListInstance { + _version: V1; + _solution: RecordingSolution; + _uri: string; + + (): RecordingContext; + get(): RecordingContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RecordingListInstance(version: V1, trunkSid: string): RecordingListInstance { + if (!isValidPathParam(trunkSid)) { + throw new Error('Parameter \'trunkSid\' is not valid.'); + } + + const instance = (() => instance.get()) as RecordingListInstance; + + instance.get = function get(): RecordingContext { + return new RecordingContextImpl(version, trunkSid); + } + + instance._version = version; + instance._solution = { trunkSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/trusthub/V1.ts b/rest/trusthub/V1.ts new file mode 100644 index 000000000..adc572012 --- /dev/null +++ b/rest/trusthub/V1.ts @@ -0,0 +1,167 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import TrusthubBase from "../TrusthubBase"; +import Version from "../../base/Version"; +import { A2PBrandRegistrationListInstance } from "./v1/a2PBrandRegistration"; +import { A2PBrandRegistrationEmbeddedSessionListInstance } from "./v1/a2PBrandRegistrationEmbeddedSession"; +import { A2PCampaignRegistrationListInstance } from "./v1/a2PCampaignRegistration"; +import { A2PCampaignRegistrationEmbeddedSessionListInstance } from "./v1/a2PCampaignRegistrationEmbeddedSession"; +import { ComplianceInquiriesListInstance } from "./v1/complianceInquiries"; +import { ComplianceRegistrationInquiriesListInstance } from "./v1/complianceRegistrationInquiries"; +import { ComplianceTollfreeInquiriesListInstance } from "./v1/complianceTollfreeInquiries"; +import { CustomerProfilesListInstance } from "./v1/customerProfiles"; +import { CustomerProfilesProvisionalCopyListInstance } from "./v1/customerProfilesProvisionalCopy"; +import { EndUserListInstance } from "./v1/endUser"; +import { EndUserTypeListInstance } from "./v1/endUserType"; +import { PoliciesListInstance } from "./v1/policies"; +import { SupportingDocumentListInstance } from "./v1/supportingDocument"; +import { SupportingDocumentTypeListInstance } from "./v1/supportingDocumentType"; +import { TrustProductsListInstance } from "./v1/trustProducts"; +import { TrustProductsProvisionalCopyListInstance } from "./v1/trustProductsProvisionalCopy"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Trusthub + * + * @param domain - The Twilio (Twilio.Trusthub) domain + */ + constructor(domain: TrusthubBase) { + super(domain, "v1"); + } + + /** a2PBrandRegistrations - { Twilio.Trusthub.V1.A2PBrandRegistrationListInstance } resource */ + protected _a2PBrandRegistrations?: A2PBrandRegistrationListInstance; + /** a2PCampaignRegistrations - { Twilio.Trusthub.V1.A2PCampaignRegistrationListInstance } resource */ + protected _a2PCampaignRegistrations?: A2PCampaignRegistrationListInstance; + /** complianceInquiries - { Twilio.Trusthub.V1.ComplianceInquiriesListInstance } resource */ + protected _complianceInquiries?: ComplianceInquiriesListInstance; + /** complianceRegistrationInquiries - { Twilio.Trusthub.V1.ComplianceRegistrationInquiriesListInstance } resource */ + protected _complianceRegistrationInquiries?: ComplianceRegistrationInquiriesListInstance; + /** complianceTollfreeInquiries - { Twilio.Trusthub.V1.ComplianceTollfreeInquiriesListInstance } resource */ + protected _complianceTollfreeInquiries?: ComplianceTollfreeInquiriesListInstance; + /** customerProfiles - { Twilio.Trusthub.V1.CustomerProfilesListInstance } resource */ + protected _customerProfiles?: CustomerProfilesListInstance; + /** customerProfilesProvisionalCopy - { Twilio.Trusthub.V1.CustomerProfilesProvisionalCopyListInstance } resource */ + protected _customerProfilesProvisionalCopy?: CustomerProfilesProvisionalCopyListInstance; + /** endUsers - { Twilio.Trusthub.V1.EndUserListInstance } resource */ + protected _endUsers?: EndUserListInstance; + /** endUserTypes - { Twilio.Trusthub.V1.EndUserTypeListInstance } resource */ + protected _endUserTypes?: EndUserTypeListInstance; + /** policies - { Twilio.Trusthub.V1.PoliciesListInstance } resource */ + protected _policies?: PoliciesListInstance; + /** supportingDocuments - { Twilio.Trusthub.V1.SupportingDocumentListInstance } resource */ + protected _supportingDocuments?: SupportingDocumentListInstance; + /** supportingDocumentTypes - { Twilio.Trusthub.V1.SupportingDocumentTypeListInstance } resource */ + protected _supportingDocumentTypes?: SupportingDocumentTypeListInstance; + /** trustProducts - { Twilio.Trusthub.V1.TrustProductsListInstance } resource */ + protected _trustProducts?: TrustProductsListInstance; + /** trustProductsProvisionalCopy - { Twilio.Trusthub.V1.TrustProductsProvisionalCopyListInstance } resource */ + protected _trustProductsProvisionalCopy?: TrustProductsProvisionalCopyListInstance; + + /** Getter for a2PBrandRegistrations resource */ + get a2PBrandRegistrations(): A2PBrandRegistrationListInstance { + this._a2PBrandRegistrations = this._a2PBrandRegistrations || A2PBrandRegistrationListInstance(this); + return this._a2PBrandRegistrations; + } + + /** Accessor for a2PBrandRegistrationEmbeddedSessions resource */ + a2PBrandRegistrationEmbeddedSessions(Id: string): A2PBrandRegistrationEmbeddedSessionListInstance { + return A2PBrandRegistrationEmbeddedSessionListInstance(this, Id); + } + + /** Getter for a2PCampaignRegistrations resource */ + get a2PCampaignRegistrations(): A2PCampaignRegistrationListInstance { + this._a2PCampaignRegistrations = this._a2PCampaignRegistrations || A2PCampaignRegistrationListInstance(this); + return this._a2PCampaignRegistrations; + } + + /** Accessor for a2PCampaignRegistrationEmbeddedSessions resource */ + a2PCampaignRegistrationEmbeddedSessions(Id: string): A2PCampaignRegistrationEmbeddedSessionListInstance { + return A2PCampaignRegistrationEmbeddedSessionListInstance(this, Id); + } + + /** Getter for complianceInquiries resource */ + get complianceInquiries(): ComplianceInquiriesListInstance { + this._complianceInquiries = this._complianceInquiries || ComplianceInquiriesListInstance(this); + return this._complianceInquiries; + } + + /** Getter for complianceRegistrationInquiries resource */ + get complianceRegistrationInquiries(): ComplianceRegistrationInquiriesListInstance { + this._complianceRegistrationInquiries = this._complianceRegistrationInquiries || ComplianceRegistrationInquiriesListInstance(this); + return this._complianceRegistrationInquiries; + } + + /** Getter for complianceTollfreeInquiries resource */ + get complianceTollfreeInquiries(): ComplianceTollfreeInquiriesListInstance { + this._complianceTollfreeInquiries = this._complianceTollfreeInquiries || ComplianceTollfreeInquiriesListInstance(this); + return this._complianceTollfreeInquiries; + } + + /** Getter for customerProfiles resource */ + get customerProfiles(): CustomerProfilesListInstance { + this._customerProfiles = this._customerProfiles || CustomerProfilesListInstance(this); + return this._customerProfiles; + } + + /** Getter for customerProfilesProvisionalCopy resource */ + get customerProfilesProvisionalCopy(): CustomerProfilesProvisionalCopyListInstance { + this._customerProfilesProvisionalCopy = this._customerProfilesProvisionalCopy || CustomerProfilesProvisionalCopyListInstance(this); + return this._customerProfilesProvisionalCopy; + } + + /** Getter for endUsers resource */ + get endUsers(): EndUserListInstance { + this._endUsers = this._endUsers || EndUserListInstance(this); + return this._endUsers; + } + + /** Getter for endUserTypes resource */ + get endUserTypes(): EndUserTypeListInstance { + this._endUserTypes = this._endUserTypes || EndUserTypeListInstance(this); + return this._endUserTypes; + } + + /** Getter for policies resource */ + get policies(): PoliciesListInstance { + this._policies = this._policies || PoliciesListInstance(this); + return this._policies; + } + + /** Getter for supportingDocuments resource */ + get supportingDocuments(): SupportingDocumentListInstance { + this._supportingDocuments = this._supportingDocuments || SupportingDocumentListInstance(this); + return this._supportingDocuments; + } + + /** Getter for supportingDocumentTypes resource */ + get supportingDocumentTypes(): SupportingDocumentTypeListInstance { + this._supportingDocumentTypes = this._supportingDocumentTypes || SupportingDocumentTypeListInstance(this); + return this._supportingDocumentTypes; + } + + /** Getter for trustProducts resource */ + get trustProducts(): TrustProductsListInstance { + this._trustProducts = this._trustProducts || TrustProductsListInstance(this); + return this._trustProducts; + } + + /** Getter for trustProductsProvisionalCopy resource */ + get trustProductsProvisionalCopy(): TrustProductsProvisionalCopyListInstance { + this._trustProductsProvisionalCopy = this._trustProductsProvisionalCopy || TrustProductsProvisionalCopyListInstance(this); + return this._trustProductsProvisionalCopy; + } + +} diff --git a/rest/trusthub/v1/a2PBrandRegistration.ts b/rest/trusthub/v1/a2PBrandRegistration.ts new file mode 100644 index 000000000..e417ee317 --- /dev/null +++ b/rest/trusthub/v1/a2PBrandRegistration.ts @@ -0,0 +1,350 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class TrusthubV1A2pBrandRegistrationRequest { + /** + * The type of brand being registered. + */ + "brandType": string; + /** + * Theme ID for styling the inquiry form. + */ + "themeSetId"?: string; + /** + * A human-readable name for the brand registration. + */ + "friendlyName"?: string; + /** + * The email address to receive notifications about the registration. + */ + "notificationEmail": string; + /** + * The legal name of the business. + */ + "businessName"?: string; + /** + * The authority with which the business is registered. + */ + "businessRegistrationAuthority"?: string; + /** + * The business registration number (e.g., EIN, CBN, ACN). Maximum 21 characters. + */ + "businessRegistrationNumber"?: string; + /** + * The industry of the business. + */ + "businessIndustry"?: string; + /** + * The business website URL (must use https://). + */ + "businessWebsite"?: string; + /** + * The type of business entity. + */ + "businessType"?: string; + /** + * The stock symbol for publicly traded companies. + */ + "businessStockSymbol"?: string; + /** + * The stock exchange where the business is listed. + */ + "businessStockExchange"?: string; + /** + * Nonprofit/political organization tax-exempt status per the U.S. tax code (e.g. 501c3, 501c1, 527). A value of 527 (political organization) requires a Campaign Verify token in brandExternalVettingToken. + */ + "businessTaxExemptStatus"?: string; + /** + * Campaign Verify token for externally vetted brands. + */ + "brandExternalVettingToken"?: string; + /** + * The street address of the business. + */ + "businessStreetAddress"?: string; + /** + * Additional street address information. + */ + "businessStreetAddress2"?: string; + /** + * The city of the business. + */ + "businessCity"?: string; + /** + * The state, province, or region of the business. + */ + "businessStateProvinceRegion"?: string; + /** + * The postal code of the business. + */ + "businessPostalCode"?: string; + /** + * The two-letter ISO country code of the business. + */ + "businessCountry"?: string; + /** + * The first name of the business contact. + */ + "businessContactFirstName"?: string; + /** + * The last name of the business contact. + */ + "businessContactLastName"?: string; + /** + * The email address of the business contact. + */ + "businessContactEmail"?: string; + /** + * The phone number of the business contact in E.164 format. + */ + "businessContactPhone"?: string; + /** + * The email address for authorized contact verification. + */ + "authorizedContactVerificationEmail"?: string; + /** + * The mobile phone number for authorized contact in E.164 format. + */ + "authorizedContactMobilePhoneNumberE164"?: string; + /** + * Whether this is a test brand registration. + */ + "isTest"?: boolean; + /** + * Whether to skip automatic secondary vetting. + */ + "skipAutomaticSecVet"?: boolean; + + constructor(payload) { + this.brandType = payload["brandType"]; + this.themeSetId = payload["themeSetId"]; + this.friendlyName = payload["friendlyName"]; + this.notificationEmail = payload["notificationEmail"]; + this.businessName = payload["businessName"]; + this.businessRegistrationAuthority = payload["businessRegistrationAuthority"]; + this.businessRegistrationNumber = payload["businessRegistrationNumber"]; + this.businessIndustry = payload["businessIndustry"]; + this.businessWebsite = payload["businessWebsite"]; + this.businessType = payload["businessType"]; + this.businessStockSymbol = payload["businessStockSymbol"]; + this.businessStockExchange = payload["businessStockExchange"]; + this.businessTaxExemptStatus = payload["businessTaxExemptStatus"]; + this.brandExternalVettingToken = payload["brandExternalVettingToken"]; + this.businessStreetAddress = payload["businessStreetAddress"]; + this.businessStreetAddress2 = payload["businessStreetAddress2"]; + this.businessCity = payload["businessCity"]; + this.businessStateProvinceRegion = payload["businessStateProvinceRegion"]; + this.businessPostalCode = payload["businessPostalCode"]; + this.businessCountry = payload["businessCountry"]; + this.businessContactFirstName = payload["businessContactFirstName"]; + this.businessContactLastName = payload["businessContactLastName"]; + this.businessContactEmail = payload["businessContactEmail"]; + this.businessContactPhone = payload["businessContactPhone"]; + this.authorizedContactVerificationEmail = payload["authorizedContactVerificationEmail"]; + this.authorizedContactMobilePhoneNumberE164 = payload["authorizedContactMobilePhoneNumberE164"]; + this.isTest = payload["isTest"]; + this.skipAutomaticSecVet = payload["skipAutomaticSecVet"]; + } +} + + + +/** + * Options to pass to create a A2PBrandRegistrationInstance + */ +export interface A2PBrandRegistrationListInstanceCreateOptions { + /** */ + "trusthubV1A2PBrandRegistrationRequest": TrusthubV1A2pBrandRegistrationRequest; +} + + +export interface A2PBrandRegistrationSolution { +} + +export interface A2PBrandRegistrationListInstance { + _version: V1; + _solution: A2PBrandRegistrationSolution; + _uri: string; + + + + /** + * Create a A2PBrandRegistrationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed A2PBrandRegistrationInstance + */ + create(params: TrusthubV1A2pBrandRegistrationRequest, headers?: any, callback?: (error: Error | null, item?: A2PBrandRegistrationInstance) => any): Promise<A2PBrandRegistrationInstance>; + + /** + * Create a A2PBrandRegistrationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed A2PBrandRegistrationInstance with HTTP metadata + */ + createWithHttpInfo(params: TrusthubV1A2pBrandRegistrationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<A2PBrandRegistrationInstance>) => any): Promise<ApiResponse<A2PBrandRegistrationInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function A2PBrandRegistrationListInstance(version: V1): A2PBrandRegistrationListInstance { + const instance = {} as A2PBrandRegistrationListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/A2PBrandRegistrations`; + + instance.create = function create(params: TrusthubV1A2pBrandRegistrationRequest, headers?: any, callback?: (error: Error | null, items: A2PBrandRegistrationInstance) => any): Promise<A2PBrandRegistrationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new A2PBrandRegistrationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TrusthubV1A2pBrandRegistrationRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<A2PBrandRegistrationInstance>) => any): Promise<ApiResponse<A2PBrandRegistrationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<A2PBrandRegistrationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<A2PBrandRegistrationInstance> => ({ + ...response, + body: new A2PBrandRegistrationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface A2PBrandRegistrationPayload extends A2PBrandRegistrationResource {} + +interface A2PBrandRegistrationResource { + id: string; + sessionId: string; + sessionToken: string; +} + +export class A2PBrandRegistrationInstance { + + constructor(protected _version: V1, payload: A2PBrandRegistrationResource) { + + this.id = (payload.id); + this.sessionId = (payload.sessionId); + this.sessionToken = (payload.sessionToken); + + } + + /** + * The unique A2P Brand or Campaign Registration identifier, formatted as `tri1.us1.account.AC.../registration.BU...`. + */ + id: string; + /** + * The Persona inquiry ID used to start the embedded compliance session. + */ + sessionId: string; + /** + * The Persona session token for embedding the compliance UI. Expires in 24 hours. + */ + sessionToken: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + sessionId: this.sessionId, + sessionToken: this.sessionToken, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/trusthub/v1/a2PBrandRegistrationEmbeddedSession.ts b/rest/trusthub/v1/a2PBrandRegistrationEmbeddedSession.ts new file mode 100644 index 000000000..7511f7e79 --- /dev/null +++ b/rest/trusthub/v1/a2PBrandRegistrationEmbeddedSession.ts @@ -0,0 +1,169 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface A2PBrandRegistrationEmbeddedSessionSolution { + id: string; +} + +export interface A2PBrandRegistrationEmbeddedSessionListInstance { + _version: V1; + _solution: A2PBrandRegistrationEmbeddedSessionSolution; + _uri: string; + + + + /** + * Create a A2PBrandRegistrationEmbeddedSessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed A2PBrandRegistrationEmbeddedSessionInstance + */ + create(callback?: (error: Error | null, item?: A2PBrandRegistrationEmbeddedSessionInstance) => any): Promise<A2PBrandRegistrationEmbeddedSessionInstance> + + /** + * Create a A2PBrandRegistrationEmbeddedSessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed A2PBrandRegistrationEmbeddedSessionInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<A2PBrandRegistrationEmbeddedSessionInstance>) => any): Promise<ApiResponse<A2PBrandRegistrationEmbeddedSessionInstance>> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function A2PBrandRegistrationEmbeddedSessionListInstance(version: V1, id: string): A2PBrandRegistrationEmbeddedSessionListInstance { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + const instance = {} as A2PBrandRegistrationEmbeddedSessionListInstance; + + instance._version = version; + instance._solution = { id, }; + instance._uri = `/A2PBrandRegistrations/${id}/EmbeddedSessions`; + + instance.create = function create( callback?: (error: Error | null, items: A2PBrandRegistrationEmbeddedSessionInstance) => any): Promise<A2PBrandRegistrationEmbeddedSessionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new A2PBrandRegistrationEmbeddedSessionInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<A2PBrandRegistrationEmbeddedSessionInstance>) => any): Promise<ApiResponse<A2PBrandRegistrationEmbeddedSessionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<A2PBrandRegistrationEmbeddedSessionResource>({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse<A2PBrandRegistrationEmbeddedSessionInstance> => ({ + ...response, + body: new A2PBrandRegistrationEmbeddedSessionInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface A2PBrandRegistrationEmbeddedSessionPayload extends A2PBrandRegistrationEmbeddedSessionResource {} + +interface A2PBrandRegistrationEmbeddedSessionResource { + id: string; + sessionId: string; + sessionToken: string; +} + +export class A2PBrandRegistrationEmbeddedSessionInstance { + + constructor(protected _version: V1, payload: A2PBrandRegistrationEmbeddedSessionResource, id?: string) { + + this.id = (payload.id); + this.sessionId = (payload.sessionId); + this.sessionToken = (payload.sessionToken); + + } + + /** + * The unique A2P Brand or Campaign Registration identifier, formatted as `tri1.us1.account.AC.../registration.BU...`. + */ + id: string; + /** + * The Persona inquiry ID used to start the embedded compliance session. + */ + sessionId: string; + /** + * The Persona session token for embedding the compliance UI. Expires in 24 hours. + */ + sessionToken: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + sessionId: this.sessionId, + sessionToken: this.sessionToken, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/trusthub/v1/a2PCampaignRegistration.ts b/rest/trusthub/v1/a2PCampaignRegistration.ts new file mode 100644 index 000000000..3bdc4704d --- /dev/null +++ b/rest/trusthub/v1/a2PCampaignRegistration.ts @@ -0,0 +1,335 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class TrusthubV1A2pCampaignRegistrationRequest { + /** + * The legacy Twilio A2P Brand SID (BN-prefixed) for the brand this campaign is registered under. This is a different identifier from the `id` returned by the Initialize Brand endpoint (which is formatted as `tri1.us1.account.AC.../registration.BU...`). Retrieve the BN brand SID via [GET /v1/a2p/BrandRegistrations/{Sid}](https://www.twilio.com/docs/messaging/api/brand-registration-resource) on `messaging.twilio.com`. + */ + "a2pBrandRegistrationSid": string; + /** + * The SID of the Messaging Service. + */ + "messagingServiceSid"?: string; + /** + * Theme ID for styling the inquiry form. + */ + "themeSetId"?: string; + /** + * The categories of the messaging use case. + */ + "useCaseCategories"?: Array<string>; + /** + * A description of the messaging use case. + */ + "useCaseDescription"?: string; + /** + * A sample message for the use case. + */ + "useCaseSampleMessage1"?: string; + /** + * A second sample message for the use case. + */ + "useCaseSampleMessage2"?: string; + /** + * A third sample message for the use case. + */ + "useCaseSampleMessage3"?: string; + /** + * A fourth sample message for the use case. + */ + "useCaseSampleMessage4"?: string; + /** + * A fifth sample message for the use case. + */ + "useCaseSampleMessage5"?: string; + /** + * The opt-in methods for the use case. + */ + "useCaseOptInTypes"?: Array<string>; + /** + * A description of the opt-in process. + */ + "useCaseOptInDescription"?: string; + /** + * Whether messages will contain embedded links. + */ + "hasEmbeddedLinks"?: boolean; + /** + * Whether messages will contain embedded phone numbers. + */ + "hasEmbeddedPhone"?: boolean; + /** + * A sample URL that will be embedded in messages (must use https://). + */ + "embeddedUrlSample"?: string; + /** + * Whether the campaign involves direct lending. + */ + "directLending"?: boolean; + /** + * Whether the content is age-gated. + */ + "ageGated"?: boolean; + /** + * The URL to the privacy policy. + */ + "privacyPolicyUrl"?: string; + /** + * The URL to the terms and conditions. + */ + "termsAndConditionsUrl"?: string; + /** + * Keywords users can text to opt in. + */ + "optInKeywords"?: Array<string>; + /** + * A sample opt-in confirmation message. + */ + "optInMessageSample"?: string; + /** + * Keywords users can text to opt out. + */ + "optOutKeywords"?: Array<string>; + /** + * A sample opt-out confirmation message. + */ + "optOutMessageSample"?: string; + /** + * Keywords users can text for help. + */ + "helpKeywords"?: Array<string>; + /** + * A sample help message. + */ + "helpMessageSample"?: string; + + constructor(payload) { + this.a2pBrandRegistrationSid = payload["a2pBrandRegistrationSid"]; + this.messagingServiceSid = payload["messagingServiceSid"]; + this.themeSetId = payload["themeSetId"]; + this.useCaseCategories = payload["useCaseCategories"]; + this.useCaseDescription = payload["useCaseDescription"]; + this.useCaseSampleMessage1 = payload["useCaseSampleMessage1"]; + this.useCaseSampleMessage2 = payload["useCaseSampleMessage2"]; + this.useCaseSampleMessage3 = payload["useCaseSampleMessage3"]; + this.useCaseSampleMessage4 = payload["useCaseSampleMessage4"]; + this.useCaseSampleMessage5 = payload["useCaseSampleMessage5"]; + this.useCaseOptInTypes = payload["useCaseOptInTypes"]; + this.useCaseOptInDescription = payload["useCaseOptInDescription"]; + this.hasEmbeddedLinks = payload["hasEmbeddedLinks"]; + this.hasEmbeddedPhone = payload["hasEmbeddedPhone"]; + this.embeddedUrlSample = payload["embeddedUrlSample"]; + this.directLending = payload["directLending"]; + this.ageGated = payload["ageGated"]; + this.privacyPolicyUrl = payload["privacyPolicyUrl"]; + this.termsAndConditionsUrl = payload["termsAndConditionsUrl"]; + this.optInKeywords = payload["optInKeywords"]; + this.optInMessageSample = payload["optInMessageSample"]; + this.optOutKeywords = payload["optOutKeywords"]; + this.optOutMessageSample = payload["optOutMessageSample"]; + this.helpKeywords = payload["helpKeywords"]; + this.helpMessageSample = payload["helpMessageSample"]; + } +} + + + +/** + * Options to pass to create a A2PCampaignRegistrationInstance + */ +export interface A2PCampaignRegistrationListInstanceCreateOptions { + /** */ + "trusthubV1A2PCampaignRegistrationRequest": TrusthubV1A2pCampaignRegistrationRequest; +} + + +export interface A2PCampaignRegistrationSolution { +} + +export interface A2PCampaignRegistrationListInstance { + _version: V1; + _solution: A2PCampaignRegistrationSolution; + _uri: string; + + + + /** + * Create a A2PCampaignRegistrationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed A2PCampaignRegistrationInstance + */ + create(params: TrusthubV1A2pCampaignRegistrationRequest, headers?: any, callback?: (error: Error | null, item?: A2PCampaignRegistrationInstance) => any): Promise<A2PCampaignRegistrationInstance>; + + /** + * Create a A2PCampaignRegistrationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed A2PCampaignRegistrationInstance with HTTP metadata + */ + createWithHttpInfo(params: TrusthubV1A2pCampaignRegistrationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<A2PCampaignRegistrationInstance>) => any): Promise<ApiResponse<A2PCampaignRegistrationInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function A2PCampaignRegistrationListInstance(version: V1): A2PCampaignRegistrationListInstance { + const instance = {} as A2PCampaignRegistrationListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/A2PCampaignRegistrations`; + + instance.create = function create(params: TrusthubV1A2pCampaignRegistrationRequest, headers?: any, callback?: (error: Error | null, items: A2PCampaignRegistrationInstance) => any): Promise<A2PCampaignRegistrationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new A2PCampaignRegistrationInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TrusthubV1A2pCampaignRegistrationRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<A2PCampaignRegistrationInstance>) => any): Promise<ApiResponse<A2PCampaignRegistrationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<A2PCampaignRegistrationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<A2PCampaignRegistrationInstance> => ({ + ...response, + body: new A2PCampaignRegistrationInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface A2PCampaignRegistrationPayload extends A2PCampaignRegistrationResource {} + +interface A2PCampaignRegistrationResource { + id: string; + sessionId: string; + sessionToken: string; +} + +export class A2PCampaignRegistrationInstance { + + constructor(protected _version: V1, payload: A2PCampaignRegistrationResource) { + + this.id = (payload.id); + this.sessionId = (payload.sessionId); + this.sessionToken = (payload.sessionToken); + + } + + /** + * The unique A2P Brand or Campaign Registration identifier, formatted as `tri1.us1.account.AC.../registration.BU...`. + */ + id: string; + /** + * The Persona inquiry ID used to start the embedded compliance session. + */ + sessionId: string; + /** + * The Persona session token for embedding the compliance UI. Expires in 24 hours. + */ + sessionToken: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + sessionId: this.sessionId, + sessionToken: this.sessionToken, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/trusthub/v1/a2PCampaignRegistrationEmbeddedSession.ts b/rest/trusthub/v1/a2PCampaignRegistrationEmbeddedSession.ts new file mode 100644 index 000000000..d6cc9d4ea --- /dev/null +++ b/rest/trusthub/v1/a2PCampaignRegistrationEmbeddedSession.ts @@ -0,0 +1,169 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface A2PCampaignRegistrationEmbeddedSessionSolution { + id: string; +} + +export interface A2PCampaignRegistrationEmbeddedSessionListInstance { + _version: V1; + _solution: A2PCampaignRegistrationEmbeddedSessionSolution; + _uri: string; + + + + /** + * Create a A2PCampaignRegistrationEmbeddedSessionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed A2PCampaignRegistrationEmbeddedSessionInstance + */ + create(callback?: (error: Error | null, item?: A2PCampaignRegistrationEmbeddedSessionInstance) => any): Promise<A2PCampaignRegistrationEmbeddedSessionInstance> + + /** + * Create a A2PCampaignRegistrationEmbeddedSessionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed A2PCampaignRegistrationEmbeddedSessionInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<A2PCampaignRegistrationEmbeddedSessionInstance>) => any): Promise<ApiResponse<A2PCampaignRegistrationEmbeddedSessionInstance>> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function A2PCampaignRegistrationEmbeddedSessionListInstance(version: V1, id: string): A2PCampaignRegistrationEmbeddedSessionListInstance { + if (!isValidPathParam(id)) { + throw new Error('Parameter \'id\' is not valid.'); + } + + const instance = {} as A2PCampaignRegistrationEmbeddedSessionListInstance; + + instance._version = version; + instance._solution = { id, }; + instance._uri = `/A2PCampaignRegistrations/${id}/EmbeddedSessions`; + + instance.create = function create( callback?: (error: Error | null, items: A2PCampaignRegistrationEmbeddedSessionInstance) => any): Promise<A2PCampaignRegistrationEmbeddedSessionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new A2PCampaignRegistrationEmbeddedSessionInstance(operationVersion, payload, instance._solution.id)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<A2PCampaignRegistrationEmbeddedSessionInstance>) => any): Promise<ApiResponse<A2PCampaignRegistrationEmbeddedSessionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<A2PCampaignRegistrationEmbeddedSessionResource>({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse<A2PCampaignRegistrationEmbeddedSessionInstance> => ({ + ...response, + body: new A2PCampaignRegistrationEmbeddedSessionInstance(operationVersion, response.body, instance._solution.id) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface A2PCampaignRegistrationEmbeddedSessionPayload extends A2PCampaignRegistrationEmbeddedSessionResource {} + +interface A2PCampaignRegistrationEmbeddedSessionResource { + id: string; + sessionId: string; + sessionToken: string; +} + +export class A2PCampaignRegistrationEmbeddedSessionInstance { + + constructor(protected _version: V1, payload: A2PCampaignRegistrationEmbeddedSessionResource, id?: string) { + + this.id = (payload.id); + this.sessionId = (payload.sessionId); + this.sessionToken = (payload.sessionToken); + + } + + /** + * The unique A2P Brand or Campaign Registration identifier, formatted as `tri1.us1.account.AC.../registration.BU...`. + */ + id: string; + /** + * The Persona inquiry ID used to start the embedded compliance session. + */ + sessionId: string; + /** + * The Persona session token for embedding the compliance UI. Expires in 24 hours. + */ + sessionToken: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + sessionId: this.sessionId, + sessionToken: this.sessionToken, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/trusthub/v1/complianceInquiries.ts b/rest/trusthub/v1/complianceInquiries.ts new file mode 100644 index 000000000..7330194d9 --- /dev/null +++ b/rest/trusthub/v1/complianceInquiries.ts @@ -0,0 +1,435 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to update a ComplianceInquiriesInstance + */ +export interface ComplianceInquiriesContextUpdateOptions { + /** The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. */ + "primaryProfileSid": string; + /** Theme id for styling the inquiry form. */ + "themeSetId"?: string; +} + +/** + * Options to pass to create a ComplianceInquiriesInstance + */ +export interface ComplianceInquiriesListInstanceCreateOptions { + /** The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. */ + "notificationEmail"?: string; + /** Theme id for styling the inquiry form. */ + "themeSetId"?: string; + /** The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. */ + "primaryProfileSid"?: string; +} + +export interface ComplianceInquiriesContext { + + /** + * Update a ComplianceInquiriesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceInquiriesInstance + */ + update(params: ComplianceInquiriesContextUpdateOptions, callback?: (error: Error | null, item?: ComplianceInquiriesInstance) => any): Promise<ComplianceInquiriesInstance>; + + /** + * Update a ComplianceInquiriesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceInquiriesInstance with HTTP metadata + */ + updateWithHttpInfo(params: ComplianceInquiriesContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ComplianceInquiriesInstance>) => any): Promise<ApiResponse<ComplianceInquiriesInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ComplianceInquiriesContextSolution { + "customerId": string; +} + +export class ComplianceInquiriesContextImpl implements ComplianceInquiriesContext { + protected _solution: ComplianceInquiriesContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, customerId: string) { + if (!isValidPathParam(customerId)) { + throw new Error('Parameter \'customerId\' is not valid.'); + } + + this._solution = { customerId, }; + this._uri = `/ComplianceInquiries/Customers/${customerId}/Initialize`; + } + + update(params: ComplianceInquiriesContextUpdateOptions,callback?: (error: Error | null, item?: ComplianceInquiriesInstance) => any): Promise<ComplianceInquiriesInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["primaryProfileSid"] === null || params["primaryProfileSid"] === undefined) { + throw new Error('Required parameter "params[\'primaryProfileSid\']" missing.'); + } + + let data: any = {}; + + + + data["PrimaryProfileSid"] = params["primaryProfileSid"]; + if (params["themeSetId"] !== undefined) + data["ThemeSetId"] = params["themeSetId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ComplianceInquiriesInstance(operationVersion, payload, instance._solution.customerId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: ComplianceInquiriesContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<ComplianceInquiriesInstance>) => any): Promise<ApiResponse<ComplianceInquiriesInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["primaryProfileSid"] === null || params["primaryProfileSid"] === undefined) { + throw new Error('Required parameter "params[\'primaryProfileSid\']" missing.'); + } + + let data: any = {}; + + + + data["PrimaryProfileSid"] = params["primaryProfileSid"]; + if (params["themeSetId"] !== undefined) + data["ThemeSetId"] = params["themeSetId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ComplianceInquiriesResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ComplianceInquiriesInstance> => ({ + ...response, + body: new ComplianceInquiriesInstance(operationVersion, response.body, instance._solution.customerId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ComplianceInquiriesPayload extends ComplianceInquiriesResource {} + +interface ComplianceInquiriesResource { + inquiry_id: string; + inquiry_session_token: string; + customer_id: string; + url: string; +} + +export class ComplianceInquiriesInstance { + protected _solution: ComplianceInquiriesContextSolution; + protected _context?: ComplianceInquiriesContext; + + constructor(protected _version: V1, payload: ComplianceInquiriesResource, customerId?: string) { + + this.inquiryId = (payload.inquiry_id); + this.inquirySessionToken = (payload.inquiry_session_token); + this.customerId = (payload.customer_id); + this.url = (payload.url); + + this._solution = { customerId: customerId, }; + } + + /** + * The unique ID used to start an embedded compliance registration session. + */ + inquiryId: string; + /** + * The session token used to start an embedded compliance registration session. + */ + inquirySessionToken: string; + /** + * The CustomerID matching the Customer Profile that should be resumed or resubmitted for editing. + */ + customerId: string; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): ComplianceInquiriesContext { + this._context = this._context || new ComplianceInquiriesContextImpl(this._version, this._solution.customerId); + return this._context; + } + + /** + * Update a ComplianceInquiriesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceInquiriesInstance + */ + update(params: ComplianceInquiriesContextUpdateOptions, callback?: (error: Error | null, item?: ComplianceInquiriesInstance) => any): Promise<ComplianceInquiriesInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ComplianceInquiriesInstance) => any): Promise<ComplianceInquiriesInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ComplianceInquiriesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceInquiriesInstance with HTTP metadata + */ + updateWithHttpInfo(params: ComplianceInquiriesContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ComplianceInquiriesInstance>) => any): Promise<ApiResponse<ComplianceInquiriesInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ComplianceInquiriesInstance>) => any): Promise<ApiResponse<ComplianceInquiriesInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + inquiryId: this.inquiryId, + inquirySessionToken: this.inquirySessionToken, + customerId: this.customerId, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ComplianceInquiriesSolution { +} + +export interface ComplianceInquiriesListInstance { + _version: V1; + _solution: ComplianceInquiriesSolution; + _uri: string; + + (customerId: string, ): ComplianceInquiriesContext; + get(customerId: string, ): ComplianceInquiriesContext; + + + + + /** + * Create a ComplianceInquiriesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceInquiriesInstance + */ + create(callback?: (error: Error | null, item?: ComplianceInquiriesInstance) => any): Promise<ComplianceInquiriesInstance>; + /** + * Create a ComplianceInquiriesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceInquiriesInstance + */ + create(params: ComplianceInquiriesListInstanceCreateOptions, callback?: (error: Error | null, item?: ComplianceInquiriesInstance) => any): Promise<ComplianceInquiriesInstance>; + + /** + * Create a ComplianceInquiriesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceInquiriesInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ComplianceInquiriesInstance>) => any): Promise<ApiResponse<ComplianceInquiriesInstance>>; + /** + * Create a ComplianceInquiriesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceInquiriesInstance with HTTP metadata + */ + createWithHttpInfo(params: ComplianceInquiriesListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ComplianceInquiriesInstance>) => any): Promise<ApiResponse<ComplianceInquiriesInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ComplianceInquiriesListInstance(version: V1): ComplianceInquiriesListInstance { + const instance = ((customerId, ) => instance.get(customerId, )) as ComplianceInquiriesListInstance; + + instance.get = function get(customerId, ): ComplianceInquiriesContext { + return new ComplianceInquiriesContextImpl(version, customerId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ComplianceInquiries/Customers/Initialize`; + + instance.create = function create(params?: ComplianceInquiriesListInstanceCreateOptions | ((error: Error | null, items: ComplianceInquiriesInstance) => any), callback?: (error: Error | null, items: ComplianceInquiriesInstance) => any): Promise<ComplianceInquiriesInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["notificationEmail"] !== undefined) + data["NotificationEmail"] = params["notificationEmail"]; + if (params["themeSetId"] !== undefined) + data["ThemeSetId"] = params["themeSetId"]; + if (params["primaryProfileSid"] !== undefined) + data["PrimaryProfileSid"] = params["primaryProfileSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ComplianceInquiriesInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ComplianceInquiriesListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<ComplianceInquiriesInstance>) => any), callback?: (error: Error | null, items: ApiResponse<ComplianceInquiriesInstance>) => any): Promise<ApiResponse<ComplianceInquiriesInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["notificationEmail"] !== undefined) + data["NotificationEmail"] = params["notificationEmail"]; + if (params["themeSetId"] !== undefined) + data["ThemeSetId"] = params["themeSetId"]; + if (params["primaryProfileSid"] !== undefined) + data["PrimaryProfileSid"] = params["primaryProfileSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ComplianceInquiriesResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ComplianceInquiriesInstance> => ({ + ...response, + body: new ComplianceInquiriesInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/trusthub/v1/complianceRegistrationInquiries.ts b/rest/trusthub/v1/complianceRegistrationInquiries.ts new file mode 100644 index 000000000..65361eb3f --- /dev/null +++ b/rest/trusthub/v1/complianceRegistrationInquiries.ts @@ -0,0 +1,695 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The type of business identity. Can be `direct customer` or `ISV`. + */ +export type ComplianceRegistrationInquiriesBusinessIdentityType = 'direct_customer'|'isv_reseller_or_partner'|'unknown'; + +/** + * The authority that registered the business + */ +export type ComplianceRegistrationInquiriesBusinessRegistrationAuthority = 'UK:CRN'|'US:EIN'|'CA:CBN'|'AU:ACN'|'Other'; + +/** + * The type of End User the regulation requires - can be `Individual` or `Business`. + */ +export type ComplianceRegistrationInquiriesEndUserType = 'Individual'|'Business'; + +/** + * The type of phone number of the Bundle\'s ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + */ +export type ComplianceRegistrationInquiriesPhoneNumberType = 'local'|'national'|'mobile'|'toll-free'; + + +/** + * Options to pass to update a ComplianceRegistrationInquiriesInstance + */ +export interface ComplianceRegistrationInquiriesContextUpdateOptions { + /** Indicates if the inquiry is being started from an ISV embedded component. */ + "isIsvEmbed"?: boolean; + /** Theme id for styling the inquiry form. */ + "themeSetId"?: string; +} + +/** + * Options to pass to create a ComplianceRegistrationInquiriesInstance + */ +export interface ComplianceRegistrationInquiriesListInstanceCreateOptions { + /** */ + "endUserType": ComplianceRegistrationInquiriesEndUserType; + /** */ + "phoneNumberType": ComplianceRegistrationInquiriesPhoneNumberType; + /** */ + "businessIdentityType"?: ComplianceRegistrationInquiriesBusinessIdentityType; + /** */ + "businessRegistrationAuthority"?: ComplianceRegistrationInquiriesBusinessRegistrationAuthority; + /** he name of the business or organization using the Tollfree number. */ + "businessLegalName"?: string; + /** he email address to receive the notification about the verification result. */ + "notificationEmail"?: string; + /** The email address to receive the notification about the verification result. */ + "acceptedNotificationReceipt"?: boolean; + /** Business registration number of the business */ + "businessRegistrationNumber"?: string; + /** The URL of the business website */ + "businessWebsiteUrl"?: string; + /** Friendly name for your business information */ + "friendlyName"?: string; + /** First name of the authorized representative */ + "authorizedRepresentative1FirstName"?: string; + /** Last name of the authorized representative */ + "authorizedRepresentative1LastName"?: string; + /** Phone number of the authorized representative */ + "authorizedRepresentative1Phone"?: string; + /** Email address of the authorized representative */ + "authorizedRepresentative1Email"?: string; + /** Birthdate of the authorized representative */ + "authorizedRepresentative1DateOfBirth"?: string; + /** Street address of the business */ + "addressStreet"?: string; + /** Street address of the business */ + "addressStreetSecondary"?: string; + /** City of the business */ + "addressCity"?: string; + /** State or province of the business */ + "addressSubdivision"?: string; + /** Postal code of the business */ + "addressPostalCode"?: string; + /** Country code of the business */ + "addressCountryCode"?: string; + /** Street address of the business */ + "emergencyAddressStreet"?: string; + /** Street address of the business */ + "emergencyAddressStreetSecondary"?: string; + /** City of the business */ + "emergencyAddressCity"?: string; + /** State or province of the business */ + "emergencyAddressSubdivision"?: string; + /** Postal code of the business */ + "emergencyAddressPostalCode"?: string; + /** Country code of the business */ + "emergencyAddressCountryCode"?: string; + /** Use the business address as the emergency address */ + "useAddressAsEmergencyAddress"?: boolean; + /** The name of the verification document to upload */ + "fileName"?: string; + /** The verification document to upload */ + "file"?: string; + /** The first name of the Individual User. */ + "firstName"?: string; + /** The last name of the Individual User. */ + "lastName"?: string; + /** The date of birth of the Individual User. */ + "dateOfBirth"?: string; + /** The email address of the Individual User. */ + "individualEmail"?: string; + /** The phone number of the Individual User. */ + "individualPhone"?: string; + /** Indicates if the inquiry is being started from an ISV embedded component. */ + "isIsvEmbed"?: boolean; + /** Indicates if the isv registering for self or tenant. */ + "isvRegisteringForSelfOrTenant"?: string; + /** The url we call to inform you of bundle changes. */ + "statusCallbackUrl"?: string; + /** Theme id for styling the inquiry form. */ + "themeSetId"?: string; +} + +export interface ComplianceRegistrationInquiriesContext { + + /** + * Update a ComplianceRegistrationInquiriesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceRegistrationInquiriesInstance + */ + update(callback?: (error: Error | null, item?: ComplianceRegistrationInquiriesInstance) => any): Promise<ComplianceRegistrationInquiriesInstance>; + /** + * Update a ComplianceRegistrationInquiriesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceRegistrationInquiriesInstance + */ + update(params: ComplianceRegistrationInquiriesContextUpdateOptions, callback?: (error: Error | null, item?: ComplianceRegistrationInquiriesInstance) => any): Promise<ComplianceRegistrationInquiriesInstance>; + + /** + * Update a ComplianceRegistrationInquiriesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceRegistrationInquiriesInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ComplianceRegistrationInquiriesInstance>) => any): Promise<ApiResponse<ComplianceRegistrationInquiriesInstance>>; + /** + * Update a ComplianceRegistrationInquiriesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceRegistrationInquiriesInstance with HTTP metadata + */ + updateWithHttpInfo(params: ComplianceRegistrationInquiriesContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ComplianceRegistrationInquiriesInstance>) => any): Promise<ApiResponse<ComplianceRegistrationInquiriesInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ComplianceRegistrationInquiriesContextSolution { + "registrationId": string; +} + +export class ComplianceRegistrationInquiriesContextImpl implements ComplianceRegistrationInquiriesContext { + protected _solution: ComplianceRegistrationInquiriesContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, registrationId: string) { + if (!isValidPathParam(registrationId)) { + throw new Error('Parameter \'registrationId\' is not valid.'); + } + + this._solution = { registrationId, }; + this._uri = `/ComplianceInquiries/Registration/${registrationId}/RegulatoryCompliance/GB/Initialize`; + } + + update(params?: ComplianceRegistrationInquiriesContextUpdateOptions | ((error: Error | null, item?: ComplianceRegistrationInquiriesInstance) => any),callback?: (error: Error | null, item?: ComplianceRegistrationInquiriesInstance) => any): Promise<ComplianceRegistrationInquiriesInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["isIsvEmbed"] !== undefined) + data["IsIsvEmbed"] = serialize.bool(params["isIsvEmbed"]); + if (params["themeSetId"] !== undefined) + data["ThemeSetId"] = params["themeSetId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ComplianceRegistrationInquiriesInstance(operationVersion, payload, instance._solution.registrationId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ComplianceRegistrationInquiriesContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ComplianceRegistrationInquiriesInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ComplianceRegistrationInquiriesInstance>) => any): Promise<ApiResponse<ComplianceRegistrationInquiriesInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["isIsvEmbed"] !== undefined) + data["IsIsvEmbed"] = serialize.bool(params["isIsvEmbed"]); + if (params["themeSetId"] !== undefined) + data["ThemeSetId"] = params["themeSetId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ComplianceRegistrationInquiriesResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ComplianceRegistrationInquiriesInstance> => ({ + ...response, + body: new ComplianceRegistrationInquiriesInstance(operationVersion, response.body, instance._solution.registrationId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ComplianceRegistrationInquiriesPayload extends ComplianceRegistrationInquiriesResource {} + +interface ComplianceRegistrationInquiriesResource { + inquiry_id: string; + inquiry_session_token: string; + registration_id: string; + url: string; +} + +export class ComplianceRegistrationInquiriesInstance { + protected _solution: ComplianceRegistrationInquiriesContextSolution; + protected _context?: ComplianceRegistrationInquiriesContext; + + constructor(protected _version: V1, payload: ComplianceRegistrationInquiriesResource, registrationId?: string) { + + this.inquiryId = (payload.inquiry_id); + this.inquirySessionToken = (payload.inquiry_session_token); + this.registrationId = (payload.registration_id); + this.url = (payload.url); + + this._solution = { registrationId: registrationId, }; + } + + /** + * The unique ID used to start an embedded compliance registration session. + */ + inquiryId: string; + /** + * The session token used to start an embedded compliance registration session. + */ + inquirySessionToken: string; + /** + * The RegistrationId matching the Registration Profile that should be resumed or resubmitted for editing. + */ + registrationId: string; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): ComplianceRegistrationInquiriesContext { + this._context = this._context || new ComplianceRegistrationInquiriesContextImpl(this._version, this._solution.registrationId); + return this._context; + } + + /** + * Update a ComplianceRegistrationInquiriesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceRegistrationInquiriesInstance + */ + update(callback?: (error: Error | null, item?: ComplianceRegistrationInquiriesInstance) => any): Promise<ComplianceRegistrationInquiriesInstance>; + /** + * Update a ComplianceRegistrationInquiriesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceRegistrationInquiriesInstance + */ + update(params: ComplianceRegistrationInquiriesContextUpdateOptions, callback?: (error: Error | null, item?: ComplianceRegistrationInquiriesInstance) => any): Promise<ComplianceRegistrationInquiriesInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ComplianceRegistrationInquiriesInstance) => any): Promise<ComplianceRegistrationInquiriesInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ComplianceRegistrationInquiriesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceRegistrationInquiriesInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ComplianceRegistrationInquiriesInstance>) => any): Promise<ApiResponse<ComplianceRegistrationInquiriesInstance>>; + /** + * Update a ComplianceRegistrationInquiriesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceRegistrationInquiriesInstance with HTTP metadata + */ + updateWithHttpInfo(params: ComplianceRegistrationInquiriesContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ComplianceRegistrationInquiriesInstance>) => any): Promise<ApiResponse<ComplianceRegistrationInquiriesInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ComplianceRegistrationInquiriesInstance>) => any): Promise<ApiResponse<ComplianceRegistrationInquiriesInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + inquiryId: this.inquiryId, + inquirySessionToken: this.inquirySessionToken, + registrationId: this.registrationId, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ComplianceRegistrationInquiriesSolution { +} + +export interface ComplianceRegistrationInquiriesListInstance { + _version: V1; + _solution: ComplianceRegistrationInquiriesSolution; + _uri: string; + + (registrationId: string, ): ComplianceRegistrationInquiriesContext; + get(registrationId: string, ): ComplianceRegistrationInquiriesContext; + + + + + /** + * Create a ComplianceRegistrationInquiriesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceRegistrationInquiriesInstance + */ + create(params: ComplianceRegistrationInquiriesListInstanceCreateOptions, callback?: (error: Error | null, item?: ComplianceRegistrationInquiriesInstance) => any): Promise<ComplianceRegistrationInquiriesInstance>; + + /** + * Create a ComplianceRegistrationInquiriesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceRegistrationInquiriesInstance with HTTP metadata + */ + createWithHttpInfo(params: ComplianceRegistrationInquiriesListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ComplianceRegistrationInquiriesInstance>) => any): Promise<ApiResponse<ComplianceRegistrationInquiriesInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ComplianceRegistrationInquiriesListInstance(version: V1): ComplianceRegistrationInquiriesListInstance { + const instance = ((registrationId, ) => instance.get(registrationId, )) as ComplianceRegistrationInquiriesListInstance; + + instance.get = function get(registrationId, ): ComplianceRegistrationInquiriesContext { + return new ComplianceRegistrationInquiriesContextImpl(version, registrationId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ComplianceInquiries/Registration/RegulatoryCompliance/GB/Initialize`; + + instance.create = function create(params: ComplianceRegistrationInquiriesListInstanceCreateOptions, callback?: (error: Error | null, items: ComplianceRegistrationInquiriesInstance) => any): Promise<ComplianceRegistrationInquiriesInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["endUserType"] === null || params["endUserType"] === undefined) { + throw new Error('Required parameter "params[\'endUserType\']" missing.'); + } + + if (params["phoneNumberType"] === null || params["phoneNumberType"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumberType\']" missing.'); + } + + let data: any = {}; + + + + data["EndUserType"] = params["endUserType"]; + + data["PhoneNumberType"] = params["phoneNumberType"]; + if (params["businessIdentityType"] !== undefined) + data["BusinessIdentityType"] = params["businessIdentityType"]; + if (params["businessRegistrationAuthority"] !== undefined) + data["BusinessRegistrationAuthority"] = params["businessRegistrationAuthority"]; + if (params["businessLegalName"] !== undefined) + data["BusinessLegalName"] = params["businessLegalName"]; + if (params["notificationEmail"] !== undefined) + data["NotificationEmail"] = params["notificationEmail"]; + if (params["acceptedNotificationReceipt"] !== undefined) + data["AcceptedNotificationReceipt"] = serialize.bool(params["acceptedNotificationReceipt"]); + if (params["businessRegistrationNumber"] !== undefined) + data["BusinessRegistrationNumber"] = params["businessRegistrationNumber"]; + if (params["businessWebsiteUrl"] !== undefined) + data["BusinessWebsiteUrl"] = params["businessWebsiteUrl"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["authorizedRepresentative1FirstName"] !== undefined) + data["AuthorizedRepresentative1FirstName"] = params["authorizedRepresentative1FirstName"]; + if (params["authorizedRepresentative1LastName"] !== undefined) + data["AuthorizedRepresentative1LastName"] = params["authorizedRepresentative1LastName"]; + if (params["authorizedRepresentative1Phone"] !== undefined) + data["AuthorizedRepresentative1Phone"] = params["authorizedRepresentative1Phone"]; + if (params["authorizedRepresentative1Email"] !== undefined) + data["AuthorizedRepresentative1Email"] = params["authorizedRepresentative1Email"]; + if (params["authorizedRepresentative1DateOfBirth"] !== undefined) + data["AuthorizedRepresentative1DateOfBirth"] = params["authorizedRepresentative1DateOfBirth"]; + if (params["addressStreet"] !== undefined) + data["AddressStreet"] = params["addressStreet"]; + if (params["addressStreetSecondary"] !== undefined) + data["AddressStreetSecondary"] = params["addressStreetSecondary"]; + if (params["addressCity"] !== undefined) + data["AddressCity"] = params["addressCity"]; + if (params["addressSubdivision"] !== undefined) + data["AddressSubdivision"] = params["addressSubdivision"]; + if (params["addressPostalCode"] !== undefined) + data["AddressPostalCode"] = params["addressPostalCode"]; + if (params["addressCountryCode"] !== undefined) + data["AddressCountryCode"] = params["addressCountryCode"]; + if (params["emergencyAddressStreet"] !== undefined) + data["EmergencyAddressStreet"] = params["emergencyAddressStreet"]; + if (params["emergencyAddressStreetSecondary"] !== undefined) + data["EmergencyAddressStreetSecondary"] = params["emergencyAddressStreetSecondary"]; + if (params["emergencyAddressCity"] !== undefined) + data["EmergencyAddressCity"] = params["emergencyAddressCity"]; + if (params["emergencyAddressSubdivision"] !== undefined) + data["EmergencyAddressSubdivision"] = params["emergencyAddressSubdivision"]; + if (params["emergencyAddressPostalCode"] !== undefined) + data["EmergencyAddressPostalCode"] = params["emergencyAddressPostalCode"]; + if (params["emergencyAddressCountryCode"] !== undefined) + data["EmergencyAddressCountryCode"] = params["emergencyAddressCountryCode"]; + if (params["useAddressAsEmergencyAddress"] !== undefined) + data["UseAddressAsEmergencyAddress"] = serialize.bool(params["useAddressAsEmergencyAddress"]); + if (params["fileName"] !== undefined) + data["FileName"] = params["fileName"]; + if (params["file"] !== undefined) + data["File"] = params["file"]; + if (params["firstName"] !== undefined) + data["FirstName"] = params["firstName"]; + if (params["lastName"] !== undefined) + data["LastName"] = params["lastName"]; + if (params["dateOfBirth"] !== undefined) + data["DateOfBirth"] = params["dateOfBirth"]; + if (params["individualEmail"] !== undefined) + data["IndividualEmail"] = params["individualEmail"]; + if (params["individualPhone"] !== undefined) + data["IndividualPhone"] = params["individualPhone"]; + if (params["isIsvEmbed"] !== undefined) + data["IsIsvEmbed"] = serialize.bool(params["isIsvEmbed"]); + if (params["isvRegisteringForSelfOrTenant"] !== undefined) + data["IsvRegisteringForSelfOrTenant"] = params["isvRegisteringForSelfOrTenant"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["themeSetId"] !== undefined) + data["ThemeSetId"] = params["themeSetId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ComplianceRegistrationInquiriesInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ComplianceRegistrationInquiriesListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ComplianceRegistrationInquiriesInstance>) => any): Promise<ApiResponse<ComplianceRegistrationInquiriesInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["endUserType"] === null || params["endUserType"] === undefined) { + throw new Error('Required parameter "params[\'endUserType\']" missing.'); + } + + if (params["phoneNumberType"] === null || params["phoneNumberType"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumberType\']" missing.'); + } + + let data: any = {}; + + + + data["EndUserType"] = params["endUserType"]; + + data["PhoneNumberType"] = params["phoneNumberType"]; + if (params["businessIdentityType"] !== undefined) + data["BusinessIdentityType"] = params["businessIdentityType"]; + if (params["businessRegistrationAuthority"] !== undefined) + data["BusinessRegistrationAuthority"] = params["businessRegistrationAuthority"]; + if (params["businessLegalName"] !== undefined) + data["BusinessLegalName"] = params["businessLegalName"]; + if (params["notificationEmail"] !== undefined) + data["NotificationEmail"] = params["notificationEmail"]; + if (params["acceptedNotificationReceipt"] !== undefined) + data["AcceptedNotificationReceipt"] = serialize.bool(params["acceptedNotificationReceipt"]); + if (params["businessRegistrationNumber"] !== undefined) + data["BusinessRegistrationNumber"] = params["businessRegistrationNumber"]; + if (params["businessWebsiteUrl"] !== undefined) + data["BusinessWebsiteUrl"] = params["businessWebsiteUrl"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["authorizedRepresentative1FirstName"] !== undefined) + data["AuthorizedRepresentative1FirstName"] = params["authorizedRepresentative1FirstName"]; + if (params["authorizedRepresentative1LastName"] !== undefined) + data["AuthorizedRepresentative1LastName"] = params["authorizedRepresentative1LastName"]; + if (params["authorizedRepresentative1Phone"] !== undefined) + data["AuthorizedRepresentative1Phone"] = params["authorizedRepresentative1Phone"]; + if (params["authorizedRepresentative1Email"] !== undefined) + data["AuthorizedRepresentative1Email"] = params["authorizedRepresentative1Email"]; + if (params["authorizedRepresentative1DateOfBirth"] !== undefined) + data["AuthorizedRepresentative1DateOfBirth"] = params["authorizedRepresentative1DateOfBirth"]; + if (params["addressStreet"] !== undefined) + data["AddressStreet"] = params["addressStreet"]; + if (params["addressStreetSecondary"] !== undefined) + data["AddressStreetSecondary"] = params["addressStreetSecondary"]; + if (params["addressCity"] !== undefined) + data["AddressCity"] = params["addressCity"]; + if (params["addressSubdivision"] !== undefined) + data["AddressSubdivision"] = params["addressSubdivision"]; + if (params["addressPostalCode"] !== undefined) + data["AddressPostalCode"] = params["addressPostalCode"]; + if (params["addressCountryCode"] !== undefined) + data["AddressCountryCode"] = params["addressCountryCode"]; + if (params["emergencyAddressStreet"] !== undefined) + data["EmergencyAddressStreet"] = params["emergencyAddressStreet"]; + if (params["emergencyAddressStreetSecondary"] !== undefined) + data["EmergencyAddressStreetSecondary"] = params["emergencyAddressStreetSecondary"]; + if (params["emergencyAddressCity"] !== undefined) + data["EmergencyAddressCity"] = params["emergencyAddressCity"]; + if (params["emergencyAddressSubdivision"] !== undefined) + data["EmergencyAddressSubdivision"] = params["emergencyAddressSubdivision"]; + if (params["emergencyAddressPostalCode"] !== undefined) + data["EmergencyAddressPostalCode"] = params["emergencyAddressPostalCode"]; + if (params["emergencyAddressCountryCode"] !== undefined) + data["EmergencyAddressCountryCode"] = params["emergencyAddressCountryCode"]; + if (params["useAddressAsEmergencyAddress"] !== undefined) + data["UseAddressAsEmergencyAddress"] = serialize.bool(params["useAddressAsEmergencyAddress"]); + if (params["fileName"] !== undefined) + data["FileName"] = params["fileName"]; + if (params["file"] !== undefined) + data["File"] = params["file"]; + if (params["firstName"] !== undefined) + data["FirstName"] = params["firstName"]; + if (params["lastName"] !== undefined) + data["LastName"] = params["lastName"]; + if (params["dateOfBirth"] !== undefined) + data["DateOfBirth"] = params["dateOfBirth"]; + if (params["individualEmail"] !== undefined) + data["IndividualEmail"] = params["individualEmail"]; + if (params["individualPhone"] !== undefined) + data["IndividualPhone"] = params["individualPhone"]; + if (params["isIsvEmbed"] !== undefined) + data["IsIsvEmbed"] = serialize.bool(params["isIsvEmbed"]); + if (params["isvRegisteringForSelfOrTenant"] !== undefined) + data["IsvRegisteringForSelfOrTenant"] = params["isvRegisteringForSelfOrTenant"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["themeSetId"] !== undefined) + data["ThemeSetId"] = params["themeSetId"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ComplianceRegistrationInquiriesResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ComplianceRegistrationInquiriesInstance> => ({ + ...response, + body: new ComplianceRegistrationInquiriesInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/trusthub/v1/complianceTollfreeInquiries.ts b/rest/trusthub/v1/complianceTollfreeInquiries.ts new file mode 100644 index 000000000..fe616ebd8 --- /dev/null +++ b/rest/trusthub/v1/complianceTollfreeInquiries.ts @@ -0,0 +1,456 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * Type of Business. + */ +export type ComplianceTollfreeInquiriesBusinessType = 'PRIVATE_PROFIT'|'PUBLIC_PROFIT'|'NON_PROFIT'|'SOLE_PROPRIETOR'|'GOVERNMENT'; + +/** + * Describe how a user opts-in to text messages. + */ +export type ComplianceTollfreeInquiriesOptInType = 'VERBAL'|'WEB_FORM'|'PAPER_FORM'|'VIA_TEXT'|'MOBILE_QR_CODE'; + + +/** + * Options to pass to create a ComplianceTollfreeInquiriesInstance + */ +export interface ComplianceTollfreeInquiriesListInstanceCreateOptions { + /** The Tollfree phone number to be verified */ + "tollfreePhoneNumber": string; + /** The email address to receive the notification about the verification result. */ + "notificationEmail": string; + /** The Customer Profile Sid associated with the Account. */ + "customerProfileSid"?: string; + /** The name of the business or organization using the Tollfree number. */ + "businessName"?: string; + /** The website of the business or organization using the Tollfree number. */ + "businessWebsite"?: string; + /** The category of the use case for the Tollfree Number. List as many are applicable.. */ + "useCaseCategories"?: Array<string>; + /** Use this to further explain how messaging is used by the business or organization. */ + "useCaseSummary"?: string; + /** An example of message content, i.e. a sample message. */ + "productionMessageSample"?: string; + /** Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. */ + "optInImageUrls"?: Array<string>; + /** */ + "optInType"?: ComplianceTollfreeInquiriesOptInType; + /** Estimate monthly volume of messages from the Tollfree Number. */ + "messageVolume"?: string; + /** The address of the business or organization using the Tollfree number. */ + "businessStreetAddress"?: string; + /** The address of the business or organization using the Tollfree number. */ + "businessStreetAddress2"?: string; + /** The city of the business or organization using the Tollfree number. */ + "businessCity"?: string; + /** The state/province/region of the business or organization using the Tollfree number. */ + "businessStateProvinceRegion"?: string; + /** The postal code of the business or organization using the Tollfree number. */ + "businessPostalCode"?: string; + /** The country of the business or organization using the Tollfree number. */ + "businessCountry"?: string; + /** Additional information to be provided for verification. */ + "additionalInformation"?: string; + /** The first name of the contact for the business or organization using the Tollfree number. */ + "businessContactFirstName"?: string; + /** The last name of the contact for the business or organization using the Tollfree number. */ + "businessContactLastName"?: string; + /** The email address of the contact for the business or organization using the Tollfree number. */ + "businessContactEmail"?: string; + /** The phone number of the contact for the business or organization using the Tollfree number. */ + "businessContactPhone"?: string; + /** Theme id for styling the inquiry form. */ + "themeSetId"?: string; + /** Skip the messaging use case screen of the inquiry form. */ + "skipMessagingUseCase"?: boolean; + /** The Business Registration Number of the business or organization. */ + "businessRegistrationNumber"?: string; + /** The Business Registration Authority of the business or organization. */ + "businessRegistrationAuthority"?: string; + /** The Business Registration Country of the business or organization. */ + "businessRegistrationCountry"?: string; + /** */ + "businessType"?: ComplianceTollfreeInquiriesBusinessType; + /** Trade name, sub entity, or downstream business name of business being submitted for verification. */ + "doingBusinessAs"?: string; + /** The confirmation message sent to users when they opt in to receive messages. */ + "optInConfirmationMessage"?: string; + /** A sample help message provided to users. */ + "helpMessageSample"?: string; + /** The URL to the privacy policy for the business or organization. */ + "privacyPolicyUrl"?: string; + /** The URL to the terms and conditions for the business or organization. */ + "termsAndConditionsUrl"?: string; + /** Indicates if the content is age gated. */ + "ageGatedContent"?: boolean; + /** A legally recognized business registration number. */ + "externalReferenceId"?: string; + /** List of keywords that users can text in to opt in to receive messages. */ + "optInKeywords"?: Array<string>; + /** Unique identifier for the created Vetting . */ + "vettingId"?: string; + /** Name of the vetting provider. */ + "vettingProvider"?: string; +} + + +export interface ComplianceTollfreeInquiriesSolution { +} + +export interface ComplianceTollfreeInquiriesListInstance { + _version: V1; + _solution: ComplianceTollfreeInquiriesSolution; + _uri: string; + + + + /** + * Create a ComplianceTollfreeInquiriesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceTollfreeInquiriesInstance + */ + create(params: ComplianceTollfreeInquiriesListInstanceCreateOptions, callback?: (error: Error | null, item?: ComplianceTollfreeInquiriesInstance) => any): Promise<ComplianceTollfreeInquiriesInstance>; + + /** + * Create a ComplianceTollfreeInquiriesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ComplianceTollfreeInquiriesInstance with HTTP metadata + */ + createWithHttpInfo(params: ComplianceTollfreeInquiriesListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ComplianceTollfreeInquiriesInstance>) => any): Promise<ApiResponse<ComplianceTollfreeInquiriesInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ComplianceTollfreeInquiriesListInstance(version: V1): ComplianceTollfreeInquiriesListInstance { + const instance = {} as ComplianceTollfreeInquiriesListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/ComplianceInquiries/Tollfree/Initialize`; + + instance.create = function create(params: ComplianceTollfreeInquiriesListInstanceCreateOptions, callback?: (error: Error | null, items: ComplianceTollfreeInquiriesInstance) => any): Promise<ComplianceTollfreeInquiriesInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["tollfreePhoneNumber"] === null || params["tollfreePhoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'tollfreePhoneNumber\']" missing.'); + } + + if (params["notificationEmail"] === null || params["notificationEmail"] === undefined) { + throw new Error('Required parameter "params[\'notificationEmail\']" missing.'); + } + + let data: any = {}; + + + + data["TollfreePhoneNumber"] = params["tollfreePhoneNumber"]; + + data["NotificationEmail"] = params["notificationEmail"]; + if (params["customerProfileSid"] !== undefined) + data["CustomerProfileSid"] = params["customerProfileSid"]; + if (params["businessName"] !== undefined) + data["BusinessName"] = params["businessName"]; + if (params["businessWebsite"] !== undefined) + data["BusinessWebsite"] = params["businessWebsite"]; + if (params["useCaseCategories"] !== undefined) + data["UseCaseCategories"] = serialize.map(params["useCaseCategories"], (e: string) => (e)); + if (params["useCaseSummary"] !== undefined) + data["UseCaseSummary"] = params["useCaseSummary"]; + if (params["productionMessageSample"] !== undefined) + data["ProductionMessageSample"] = params["productionMessageSample"]; + if (params["optInImageUrls"] !== undefined) + data["OptInImageUrls"] = serialize.map(params["optInImageUrls"], (e: string) => (e)); + if (params["optInType"] !== undefined) + data["OptInType"] = params["optInType"]; + if (params["messageVolume"] !== undefined) + data["MessageVolume"] = params["messageVolume"]; + if (params["businessStreetAddress"] !== undefined) + data["BusinessStreetAddress"] = params["businessStreetAddress"]; + if (params["businessStreetAddress2"] !== undefined) + data["BusinessStreetAddress2"] = params["businessStreetAddress2"]; + if (params["businessCity"] !== undefined) + data["BusinessCity"] = params["businessCity"]; + if (params["businessStateProvinceRegion"] !== undefined) + data["BusinessStateProvinceRegion"] = params["businessStateProvinceRegion"]; + if (params["businessPostalCode"] !== undefined) + data["BusinessPostalCode"] = params["businessPostalCode"]; + if (params["businessCountry"] !== undefined) + data["BusinessCountry"] = params["businessCountry"]; + if (params["additionalInformation"] !== undefined) + data["AdditionalInformation"] = params["additionalInformation"]; + if (params["businessContactFirstName"] !== undefined) + data["BusinessContactFirstName"] = params["businessContactFirstName"]; + if (params["businessContactLastName"] !== undefined) + data["BusinessContactLastName"] = params["businessContactLastName"]; + if (params["businessContactEmail"] !== undefined) + data["BusinessContactEmail"] = params["businessContactEmail"]; + if (params["businessContactPhone"] !== undefined) + data["BusinessContactPhone"] = params["businessContactPhone"]; + if (params["themeSetId"] !== undefined) + data["ThemeSetId"] = params["themeSetId"]; + if (params["skipMessagingUseCase"] !== undefined) + data["SkipMessagingUseCase"] = serialize.bool(params["skipMessagingUseCase"]); + if (params["businessRegistrationNumber"] !== undefined) + data["BusinessRegistrationNumber"] = params["businessRegistrationNumber"]; + if (params["businessRegistrationAuthority"] !== undefined) + data["BusinessRegistrationAuthority"] = params["businessRegistrationAuthority"]; + if (params["businessRegistrationCountry"] !== undefined) + data["BusinessRegistrationCountry"] = params["businessRegistrationCountry"]; + if (params["businessType"] !== undefined) + data["BusinessType"] = params["businessType"]; + if (params["doingBusinessAs"] !== undefined) + data["DoingBusinessAs"] = params["doingBusinessAs"]; + if (params["optInConfirmationMessage"] !== undefined) + data["OptInConfirmationMessage"] = params["optInConfirmationMessage"]; + if (params["helpMessageSample"] !== undefined) + data["HelpMessageSample"] = params["helpMessageSample"]; + if (params["privacyPolicyUrl"] !== undefined) + data["PrivacyPolicyUrl"] = params["privacyPolicyUrl"]; + if (params["termsAndConditionsUrl"] !== undefined) + data["TermsAndConditionsUrl"] = params["termsAndConditionsUrl"]; + if (params["ageGatedContent"] !== undefined) + data["AgeGatedContent"] = serialize.bool(params["ageGatedContent"]); + if (params["externalReferenceId"] !== undefined) + data["ExternalReferenceId"] = params["externalReferenceId"]; + if (params["optInKeywords"] !== undefined) + data["OptInKeywords"] = serialize.map(params["optInKeywords"], (e: string) => (e)); + if (params["vettingId"] !== undefined) + data["VettingId"] = params["vettingId"]; + if (params["vettingProvider"] !== undefined) + data["VettingProvider"] = params["vettingProvider"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ComplianceTollfreeInquiriesInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ComplianceTollfreeInquiriesListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ComplianceTollfreeInquiriesInstance>) => any): Promise<ApiResponse<ComplianceTollfreeInquiriesInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["tollfreePhoneNumber"] === null || params["tollfreePhoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'tollfreePhoneNumber\']" missing.'); + } + + if (params["notificationEmail"] === null || params["notificationEmail"] === undefined) { + throw new Error('Required parameter "params[\'notificationEmail\']" missing.'); + } + + let data: any = {}; + + + + data["TollfreePhoneNumber"] = params["tollfreePhoneNumber"]; + + data["NotificationEmail"] = params["notificationEmail"]; + if (params["customerProfileSid"] !== undefined) + data["CustomerProfileSid"] = params["customerProfileSid"]; + if (params["businessName"] !== undefined) + data["BusinessName"] = params["businessName"]; + if (params["businessWebsite"] !== undefined) + data["BusinessWebsite"] = params["businessWebsite"]; + if (params["useCaseCategories"] !== undefined) + data["UseCaseCategories"] = serialize.map(params["useCaseCategories"], (e: string) => (e)); + if (params["useCaseSummary"] !== undefined) + data["UseCaseSummary"] = params["useCaseSummary"]; + if (params["productionMessageSample"] !== undefined) + data["ProductionMessageSample"] = params["productionMessageSample"]; + if (params["optInImageUrls"] !== undefined) + data["OptInImageUrls"] = serialize.map(params["optInImageUrls"], (e: string) => (e)); + if (params["optInType"] !== undefined) + data["OptInType"] = params["optInType"]; + if (params["messageVolume"] !== undefined) + data["MessageVolume"] = params["messageVolume"]; + if (params["businessStreetAddress"] !== undefined) + data["BusinessStreetAddress"] = params["businessStreetAddress"]; + if (params["businessStreetAddress2"] !== undefined) + data["BusinessStreetAddress2"] = params["businessStreetAddress2"]; + if (params["businessCity"] !== undefined) + data["BusinessCity"] = params["businessCity"]; + if (params["businessStateProvinceRegion"] !== undefined) + data["BusinessStateProvinceRegion"] = params["businessStateProvinceRegion"]; + if (params["businessPostalCode"] !== undefined) + data["BusinessPostalCode"] = params["businessPostalCode"]; + if (params["businessCountry"] !== undefined) + data["BusinessCountry"] = params["businessCountry"]; + if (params["additionalInformation"] !== undefined) + data["AdditionalInformation"] = params["additionalInformation"]; + if (params["businessContactFirstName"] !== undefined) + data["BusinessContactFirstName"] = params["businessContactFirstName"]; + if (params["businessContactLastName"] !== undefined) + data["BusinessContactLastName"] = params["businessContactLastName"]; + if (params["businessContactEmail"] !== undefined) + data["BusinessContactEmail"] = params["businessContactEmail"]; + if (params["businessContactPhone"] !== undefined) + data["BusinessContactPhone"] = params["businessContactPhone"]; + if (params["themeSetId"] !== undefined) + data["ThemeSetId"] = params["themeSetId"]; + if (params["skipMessagingUseCase"] !== undefined) + data["SkipMessagingUseCase"] = serialize.bool(params["skipMessagingUseCase"]); + if (params["businessRegistrationNumber"] !== undefined) + data["BusinessRegistrationNumber"] = params["businessRegistrationNumber"]; + if (params["businessRegistrationAuthority"] !== undefined) + data["BusinessRegistrationAuthority"] = params["businessRegistrationAuthority"]; + if (params["businessRegistrationCountry"] !== undefined) + data["BusinessRegistrationCountry"] = params["businessRegistrationCountry"]; + if (params["businessType"] !== undefined) + data["BusinessType"] = params["businessType"]; + if (params["doingBusinessAs"] !== undefined) + data["DoingBusinessAs"] = params["doingBusinessAs"]; + if (params["optInConfirmationMessage"] !== undefined) + data["OptInConfirmationMessage"] = params["optInConfirmationMessage"]; + if (params["helpMessageSample"] !== undefined) + data["HelpMessageSample"] = params["helpMessageSample"]; + if (params["privacyPolicyUrl"] !== undefined) + data["PrivacyPolicyUrl"] = params["privacyPolicyUrl"]; + if (params["termsAndConditionsUrl"] !== undefined) + data["TermsAndConditionsUrl"] = params["termsAndConditionsUrl"]; + if (params["ageGatedContent"] !== undefined) + data["AgeGatedContent"] = serialize.bool(params["ageGatedContent"]); + if (params["externalReferenceId"] !== undefined) + data["ExternalReferenceId"] = params["externalReferenceId"]; + if (params["optInKeywords"] !== undefined) + data["OptInKeywords"] = serialize.map(params["optInKeywords"], (e: string) => (e)); + if (params["vettingId"] !== undefined) + data["VettingId"] = params["vettingId"]; + if (params["vettingProvider"] !== undefined) + data["VettingProvider"] = params["vettingProvider"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ComplianceTollfreeInquiriesResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ComplianceTollfreeInquiriesInstance> => ({ + ...response, + body: new ComplianceTollfreeInquiriesInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ComplianceTollfreeInquiriesPayload extends ComplianceTollfreeInquiriesResource {} + +interface ComplianceTollfreeInquiriesResource { + inquiry_id: string; + inquiry_session_token: string; + registration_id: string; + url: string; +} + +export class ComplianceTollfreeInquiriesInstance { + + constructor(protected _version: V1, payload: ComplianceTollfreeInquiriesResource) { + + this.inquiryId = (payload.inquiry_id); + this.inquirySessionToken = (payload.inquiry_session_token); + this.registrationId = (payload.registration_id); + this.url = (payload.url); + + } + + /** + * The unique ID used to start an embedded compliance registration session. + */ + inquiryId: string; + /** + * The session token used to start an embedded compliance registration session. + */ + inquirySessionToken: string; + /** + * The TolfreeId matching the Tollfree Profile that should be resumed or resubmitted for editing. + */ + registrationId: string; + /** + * The URL of this resource. + */ + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + inquiryId: this.inquiryId, + inquirySessionToken: this.inquirySessionToken, + registrationId: this.registrationId, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/trusthub/v1/customerProfiles.ts b/rest/trusthub/v1/customerProfiles.ts new file mode 100644 index 000000000..f807d23e0 --- /dev/null +++ b/rest/trusthub/v1/customerProfiles.ts @@ -0,0 +1,1067 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { CustomerProfilesChannelEndpointAssignmentListInstance } from "./customerProfiles/customerProfilesChannelEndpointAssignment"; +import { CustomerProfilesEntityAssignmentsListInstance } from "./customerProfiles/customerProfilesEntityAssignments"; +import { CustomerProfilesEvaluationsListInstance } from "./customerProfiles/customerProfilesEvaluations"; + + +/** + * The verification status of the Customer-Profile resource. + */ +export type CustomerProfilesStatus = 'draft'|'pending-review'|'in-review'|'twilio-rejected'|'twilio-approved'; + + + + +/** + * Options to pass to update a CustomerProfilesInstance + */ +export interface CustomerProfilesContextUpdateOptions { + /** */ + "status"?: CustomerProfilesStatus; + /** The URL we call to inform your application of status changes. */ + "statusCallback"?: string; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The email address that will receive updates when the Customer-Profile resource changes status. */ + "email"?: string; +} + +/** + * Options to pass to create a CustomerProfilesInstance + */ +export interface CustomerProfilesListInstanceCreateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName": string; + /** The email address that will receive updates when the Customer-Profile resource changes status. */ + "email": string; + /** The unique string of a policy that is associated to the Customer-Profile resource. */ + "policySid": string; + /** The URL we call to inform your application of status changes. */ + "statusCallback"?: string; +} + +/** + * Options to pass to each + */ +export interface CustomerProfilesListInstanceEachOptions { + /** The verification status of the Customer-Profile resource. */ + "status"?: CustomerProfilesStatus; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The unique string of a policy that is associated to the Customer-Profile resource. */ + "policySid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CustomerProfilesInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CustomerProfilesListInstanceOptions { + /** The verification status of the Customer-Profile resource. */ + "status"?: CustomerProfilesStatus; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The unique string of a policy that is associated to the Customer-Profile resource. */ + "policySid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CustomerProfilesListInstancePageOptions { + /** The verification status of the Customer-Profile resource. */ + "status"?: CustomerProfilesStatus; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The unique string of a policy that is associated to the Customer-Profile resource. */ + "policySid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CustomerProfilesContext { + customerProfilesChannelEndpointAssignment: CustomerProfilesChannelEndpointAssignmentListInstance; + customerProfilesEntityAssignments: CustomerProfilesEntityAssignmentsListInstance; + customerProfilesEvaluations: CustomerProfilesEvaluationsListInstance; + + /** + * Remove a CustomerProfilesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a CustomerProfilesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a CustomerProfilesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance + */ + fetch(callback?: (error: Error | null, item?: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance> + + /** + * Fetch a CustomerProfilesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>> + + /** + * Update a CustomerProfilesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance + */ + update(callback?: (error: Error | null, item?: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance>; + /** + * Update a CustomerProfilesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance + */ + update(params: CustomerProfilesContextUpdateOptions, callback?: (error: Error | null, item?: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance>; + + /** + * Update a CustomerProfilesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>>; + /** + * Update a CustomerProfilesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance with HTTP metadata + */ + updateWithHttpInfo(params: CustomerProfilesContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CustomerProfilesContextSolution { + "sid": string; +} + +export class CustomerProfilesContextImpl implements CustomerProfilesContext { + protected _solution: CustomerProfilesContextSolution; + protected _uri: string; + + protected _customerProfilesChannelEndpointAssignment?: CustomerProfilesChannelEndpointAssignmentListInstance; + protected _customerProfilesEntityAssignments?: CustomerProfilesEntityAssignmentsListInstance; + protected _customerProfilesEvaluations?: CustomerProfilesEvaluationsListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/CustomerProfiles/${sid}`; + } + + get customerProfilesChannelEndpointAssignment(): CustomerProfilesChannelEndpointAssignmentListInstance { + this._customerProfilesChannelEndpointAssignment = this._customerProfilesChannelEndpointAssignment || CustomerProfilesChannelEndpointAssignmentListInstance(this._version, this._solution.sid); + return this._customerProfilesChannelEndpointAssignment; + } + + get customerProfilesEntityAssignments(): CustomerProfilesEntityAssignmentsListInstance { + this._customerProfilesEntityAssignments = this._customerProfilesEntityAssignments || CustomerProfilesEntityAssignmentsListInstance(this._version, this._solution.sid); + return this._customerProfilesEntityAssignments; + } + + get customerProfilesEvaluations(): CustomerProfilesEvaluationsListInstance { + this._customerProfilesEvaluations = this._customerProfilesEvaluations || CustomerProfilesEvaluationsListInstance(this._version, this._solution.sid); + return this._customerProfilesEvaluations; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CustomerProfilesResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CustomerProfilesInstance> => ({ + ...response, + body: new CustomerProfilesInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: CustomerProfilesContextUpdateOptions | ((error: Error | null, item?: CustomerProfilesInstance) => any),callback?: (error: Error | null, item?: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: CustomerProfilesContextUpdateOptions | ((error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<CustomerProfilesResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CustomerProfilesInstance> => ({ + ...response, + body: new CustomerProfilesInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CustomerProfilesPayload extends TwilioResponsePayload { + results: CustomerProfilesResource[]; +} + +interface CustomerProfilesResource { + sid: string; + account_sid: string; + policy_sid: string; + friendly_name: string; + status: CustomerProfilesStatus; + valid_until: Date; + email: string; + status_callback: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; + errors: Array<any>; +} + +export class CustomerProfilesInstance { + protected _solution: CustomerProfilesContextSolution; + protected _context?: CustomerProfilesContext; + + constructor(protected _version: V1, payload: CustomerProfilesResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.policySid = (payload.policy_sid); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.validUntil = deserialize.iso8601DateTime(payload.valid_until); + this.email = (payload.email); + this.statusCallback = (payload.status_callback); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + this.errors = (payload.errors); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Customer-Profile resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Customer-Profile resource. + */ + accountSid: string; + /** + * The unique string of a policy that is associated to the Customer-Profile resource. + */ + policySid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + status: CustomerProfilesStatus; + /** + * The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + */ + validUntil: Date; + /** + * The email address that will receive updates when the Customer-Profile resource changes status. + */ + email: string; + /** + * The URL we call to inform your application of status changes. + */ + statusCallback: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Customer-Profile resource. + */ + url: string; + /** + * The URLs of the Assigned Items of the Customer-Profile resource. + */ + links: Record<string, string>; + /** + * The error codes associated with the rejection of the Customer-Profile. + */ + errors: Array<any>; + + private get _proxy(): CustomerProfilesContext { + this._context = this._context || new CustomerProfilesContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CustomerProfilesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CustomerProfilesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CustomerProfilesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance + */ + fetch(callback?: (error: Error | null, item?: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CustomerProfilesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CustomerProfilesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance + */ + update(callback?: (error: Error | null, item?: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance>; + /** + * Update a CustomerProfilesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance + */ + update(params: CustomerProfilesContextUpdateOptions, callback?: (error: Error | null, item?: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance>; + + update(params?: any, callback?: (error: Error | null, item?: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a CustomerProfilesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>>; + /** + * Update a CustomerProfilesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance with HTTP metadata + */ + updateWithHttpInfo(params: CustomerProfilesContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the customerProfilesChannelEndpointAssignment. + */ + customerProfilesChannelEndpointAssignment(): CustomerProfilesChannelEndpointAssignmentListInstance { + return this._proxy.customerProfilesChannelEndpointAssignment; + } + + /** + * Access the customerProfilesEntityAssignments. + */ + customerProfilesEntityAssignments(): CustomerProfilesEntityAssignmentsListInstance { + return this._proxy.customerProfilesEntityAssignments; + } + + /** + * Access the customerProfilesEvaluations. + */ + customerProfilesEvaluations(): CustomerProfilesEvaluationsListInstance { + return this._proxy.customerProfilesEvaluations; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + policySid: this.policySid, + friendlyName: this.friendlyName, + status: this.status, + validUntil: this.validUntil, + email: this.email, + statusCallback: this.statusCallback, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + errors: this.errors, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CustomerProfilesSolution { +} + +export interface CustomerProfilesListInstance { + _version: V1; + _solution: CustomerProfilesSolution; + _uri: string; + + (sid: string, ): CustomerProfilesContext; + get(sid: string, ): CustomerProfilesContext; + + + + + + + + + /** + * Create a CustomerProfilesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance + */ + create(params: CustomerProfilesListInstanceCreateOptions, callback?: (error: Error | null, item?: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance>; + + /** + * Create a CustomerProfilesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesInstance with HTTP metadata + */ + createWithHttpInfo(params: CustomerProfilesListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>>; + + + + + /** + * Streams CustomerProfilesInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CustomerProfilesInstance, done: (err?: Error) => void) => void): void; + each(params: CustomerProfilesListInstanceEachOptions, callback?: (item: CustomerProfilesInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CustomerProfilesInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CustomerProfilesInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CustomerProfilesListInstanceEachOptions, callback?: (item: CustomerProfilesInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CustomerProfilesInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CustomerProfilesPage) => any): Promise<CustomerProfilesPage>; + /** + * Retrieve a single target page of CustomerProfilesInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesPage>) => any): Promise<ApiResponse<CustomerProfilesPage>>; + /** + * Lists CustomerProfilesInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CustomerProfilesInstance[]) => any): Promise<CustomerProfilesInstance[]>; + list(params: CustomerProfilesListInstanceOptions, callback?: (error: Error | null, items: CustomerProfilesInstance[]) => any): Promise<CustomerProfilesInstance[]>; + /** + * Lists CustomerProfilesInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CustomerProfilesInstance[]>) => any): Promise<ApiResponse<CustomerProfilesInstance[]>>; + listWithHttpInfo(params: CustomerProfilesListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesInstance[]>) => any): Promise<ApiResponse<CustomerProfilesInstance[]>>; + /** + * Retrieve a single page of CustomerProfilesInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CustomerProfilesPage) => any): Promise<CustomerProfilesPage>; + page(params: CustomerProfilesListInstancePageOptions, callback?: (error: Error | null, items: CustomerProfilesPage) => any): Promise<CustomerProfilesPage>; + /** + * Retrieve a single page of CustomerProfilesInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CustomerProfilesPage>) => any): Promise<ApiResponse<CustomerProfilesPage>>; + pageWithHttpInfo(params: CustomerProfilesListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesPage>) => any): Promise<ApiResponse<CustomerProfilesPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CustomerProfilesListInstance(version: V1): CustomerProfilesListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CustomerProfilesListInstance; + + instance.get = function get(sid, ): CustomerProfilesContext { + return new CustomerProfilesContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/CustomerProfiles`; + + instance.create = function create(params: CustomerProfilesListInstanceCreateOptions, callback?: (error: Error | null, items: CustomerProfilesInstance) => any): Promise<CustomerProfilesInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + if (params["policySid"] === null || params["policySid"] === undefined) { + throw new Error('Required parameter "params[\'policySid\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Email"] = params["email"]; + + data["PolicySid"] = params["policySid"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CustomerProfilesListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesInstance>) => any): Promise<ApiResponse<CustomerProfilesInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + if (params["policySid"] === null || params["policySid"] === undefined) { + throw new Error('Required parameter "params[\'policySid\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Email"] = params["email"]; + + data["PolicySid"] = params["policySid"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CustomerProfilesResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CustomerProfilesInstance> => ({ + ...response, + body: new CustomerProfilesInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CustomerProfilesListInstancePageOptions | ((error: Error | null, items: CustomerProfilesPage) => any), callback?: (error: Error | null, items: CustomerProfilesPage) => any): Promise<CustomerProfilesPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["policySid"] !== undefined) + data["PolicySid"] = params["policySid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CustomerProfilesPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CustomerProfilesPage) => any): Promise<CustomerProfilesPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CustomerProfilesPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CustomerProfilesListInstancePageOptions | ((error: Error | null, items: ApiResponse<CustomerProfilesPage>) => any), callback?: (error: Error | null, items: ApiResponse<CustomerProfilesPage>) => any): Promise<ApiResponse<CustomerProfilesPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["policySid"] !== undefined) + data["PolicySid"] = params["policySid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CustomerProfilesPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CustomerProfilesPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CustomerProfilesPage>) => any): Promise<ApiResponse<CustomerProfilesPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CustomerProfilesPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CustomerProfilesPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CustomerProfilesPage extends Page<V1, CustomerProfilesPayload, CustomerProfilesResource, CustomerProfilesInstance> { +/** +* Initialize the CustomerProfilesPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CustomerProfilesSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CustomerProfilesInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CustomerProfilesResource): CustomerProfilesInstance { + + return new CustomerProfilesInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/customerProfiles/customerProfilesChannelEndpointAssignment.ts b/rest/trusthub/v1/customerProfiles/customerProfilesChannelEndpointAssignment.ts new file mode 100644 index 000000000..9531b597d --- /dev/null +++ b/rest/trusthub/v1/customerProfiles/customerProfilesChannelEndpointAssignment.ts @@ -0,0 +1,780 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a CustomerProfilesChannelEndpointAssignmentInstance + */ +export interface CustomerProfilesChannelEndpointAssignmentListInstanceCreateOptions { + /** The type of channel endpoint. eg: phone-number */ + "channelEndpointType": string; + /** The SID of an channel endpoint */ + "channelEndpointSid": string; +} + +/** + * Options to pass to each + */ +export interface CustomerProfilesChannelEndpointAssignmentListInstanceEachOptions { + /** The SID of an channel endpoint */ + "channelEndpointSid"?: string; + /** comma separated list of channel endpoint sids */ + "channelEndpointSids"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CustomerProfilesChannelEndpointAssignmentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CustomerProfilesChannelEndpointAssignmentListInstanceOptions { + /** The SID of an channel endpoint */ + "channelEndpointSid"?: string; + /** comma separated list of channel endpoint sids */ + "channelEndpointSids"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CustomerProfilesChannelEndpointAssignmentListInstancePageOptions { + /** The SID of an channel endpoint */ + "channelEndpointSid"?: string; + /** comma separated list of channel endpoint sids */ + "channelEndpointSids"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CustomerProfilesChannelEndpointAssignmentContext { + + /** + * Remove a CustomerProfilesChannelEndpointAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a CustomerProfilesChannelEndpointAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a CustomerProfilesChannelEndpointAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesChannelEndpointAssignmentInstance + */ + fetch(callback?: (error: Error | null, item?: CustomerProfilesChannelEndpointAssignmentInstance) => any): Promise<CustomerProfilesChannelEndpointAssignmentInstance> + + /** + * Fetch a CustomerProfilesChannelEndpointAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesChannelEndpointAssignmentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CustomerProfilesChannelEndpointAssignmentContextSolution { + "customerProfileSid": string; + "sid": string; +} + +export class CustomerProfilesChannelEndpointAssignmentContextImpl implements CustomerProfilesChannelEndpointAssignmentContext { + protected _solution: CustomerProfilesChannelEndpointAssignmentContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, customerProfileSid: string, sid: string) { + if (!isValidPathParam(customerProfileSid)) { + throw new Error('Parameter \'customerProfileSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { customerProfileSid, sid, }; + this._uri = `/CustomerProfiles/${customerProfileSid}/ChannelEndpointAssignments/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CustomerProfilesChannelEndpointAssignmentInstance) => any): Promise<CustomerProfilesChannelEndpointAssignmentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesChannelEndpointAssignmentInstance(operationVersion, payload, instance._solution.customerProfileSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CustomerProfilesChannelEndpointAssignmentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance> => ({ + ...response, + body: new CustomerProfilesChannelEndpointAssignmentInstance(operationVersion, response.body, instance._solution.customerProfileSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CustomerProfilesChannelEndpointAssignmentPayload extends TwilioResponsePayload { + results: CustomerProfilesChannelEndpointAssignmentResource[]; +} + +interface CustomerProfilesChannelEndpointAssignmentResource { + sid: string; + customer_profile_sid: string; + account_sid: string; + channel_endpoint_type: string; + channel_endpoint_sid: string; + date_created: Date; + url: string; +} + +export class CustomerProfilesChannelEndpointAssignmentInstance { + protected _solution: CustomerProfilesChannelEndpointAssignmentContextSolution; + protected _context?: CustomerProfilesChannelEndpointAssignmentContext; + + constructor(protected _version: V1, payload: CustomerProfilesChannelEndpointAssignmentResource, customerProfileSid: string, sid?: string) { + + this.sid = (payload.sid); + this.customerProfileSid = (payload.customer_profile_sid); + this.accountSid = (payload.account_sid); + this.channelEndpointType = (payload.channel_endpoint_type); + this.channelEndpointSid = (payload.channel_endpoint_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { customerProfileSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Item Assignment resource. + */ + sid: string; + /** + * The unique string that we created to identify the CustomerProfile resource. + */ + customerProfileSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + */ + accountSid: string; + /** + * The type of channel endpoint. eg: phone-number + */ + channelEndpointType: string; + /** + * The SID of an channel endpoint + */ + channelEndpointSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Identity resource. + */ + url: string; + + private get _proxy(): CustomerProfilesChannelEndpointAssignmentContext { + this._context = this._context || new CustomerProfilesChannelEndpointAssignmentContextImpl(this._version, this._solution.customerProfileSid, this._solution.sid); + return this._context; + } + + /** + * Remove a CustomerProfilesChannelEndpointAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CustomerProfilesChannelEndpointAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CustomerProfilesChannelEndpointAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesChannelEndpointAssignmentInstance + */ + fetch(callback?: (error: Error | null, item?: CustomerProfilesChannelEndpointAssignmentInstance) => any): Promise<CustomerProfilesChannelEndpointAssignmentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CustomerProfilesChannelEndpointAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesChannelEndpointAssignmentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + customerProfileSid: this.customerProfileSid, + accountSid: this.accountSid, + channelEndpointType: this.channelEndpointType, + channelEndpointSid: this.channelEndpointSid, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CustomerProfilesChannelEndpointAssignmentSolution { + customerProfileSid: string; +} + +export interface CustomerProfilesChannelEndpointAssignmentListInstance { + _version: V1; + _solution: CustomerProfilesChannelEndpointAssignmentSolution; + _uri: string; + + (sid: string, ): CustomerProfilesChannelEndpointAssignmentContext; + get(sid: string, ): CustomerProfilesChannelEndpointAssignmentContext; + + + + + + + /** + * Create a CustomerProfilesChannelEndpointAssignmentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesChannelEndpointAssignmentInstance + */ + create(params: CustomerProfilesChannelEndpointAssignmentListInstanceCreateOptions, callback?: (error: Error | null, item?: CustomerProfilesChannelEndpointAssignmentInstance) => any): Promise<CustomerProfilesChannelEndpointAssignmentInstance>; + + /** + * Create a CustomerProfilesChannelEndpointAssignmentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesChannelEndpointAssignmentInstance with HTTP metadata + */ + createWithHttpInfo(params: CustomerProfilesChannelEndpointAssignmentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance>>; + + + + + /** + * Streams CustomerProfilesChannelEndpointAssignmentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesChannelEndpointAssignmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CustomerProfilesChannelEndpointAssignmentInstance, done: (err?: Error) => void) => void): void; + each(params: CustomerProfilesChannelEndpointAssignmentListInstanceEachOptions, callback?: (item: CustomerProfilesChannelEndpointAssignmentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CustomerProfilesChannelEndpointAssignmentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesChannelEndpointAssignmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CustomerProfilesChannelEndpointAssignmentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CustomerProfilesChannelEndpointAssignmentListInstanceEachOptions, callback?: (item: CustomerProfilesChannelEndpointAssignmentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CustomerProfilesChannelEndpointAssignmentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CustomerProfilesChannelEndpointAssignmentPage) => any): Promise<CustomerProfilesChannelEndpointAssignmentPage>; + /** + * Retrieve a single target page of CustomerProfilesChannelEndpointAssignmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>>; + /** + * Lists CustomerProfilesChannelEndpointAssignmentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesChannelEndpointAssignmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CustomerProfilesChannelEndpointAssignmentInstance[]) => any): Promise<CustomerProfilesChannelEndpointAssignmentInstance[]>; + list(params: CustomerProfilesChannelEndpointAssignmentListInstanceOptions, callback?: (error: Error | null, items: CustomerProfilesChannelEndpointAssignmentInstance[]) => any): Promise<CustomerProfilesChannelEndpointAssignmentInstance[]>; + /** + * Lists CustomerProfilesChannelEndpointAssignmentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesChannelEndpointAssignmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance[]>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance[]>>; + listWithHttpInfo(params: CustomerProfilesChannelEndpointAssignmentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance[]>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance[]>>; + /** + * Retrieve a single page of CustomerProfilesChannelEndpointAssignmentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesChannelEndpointAssignmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CustomerProfilesChannelEndpointAssignmentPage) => any): Promise<CustomerProfilesChannelEndpointAssignmentPage>; + page(params: CustomerProfilesChannelEndpointAssignmentListInstancePageOptions, callback?: (error: Error | null, items: CustomerProfilesChannelEndpointAssignmentPage) => any): Promise<CustomerProfilesChannelEndpointAssignmentPage>; + /** + * Retrieve a single page of CustomerProfilesChannelEndpointAssignmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesChannelEndpointAssignmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>>; + pageWithHttpInfo(params: CustomerProfilesChannelEndpointAssignmentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CustomerProfilesChannelEndpointAssignmentListInstance(version: V1, customerProfileSid: string): CustomerProfilesChannelEndpointAssignmentListInstance { + if (!isValidPathParam(customerProfileSid)) { + throw new Error('Parameter \'customerProfileSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as CustomerProfilesChannelEndpointAssignmentListInstance; + + instance.get = function get(sid, ): CustomerProfilesChannelEndpointAssignmentContext { + return new CustomerProfilesChannelEndpointAssignmentContextImpl(version, customerProfileSid, sid); + } + + instance._version = version; + instance._solution = { customerProfileSid, }; + instance._uri = `/CustomerProfiles/${customerProfileSid}/ChannelEndpointAssignments`; + + instance.create = function create(params: CustomerProfilesChannelEndpointAssignmentListInstanceCreateOptions, callback?: (error: Error | null, items: CustomerProfilesChannelEndpointAssignmentInstance) => any): Promise<CustomerProfilesChannelEndpointAssignmentInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["channelEndpointType"] === null || params["channelEndpointType"] === undefined) { + throw new Error('Required parameter "params[\'channelEndpointType\']" missing.'); + } + + if (params["channelEndpointSid"] === null || params["channelEndpointSid"] === undefined) { + throw new Error('Required parameter "params[\'channelEndpointSid\']" missing.'); + } + + let data: any = {}; + + + + data["ChannelEndpointType"] = params["channelEndpointType"]; + + data["ChannelEndpointSid"] = params["channelEndpointSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesChannelEndpointAssignmentInstance(operationVersion, payload, instance._solution.customerProfileSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CustomerProfilesChannelEndpointAssignmentListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["channelEndpointType"] === null || params["channelEndpointType"] === undefined) { + throw new Error('Required parameter "params[\'channelEndpointType\']" missing.'); + } + + if (params["channelEndpointSid"] === null || params["channelEndpointSid"] === undefined) { + throw new Error('Required parameter "params[\'channelEndpointSid\']" missing.'); + } + + let data: any = {}; + + + + data["ChannelEndpointType"] = params["channelEndpointType"]; + + data["ChannelEndpointSid"] = params["channelEndpointSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CustomerProfilesChannelEndpointAssignmentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CustomerProfilesChannelEndpointAssignmentInstance> => ({ + ...response, + body: new CustomerProfilesChannelEndpointAssignmentInstance(operationVersion, response.body, instance._solution.customerProfileSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CustomerProfilesChannelEndpointAssignmentListInstancePageOptions | ((error: Error | null, items: CustomerProfilesChannelEndpointAssignmentPage) => any), callback?: (error: Error | null, items: CustomerProfilesChannelEndpointAssignmentPage) => any): Promise<CustomerProfilesChannelEndpointAssignmentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["channelEndpointSid"] !== undefined) + data["ChannelEndpointSid"] = params["channelEndpointSid"]; + if (params["channelEndpointSids"] !== undefined) + data["ChannelEndpointSids"] = params["channelEndpointSids"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CustomerProfilesChannelEndpointAssignmentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CustomerProfilesChannelEndpointAssignmentPage) => any): Promise<CustomerProfilesChannelEndpointAssignmentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CustomerProfilesChannelEndpointAssignmentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CustomerProfilesChannelEndpointAssignmentListInstancePageOptions | ((error: Error | null, items: ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>) => any), callback?: (error: Error | null, items: ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["channelEndpointSid"] !== undefined) + data["ChannelEndpointSid"] = params["channelEndpointSid"]; + if (params["channelEndpointSids"] !== undefined) + data["ChannelEndpointSids"] = params["channelEndpointSids"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CustomerProfilesChannelEndpointAssignmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CustomerProfilesChannelEndpointAssignmentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>) => any): Promise<ApiResponse<CustomerProfilesChannelEndpointAssignmentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CustomerProfilesChannelEndpointAssignmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CustomerProfilesChannelEndpointAssignmentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CustomerProfilesChannelEndpointAssignmentPage extends Page<V1, CustomerProfilesChannelEndpointAssignmentPayload, CustomerProfilesChannelEndpointAssignmentResource, CustomerProfilesChannelEndpointAssignmentInstance> { +/** +* Initialize the CustomerProfilesChannelEndpointAssignmentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CustomerProfilesChannelEndpointAssignmentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CustomerProfilesChannelEndpointAssignmentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CustomerProfilesChannelEndpointAssignmentResource): CustomerProfilesChannelEndpointAssignmentInstance { + + return new CustomerProfilesChannelEndpointAssignmentInstance( + this._version, + payload, + this._solution.customerProfileSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/customerProfiles/customerProfilesEntityAssignments.ts b/rest/trusthub/v1/customerProfiles/customerProfilesEntityAssignments.ts new file mode 100644 index 000000000..be8589755 --- /dev/null +++ b/rest/trusthub/v1/customerProfiles/customerProfilesEntityAssignments.ts @@ -0,0 +1,749 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a CustomerProfilesEntityAssignmentsInstance + */ +export interface CustomerProfilesEntityAssignmentsListInstanceCreateOptions { + /** The SID of an object bag that holds information of the different items. */ + "objectSid": string; +} + +/** + * Options to pass to each + */ +export interface CustomerProfilesEntityAssignmentsListInstanceEachOptions { + /** A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. */ + "objectType"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CustomerProfilesEntityAssignmentsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CustomerProfilesEntityAssignmentsListInstanceOptions { + /** A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. */ + "objectType"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CustomerProfilesEntityAssignmentsListInstancePageOptions { + /** A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. */ + "objectType"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CustomerProfilesEntityAssignmentsContext { + + /** + * Remove a CustomerProfilesEntityAssignmentsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a CustomerProfilesEntityAssignmentsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a CustomerProfilesEntityAssignmentsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEntityAssignmentsInstance + */ + fetch(callback?: (error: Error | null, item?: CustomerProfilesEntityAssignmentsInstance) => any): Promise<CustomerProfilesEntityAssignmentsInstance> + + /** + * Fetch a CustomerProfilesEntityAssignmentsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEntityAssignmentsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesEntityAssignmentsInstance>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CustomerProfilesEntityAssignmentsContextSolution { + "customerProfileSid": string; + "sid": string; +} + +export class CustomerProfilesEntityAssignmentsContextImpl implements CustomerProfilesEntityAssignmentsContext { + protected _solution: CustomerProfilesEntityAssignmentsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, customerProfileSid: string, sid: string) { + if (!isValidPathParam(customerProfileSid)) { + throw new Error('Parameter \'customerProfileSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { customerProfileSid, sid, }; + this._uri = `/CustomerProfiles/${customerProfileSid}/EntityAssignments/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CustomerProfilesEntityAssignmentsInstance) => any): Promise<CustomerProfilesEntityAssignmentsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesEntityAssignmentsInstance(operationVersion, payload, instance._solution.customerProfileSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesEntityAssignmentsInstance>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CustomerProfilesEntityAssignmentsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CustomerProfilesEntityAssignmentsInstance> => ({ + ...response, + body: new CustomerProfilesEntityAssignmentsInstance(operationVersion, response.body, instance._solution.customerProfileSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CustomerProfilesEntityAssignmentsPayload extends TwilioResponsePayload { + results: CustomerProfilesEntityAssignmentsResource[]; +} + +interface CustomerProfilesEntityAssignmentsResource { + sid: string; + customer_profile_sid: string; + account_sid: string; + object_sid: string; + date_created: Date; + url: string; +} + +export class CustomerProfilesEntityAssignmentsInstance { + protected _solution: CustomerProfilesEntityAssignmentsContextSolution; + protected _context?: CustomerProfilesEntityAssignmentsContext; + + constructor(protected _version: V1, payload: CustomerProfilesEntityAssignmentsResource, customerProfileSid: string, sid?: string) { + + this.sid = (payload.sid); + this.customerProfileSid = (payload.customer_profile_sid); + this.accountSid = (payload.account_sid); + this.objectSid = (payload.object_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { customerProfileSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Item Assignment resource. + */ + sid: string; + /** + * The unique string that we created to identify the CustomerProfile resource. + */ + customerProfileSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + */ + accountSid: string; + /** + * The SID of an object bag that holds information of the different items. + */ + objectSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Identity resource. + */ + url: string; + + private get _proxy(): CustomerProfilesEntityAssignmentsContext { + this._context = this._context || new CustomerProfilesEntityAssignmentsContextImpl(this._version, this._solution.customerProfileSid, this._solution.sid); + return this._context; + } + + /** + * Remove a CustomerProfilesEntityAssignmentsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CustomerProfilesEntityAssignmentsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CustomerProfilesEntityAssignmentsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEntityAssignmentsInstance + */ + fetch(callback?: (error: Error | null, item?: CustomerProfilesEntityAssignmentsInstance) => any): Promise<CustomerProfilesEntityAssignmentsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CustomerProfilesEntityAssignmentsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEntityAssignmentsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesEntityAssignmentsInstance>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + customerProfileSid: this.customerProfileSid, + accountSid: this.accountSid, + objectSid: this.objectSid, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CustomerProfilesEntityAssignmentsSolution { + customerProfileSid: string; +} + +export interface CustomerProfilesEntityAssignmentsListInstance { + _version: V1; + _solution: CustomerProfilesEntityAssignmentsSolution; + _uri: string; + + (sid: string, ): CustomerProfilesEntityAssignmentsContext; + get(sid: string, ): CustomerProfilesEntityAssignmentsContext; + + + + + + + /** + * Create a CustomerProfilesEntityAssignmentsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEntityAssignmentsInstance + */ + create(params: CustomerProfilesEntityAssignmentsListInstanceCreateOptions, callback?: (error: Error | null, item?: CustomerProfilesEntityAssignmentsInstance) => any): Promise<CustomerProfilesEntityAssignmentsInstance>; + + /** + * Create a CustomerProfilesEntityAssignmentsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEntityAssignmentsInstance with HTTP metadata + */ + createWithHttpInfo(params: CustomerProfilesEntityAssignmentsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesEntityAssignmentsInstance>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsInstance>>; + + + + + /** + * Streams CustomerProfilesEntityAssignmentsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEntityAssignmentsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CustomerProfilesEntityAssignmentsInstance, done: (err?: Error) => void) => void): void; + each(params: CustomerProfilesEntityAssignmentsListInstanceEachOptions, callback?: (item: CustomerProfilesEntityAssignmentsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CustomerProfilesEntityAssignmentsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEntityAssignmentsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CustomerProfilesEntityAssignmentsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CustomerProfilesEntityAssignmentsListInstanceEachOptions, callback?: (item: CustomerProfilesEntityAssignmentsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CustomerProfilesEntityAssignmentsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CustomerProfilesEntityAssignmentsPage) => any): Promise<CustomerProfilesEntityAssignmentsPage>; + /** + * Retrieve a single target page of CustomerProfilesEntityAssignmentsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEntityAssignmentsPage>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsPage>>; + /** + * Lists CustomerProfilesEntityAssignmentsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEntityAssignmentsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CustomerProfilesEntityAssignmentsInstance[]) => any): Promise<CustomerProfilesEntityAssignmentsInstance[]>; + list(params: CustomerProfilesEntityAssignmentsListInstanceOptions, callback?: (error: Error | null, items: CustomerProfilesEntityAssignmentsInstance[]) => any): Promise<CustomerProfilesEntityAssignmentsInstance[]>; + /** + * Lists CustomerProfilesEntityAssignmentsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEntityAssignmentsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEntityAssignmentsInstance[]>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsInstance[]>>; + listWithHttpInfo(params: CustomerProfilesEntityAssignmentsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEntityAssignmentsInstance[]>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsInstance[]>>; + /** + * Retrieve a single page of CustomerProfilesEntityAssignmentsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEntityAssignmentsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CustomerProfilesEntityAssignmentsPage) => any): Promise<CustomerProfilesEntityAssignmentsPage>; + page(params: CustomerProfilesEntityAssignmentsListInstancePageOptions, callback?: (error: Error | null, items: CustomerProfilesEntityAssignmentsPage) => any): Promise<CustomerProfilesEntityAssignmentsPage>; + /** + * Retrieve a single page of CustomerProfilesEntityAssignmentsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEntityAssignmentsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEntityAssignmentsPage>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsPage>>; + pageWithHttpInfo(params: CustomerProfilesEntityAssignmentsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEntityAssignmentsPage>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CustomerProfilesEntityAssignmentsListInstance(version: V1, customerProfileSid: string): CustomerProfilesEntityAssignmentsListInstance { + if (!isValidPathParam(customerProfileSid)) { + throw new Error('Parameter \'customerProfileSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as CustomerProfilesEntityAssignmentsListInstance; + + instance.get = function get(sid, ): CustomerProfilesEntityAssignmentsContext { + return new CustomerProfilesEntityAssignmentsContextImpl(version, customerProfileSid, sid); + } + + instance._version = version; + instance._solution = { customerProfileSid, }; + instance._uri = `/CustomerProfiles/${customerProfileSid}/EntityAssignments`; + + instance.create = function create(params: CustomerProfilesEntityAssignmentsListInstanceCreateOptions, callback?: (error: Error | null, items: CustomerProfilesEntityAssignmentsInstance) => any): Promise<CustomerProfilesEntityAssignmentsInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["objectSid"] === null || params["objectSid"] === undefined) { + throw new Error('Required parameter "params[\'objectSid\']" missing.'); + } + + let data: any = {}; + + + + data["ObjectSid"] = params["objectSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesEntityAssignmentsInstance(operationVersion, payload, instance._solution.customerProfileSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CustomerProfilesEntityAssignmentsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEntityAssignmentsInstance>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["objectSid"] === null || params["objectSid"] === undefined) { + throw new Error('Required parameter "params[\'objectSid\']" missing.'); + } + + let data: any = {}; + + + + data["ObjectSid"] = params["objectSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CustomerProfilesEntityAssignmentsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CustomerProfilesEntityAssignmentsInstance> => ({ + ...response, + body: new CustomerProfilesEntityAssignmentsInstance(operationVersion, response.body, instance._solution.customerProfileSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CustomerProfilesEntityAssignmentsListInstancePageOptions | ((error: Error | null, items: CustomerProfilesEntityAssignmentsPage) => any), callback?: (error: Error | null, items: CustomerProfilesEntityAssignmentsPage) => any): Promise<CustomerProfilesEntityAssignmentsPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["objectType"] !== undefined) + data["ObjectType"] = params["objectType"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CustomerProfilesEntityAssignmentsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CustomerProfilesEntityAssignmentsPage) => any): Promise<CustomerProfilesEntityAssignmentsPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CustomerProfilesEntityAssignmentsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CustomerProfilesEntityAssignmentsListInstancePageOptions | ((error: Error | null, items: ApiResponse<CustomerProfilesEntityAssignmentsPage>) => any), callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEntityAssignmentsPage>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["objectType"] !== undefined) + data["ObjectType"] = params["objectType"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CustomerProfilesEntityAssignmentsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CustomerProfilesEntityAssignmentsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CustomerProfilesEntityAssignmentsPage>) => any): Promise<ApiResponse<CustomerProfilesEntityAssignmentsPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CustomerProfilesEntityAssignmentsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CustomerProfilesEntityAssignmentsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CustomerProfilesEntityAssignmentsPage extends Page<V1, CustomerProfilesEntityAssignmentsPayload, CustomerProfilesEntityAssignmentsResource, CustomerProfilesEntityAssignmentsInstance> { +/** +* Initialize the CustomerProfilesEntityAssignmentsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CustomerProfilesEntityAssignmentsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CustomerProfilesEntityAssignmentsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CustomerProfilesEntityAssignmentsResource): CustomerProfilesEntityAssignmentsInstance { + + return new CustomerProfilesEntityAssignmentsInstance( + this._version, + payload, + this._solution.customerProfileSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/customerProfiles/customerProfilesEvaluations.ts b/rest/trusthub/v1/customerProfiles/customerProfilesEvaluations.ts new file mode 100644 index 000000000..0f6d7081a --- /dev/null +++ b/rest/trusthub/v1/customerProfiles/customerProfilesEvaluations.ts @@ -0,0 +1,671 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The compliance status of the Evaluation resource. + */ +export type CustomerProfilesEvaluationsStatus = 'compliant'|'noncompliant'; + + + +/** + * Options to pass to create a CustomerProfilesEvaluationsInstance + */ +export interface CustomerProfilesEvaluationsListInstanceCreateOptions { + /** The unique string of a policy that is associated to the customer_profile resource. */ + "policySid": string; +} + +/** + * Options to pass to each + */ +export interface CustomerProfilesEvaluationsListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CustomerProfilesEvaluationsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CustomerProfilesEvaluationsListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CustomerProfilesEvaluationsListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CustomerProfilesEvaluationsContext { + + /** + * Fetch a CustomerProfilesEvaluationsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEvaluationsInstance + */ + fetch(callback?: (error: Error | null, item?: CustomerProfilesEvaluationsInstance) => any): Promise<CustomerProfilesEvaluationsInstance> + + /** + * Fetch a CustomerProfilesEvaluationsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEvaluationsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesEvaluationsInstance>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CustomerProfilesEvaluationsContextSolution { + "customerProfileSid": string; + "sid": string; +} + +export class CustomerProfilesEvaluationsContextImpl implements CustomerProfilesEvaluationsContext { + protected _solution: CustomerProfilesEvaluationsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, customerProfileSid: string, sid: string) { + if (!isValidPathParam(customerProfileSid)) { + throw new Error('Parameter \'customerProfileSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { customerProfileSid, sid, }; + this._uri = `/CustomerProfiles/${customerProfileSid}/Evaluations/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: CustomerProfilesEvaluationsInstance) => any): Promise<CustomerProfilesEvaluationsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesEvaluationsInstance(operationVersion, payload, instance._solution.customerProfileSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesEvaluationsInstance>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CustomerProfilesEvaluationsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CustomerProfilesEvaluationsInstance> => ({ + ...response, + body: new CustomerProfilesEvaluationsInstance(operationVersion, response.body, instance._solution.customerProfileSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CustomerProfilesEvaluationsPayload extends TwilioResponsePayload { + results: CustomerProfilesEvaluationsResource[]; +} + +interface CustomerProfilesEvaluationsResource { + sid: string; + account_sid: string; + policy_sid: string; + customer_profile_sid: string; + status: CustomerProfilesEvaluationsStatus; + results: Array<any>; + date_created: Date; + url: string; +} + +export class CustomerProfilesEvaluationsInstance { + protected _solution: CustomerProfilesEvaluationsContextSolution; + protected _context?: CustomerProfilesEvaluationsContext; + + constructor(protected _version: V1, payload: CustomerProfilesEvaluationsResource, customerProfileSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.policySid = (payload.policy_sid); + this.customerProfileSid = (payload.customer_profile_sid); + this.status = payload.status; + this.results = (payload.results); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { customerProfileSid, sid: sid, }; + } + + /** + * The unique string that identifies the Evaluation resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the customer_profile resource. + */ + accountSid: string; + /** + * The unique string of a policy that is associated to the customer_profile resource. + */ + policySid: string; + /** + * The unique string that we created to identify the customer_profile resource. + */ + customerProfileSid: string; + status: CustomerProfilesEvaluationsStatus; + /** + * The results of the Evaluation which includes the valid and invalid attributes. + */ + results: Array<any>; + dateCreated: Date; + url: string; + + private get _proxy(): CustomerProfilesEvaluationsContext { + this._context = this._context || new CustomerProfilesEvaluationsContextImpl(this._version, this._solution.customerProfileSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a CustomerProfilesEvaluationsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEvaluationsInstance + */ + fetch(callback?: (error: Error | null, item?: CustomerProfilesEvaluationsInstance) => any): Promise<CustomerProfilesEvaluationsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CustomerProfilesEvaluationsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEvaluationsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesEvaluationsInstance>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + policySid: this.policySid, + customerProfileSid: this.customerProfileSid, + status: this.status, + results: this.results, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CustomerProfilesEvaluationsSolution { + customerProfileSid: string; +} + +export interface CustomerProfilesEvaluationsListInstance { + _version: V1; + _solution: CustomerProfilesEvaluationsSolution; + _uri: string; + + (sid: string, ): CustomerProfilesEvaluationsContext; + get(sid: string, ): CustomerProfilesEvaluationsContext; + + + + + /** + * Create a CustomerProfilesEvaluationsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEvaluationsInstance + */ + create(params: CustomerProfilesEvaluationsListInstanceCreateOptions, callback?: (error: Error | null, item?: CustomerProfilesEvaluationsInstance) => any): Promise<CustomerProfilesEvaluationsInstance>; + + /** + * Create a CustomerProfilesEvaluationsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesEvaluationsInstance with HTTP metadata + */ + createWithHttpInfo(params: CustomerProfilesEvaluationsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesEvaluationsInstance>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsInstance>>; + + + + + /** + * Streams CustomerProfilesEvaluationsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEvaluationsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CustomerProfilesEvaluationsInstance, done: (err?: Error) => void) => void): void; + each(params: CustomerProfilesEvaluationsListInstanceEachOptions, callback?: (item: CustomerProfilesEvaluationsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CustomerProfilesEvaluationsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEvaluationsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CustomerProfilesEvaluationsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CustomerProfilesEvaluationsListInstanceEachOptions, callback?: (item: CustomerProfilesEvaluationsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CustomerProfilesEvaluationsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CustomerProfilesEvaluationsPage) => any): Promise<CustomerProfilesEvaluationsPage>; + /** + * Retrieve a single target page of CustomerProfilesEvaluationsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEvaluationsPage>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsPage>>; + /** + * Lists CustomerProfilesEvaluationsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEvaluationsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CustomerProfilesEvaluationsInstance[]) => any): Promise<CustomerProfilesEvaluationsInstance[]>; + list(params: CustomerProfilesEvaluationsListInstanceOptions, callback?: (error: Error | null, items: CustomerProfilesEvaluationsInstance[]) => any): Promise<CustomerProfilesEvaluationsInstance[]>; + /** + * Lists CustomerProfilesEvaluationsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEvaluationsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEvaluationsInstance[]>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsInstance[]>>; + listWithHttpInfo(params: CustomerProfilesEvaluationsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEvaluationsInstance[]>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsInstance[]>>; + /** + * Retrieve a single page of CustomerProfilesEvaluationsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEvaluationsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CustomerProfilesEvaluationsPage) => any): Promise<CustomerProfilesEvaluationsPage>; + page(params: CustomerProfilesEvaluationsListInstancePageOptions, callback?: (error: Error | null, items: CustomerProfilesEvaluationsPage) => any): Promise<CustomerProfilesEvaluationsPage>; + /** + * Retrieve a single page of CustomerProfilesEvaluationsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CustomerProfilesEvaluationsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEvaluationsPage>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsPage>>; + pageWithHttpInfo(params: CustomerProfilesEvaluationsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEvaluationsPage>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CustomerProfilesEvaluationsListInstance(version: V1, customerProfileSid: string): CustomerProfilesEvaluationsListInstance { + if (!isValidPathParam(customerProfileSid)) { + throw new Error('Parameter \'customerProfileSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as CustomerProfilesEvaluationsListInstance; + + instance.get = function get(sid, ): CustomerProfilesEvaluationsContext { + return new CustomerProfilesEvaluationsContextImpl(version, customerProfileSid, sid); + } + + instance._version = version; + instance._solution = { customerProfileSid, }; + instance._uri = `/CustomerProfiles/${customerProfileSid}/Evaluations`; + + instance.create = function create(params: CustomerProfilesEvaluationsListInstanceCreateOptions, callback?: (error: Error | null, items: CustomerProfilesEvaluationsInstance) => any): Promise<CustomerProfilesEvaluationsInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["policySid"] === null || params["policySid"] === undefined) { + throw new Error('Required parameter "params[\'policySid\']" missing.'); + } + + let data: any = {}; + + + + data["PolicySid"] = params["policySid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesEvaluationsInstance(operationVersion, payload, instance._solution.customerProfileSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CustomerProfilesEvaluationsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEvaluationsInstance>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["policySid"] === null || params["policySid"] === undefined) { + throw new Error('Required parameter "params[\'policySid\']" missing.'); + } + + let data: any = {}; + + + + data["PolicySid"] = params["policySid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CustomerProfilesEvaluationsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CustomerProfilesEvaluationsInstance> => ({ + ...response, + body: new CustomerProfilesEvaluationsInstance(operationVersion, response.body, instance._solution.customerProfileSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CustomerProfilesEvaluationsListInstancePageOptions | ((error: Error | null, items: CustomerProfilesEvaluationsPage) => any), callback?: (error: Error | null, items: CustomerProfilesEvaluationsPage) => any): Promise<CustomerProfilesEvaluationsPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CustomerProfilesEvaluationsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CustomerProfilesEvaluationsPage) => any): Promise<CustomerProfilesEvaluationsPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CustomerProfilesEvaluationsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CustomerProfilesEvaluationsListInstancePageOptions | ((error: Error | null, items: ApiResponse<CustomerProfilesEvaluationsPage>) => any), callback?: (error: Error | null, items: ApiResponse<CustomerProfilesEvaluationsPage>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CustomerProfilesEvaluationsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CustomerProfilesEvaluationsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CustomerProfilesEvaluationsPage>) => any): Promise<ApiResponse<CustomerProfilesEvaluationsPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CustomerProfilesEvaluationsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CustomerProfilesEvaluationsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CustomerProfilesEvaluationsPage extends Page<V1, CustomerProfilesEvaluationsPayload, CustomerProfilesEvaluationsResource, CustomerProfilesEvaluationsInstance> { +/** +* Initialize the CustomerProfilesEvaluationsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CustomerProfilesEvaluationsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CustomerProfilesEvaluationsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CustomerProfilesEvaluationsResource): CustomerProfilesEvaluationsInstance { + + return new CustomerProfilesEvaluationsInstance( + this._version, + payload, + this._solution.customerProfileSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/customerProfilesProvisionalCopy.ts b/rest/trusthub/v1/customerProfilesProvisionalCopy.ts new file mode 100644 index 000000000..cd8a44154 --- /dev/null +++ b/rest/trusthub/v1/customerProfilesProvisionalCopy.ts @@ -0,0 +1,386 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface CustomerProfilesProvisionalCopyContext { + + /** + * Create a CustomerProfilesProvisionalCopyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesProvisionalCopyInstance + */ + create(callback?: (error: Error | null, item?: CustomerProfilesProvisionalCopyInstance) => any): Promise<CustomerProfilesProvisionalCopyInstance> + + /** + * Create a CustomerProfilesProvisionalCopyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesProvisionalCopyInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesProvisionalCopyInstance>) => any): Promise<ApiResponse<CustomerProfilesProvisionalCopyInstance>> + + /** + * Fetch a CustomerProfilesProvisionalCopyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesProvisionalCopyInstance + */ + fetch(callback?: (error: Error | null, item?: CustomerProfilesProvisionalCopyInstance) => any): Promise<CustomerProfilesProvisionalCopyInstance> + + /** + * Fetch a CustomerProfilesProvisionalCopyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesProvisionalCopyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesProvisionalCopyInstance>) => any): Promise<ApiResponse<CustomerProfilesProvisionalCopyInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CustomerProfilesProvisionalCopyContextSolution { + "customerProfileSid": string; +} + +export class CustomerProfilesProvisionalCopyContextImpl implements CustomerProfilesProvisionalCopyContext { + protected _solution: CustomerProfilesProvisionalCopyContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, customerProfileSid: string) { + if (!isValidPathParam(customerProfileSid)) { + throw new Error('Parameter \'customerProfileSid\' is not valid.'); + } + + this._solution = { customerProfileSid, }; + this._uri = `/CustomerProfiles/${customerProfileSid}/ProvisionalCopy`; + } + + create(callback?: (error: Error | null, item?: CustomerProfilesProvisionalCopyInstance) => any): Promise<CustomerProfilesProvisionalCopyInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesProvisionalCopyInstance(operationVersion, payload, instance._solution.customerProfileSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesProvisionalCopyInstance>) => any): Promise<ApiResponse<CustomerProfilesProvisionalCopyInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CustomerProfilesProvisionalCopyResource>({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse<CustomerProfilesProvisionalCopyInstance> => ({ + ...response, + body: new CustomerProfilesProvisionalCopyInstance(operationVersion, response.body, instance._solution.customerProfileSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CustomerProfilesProvisionalCopyInstance) => any): Promise<CustomerProfilesProvisionalCopyInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CustomerProfilesProvisionalCopyInstance(operationVersion, payload, instance._solution.customerProfileSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesProvisionalCopyInstance>) => any): Promise<ApiResponse<CustomerProfilesProvisionalCopyInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CustomerProfilesProvisionalCopyResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CustomerProfilesProvisionalCopyInstance> => ({ + ...response, + body: new CustomerProfilesProvisionalCopyInstance(operationVersion, response.body, instance._solution.customerProfileSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CustomerProfilesProvisionalCopyPayload extends CustomerProfilesProvisionalCopyResource {} + +interface CustomerProfilesProvisionalCopyResource { + customer_profile_sid: string; + account_sid: string; + policy_sid: string; + friendly_name: string; + status: string; + email: string; + status_callback: string; + valid_until: Date; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CustomerProfilesProvisionalCopyInstance { + protected _solution: CustomerProfilesProvisionalCopyContextSolution; + protected _context?: CustomerProfilesProvisionalCopyContext; + + constructor(protected _version: V1, payload: CustomerProfilesProvisionalCopyResource, customerProfileSid?: string) { + + this.customerProfileSid = (payload.customer_profile_sid); + this.accountSid = (payload.account_sid); + this.policySid = (payload.policy_sid); + this.friendlyName = (payload.friendly_name); + this.status = (payload.status); + this.email = (payload.email); + this.statusCallback = (payload.status_callback); + this.validUntil = deserialize.iso8601DateTime(payload.valid_until); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { customerProfileSid: customerProfileSid, }; + } + + /** + * The unique SID identifier of the Customer Profile. + */ + customerProfileSid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique string of a policy that is associated to the Customer-Profile resource. + */ + policySid: string; + /** + * A human readable description of this resource, up to 64 characters. + */ + friendlyName: string; + /** + * The verification status of the Customer-Profile resource. + */ + status: string; + /** + * The email address that will receive updates when the Customer-Profile resource changes status. + */ + email: string; + /** + * The URL we call to inform your application of status changes. + */ + statusCallback: string; + /** + * The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + */ + validUntil: Date; + /** + * The date that this Customer Profiles Provisional Copy was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Customer Profiles Provisional Copy was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): CustomerProfilesProvisionalCopyContext { + this._context = this._context || new CustomerProfilesProvisionalCopyContextImpl(this._version, this._solution.customerProfileSid); + return this._context; + } + + /** + * Create a CustomerProfilesProvisionalCopyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesProvisionalCopyInstance + */ + create(callback?: (error: Error | null, item?: CustomerProfilesProvisionalCopyInstance) => any): Promise<CustomerProfilesProvisionalCopyInstance> + + { + return this._proxy.create(callback); + } + + /** + * Create a CustomerProfilesProvisionalCopyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesProvisionalCopyInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesProvisionalCopyInstance>) => any): Promise<ApiResponse<CustomerProfilesProvisionalCopyInstance>> + + { + return this._proxy.createWithHttpInfo(callback); + } + + /** + * Fetch a CustomerProfilesProvisionalCopyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesProvisionalCopyInstance + */ + fetch(callback?: (error: Error | null, item?: CustomerProfilesProvisionalCopyInstance) => any): Promise<CustomerProfilesProvisionalCopyInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CustomerProfilesProvisionalCopyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CustomerProfilesProvisionalCopyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CustomerProfilesProvisionalCopyInstance>) => any): Promise<ApiResponse<CustomerProfilesProvisionalCopyInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + customerProfileSid: this.customerProfileSid, + accountSid: this.accountSid, + policySid: this.policySid, + friendlyName: this.friendlyName, + status: this.status, + email: this.email, + statusCallback: this.statusCallback, + validUntil: this.validUntil, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CustomerProfilesProvisionalCopySolution { +} + +export interface CustomerProfilesProvisionalCopyListInstance { + _version: V1; + _solution: CustomerProfilesProvisionalCopySolution; + _uri: string; + + (customerProfileSid: string, ): CustomerProfilesProvisionalCopyContext; + get(customerProfileSid: string, ): CustomerProfilesProvisionalCopyContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CustomerProfilesProvisionalCopyListInstance(version: V1): CustomerProfilesProvisionalCopyListInstance { + const instance = ((customerProfileSid, ) => instance.get(customerProfileSid, )) as CustomerProfilesProvisionalCopyListInstance; + + instance.get = function get(customerProfileSid, ): CustomerProfilesProvisionalCopyContext { + return new CustomerProfilesProvisionalCopyContextImpl(version, customerProfileSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/trusthub/v1/endUser.ts b/rest/trusthub/v1/endUser.ts new file mode 100644 index 000000000..940318602 --- /dev/null +++ b/rest/trusthub/v1/endUser.ts @@ -0,0 +1,929 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a EndUserInstance + */ +export interface EndUserContextUpdateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The set of parameters that are the attributes of the End User resource which are derived End User Types. */ + "attributes"?: any; +} + +/** + * Options to pass to create a EndUserInstance + */ +export interface EndUserListInstanceCreateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName": string; + /** The type of end user of the Bundle resource - can be `individual` or `business`. */ + "type": string; + /** The set of parameters that are the attributes of the End User resource which are derived End User Types. */ + "attributes"?: any; +} + +/** + * Options to pass to each + */ +export interface EndUserListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EndUserInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EndUserListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EndUserListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EndUserContext { + + /** + * Remove a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + fetch(callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance> + + /** + * Fetch a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> + + /** + * Update a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + update(callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance>; + /** + * Update a EndUserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + update(params: EndUserContextUpdateOptions, callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance>; + + /** + * Update a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>>; + /** + * Update a EndUserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + updateWithHttpInfo(params: EndUserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EndUserContextSolution { + "sid": string; +} + +export class EndUserContextImpl implements EndUserContext { + protected _solution: EndUserContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/EndUsers/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EndUserInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EndUserResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EndUserInstance> => ({ + ...response, + body: new EndUserInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: EndUserContextUpdateOptions | ((error: Error | null, item?: EndUserInstance) => any),callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new EndUserInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: EndUserContextUpdateOptions | ((error: Error | null, item?: ApiResponse<EndUserInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<EndUserResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<EndUserInstance> => ({ + ...response, + body: new EndUserInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EndUserPayload extends TwilioResponsePayload { + results: EndUserResource[]; +} + +interface EndUserResource { + sid: string; + account_sid: string; + friendly_name: string; + type: string; + attributes: any; + date_created: Date; + date_updated: Date; + url: string; +} + +export class EndUserInstance { + protected _solution: EndUserContextSolution; + protected _context?: EndUserContext; + + constructor(protected _version: V1, payload: EndUserResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.type = (payload.type); + this.attributes = (payload.attributes); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string created by Twilio to identify the End User resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the End User resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The type of end user of the Bundle resource - can be `individual` or `business`. + */ + type: string; + /** + * The set of parameters that are the attributes of the End Users resource which are listed in the End User Types. + */ + attributes: any; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the End User resource. + */ + url: string; + + private get _proxy(): EndUserContext { + this._context = this._context || new EndUserContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + fetch(callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a EndUserInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + update(callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance>; + /** + * Update a EndUserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + update(params: EndUserContextUpdateOptions, callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance>; + + update(params?: any, callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a EndUserInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>>; + /** + * Update a EndUserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + updateWithHttpInfo(params: EndUserContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + type: this.type, + attributes: this.attributes, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EndUserSolution { +} + +export interface EndUserListInstance { + _version: V1; + _solution: EndUserSolution; + _uri: string; + + (sid: string, ): EndUserContext; + get(sid: string, ): EndUserContext; + + + + + + + + + /** + * Create a EndUserInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance + */ + create(params: EndUserListInstanceCreateOptions, callback?: (error: Error | null, item?: EndUserInstance) => any): Promise<EndUserInstance>; + + /** + * Create a EndUserInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserInstance with HTTP metadata + */ + createWithHttpInfo(params: EndUserListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>>; + + + + + /** + * Streams EndUserInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EndUserInstance, done: (err?: Error) => void) => void): void; + each(params: EndUserListInstanceEachOptions, callback?: (item: EndUserInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EndUserInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EndUserInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EndUserListInstanceEachOptions, callback?: (item: EndUserInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EndUserInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EndUserPage) => any): Promise<EndUserPage>; + /** + * Retrieve a single target page of EndUserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EndUserPage>) => any): Promise<ApiResponse<EndUserPage>>; + /** + * Lists EndUserInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EndUserInstance[]) => any): Promise<EndUserInstance[]>; + list(params: EndUserListInstanceOptions, callback?: (error: Error | null, items: EndUserInstance[]) => any): Promise<EndUserInstance[]>; + /** + * Lists EndUserInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EndUserInstance[]>) => any): Promise<ApiResponse<EndUserInstance[]>>; + listWithHttpInfo(params: EndUserListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EndUserInstance[]>) => any): Promise<ApiResponse<EndUserInstance[]>>; + /** + * Retrieve a single page of EndUserInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EndUserPage) => any): Promise<EndUserPage>; + page(params: EndUserListInstancePageOptions, callback?: (error: Error | null, items: EndUserPage) => any): Promise<EndUserPage>; + /** + * Retrieve a single page of EndUserInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EndUserPage>) => any): Promise<ApiResponse<EndUserPage>>; + pageWithHttpInfo(params: EndUserListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EndUserPage>) => any): Promise<ApiResponse<EndUserPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EndUserListInstance(version: V1): EndUserListInstance { + const instance = ((sid, ) => instance.get(sid, )) as EndUserListInstance; + + instance.get = function get(sid, ): EndUserContext { + return new EndUserContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/EndUsers`; + + instance.create = function create(params: EndUserListInstanceCreateOptions, callback?: (error: Error | null, items: EndUserInstance) => any): Promise<EndUserInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new EndUserInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: EndUserListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<EndUserInstance>) => any): Promise<ApiResponse<EndUserInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<EndUserResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<EndUserInstance> => ({ + ...response, + body: new EndUserInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: EndUserListInstancePageOptions | ((error: Error | null, items: EndUserPage) => any), callback?: (error: Error | null, items: EndUserPage) => any): Promise<EndUserPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EndUserPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EndUserPage) => any): Promise<EndUserPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EndUserPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EndUserListInstancePageOptions | ((error: Error | null, items: ApiResponse<EndUserPage>) => any), callback?: (error: Error | null, items: ApiResponse<EndUserPage>) => any): Promise<ApiResponse<EndUserPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EndUserPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EndUserPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EndUserPage>) => any): Promise<ApiResponse<EndUserPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EndUserPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EndUserPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EndUserPage extends Page<V1, EndUserPayload, EndUserResource, EndUserInstance> { +/** +* Initialize the EndUserPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: EndUserSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EndUserInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EndUserResource): EndUserInstance { + + return new EndUserInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/endUserType.ts b/rest/trusthub/v1/endUserType.ts new file mode 100644 index 000000000..f3159c431 --- /dev/null +++ b/rest/trusthub/v1/endUserType.ts @@ -0,0 +1,544 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface EndUserTypeListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EndUserTypeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EndUserTypeListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EndUserTypeListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EndUserTypeContext { + + /** + * Fetch a EndUserTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserTypeInstance + */ + fetch(callback?: (error: Error | null, item?: EndUserTypeInstance) => any): Promise<EndUserTypeInstance> + + /** + * Fetch a EndUserTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserTypeInstance>) => any): Promise<ApiResponse<EndUserTypeInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EndUserTypeContextSolution { + "sid": string; +} + +export class EndUserTypeContextImpl implements EndUserTypeContext { + protected _solution: EndUserTypeContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/EndUserTypes/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: EndUserTypeInstance) => any): Promise<EndUserTypeInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EndUserTypeInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserTypeInstance>) => any): Promise<ApiResponse<EndUserTypeInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EndUserTypeResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EndUserTypeInstance> => ({ + ...response, + body: new EndUserTypeInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EndUserTypePayload extends TwilioResponsePayload { + end_user_types: EndUserTypeResource[]; +} + +interface EndUserTypeResource { + sid: string; + friendly_name: string; + machine_name: string; + fields: Array<any>; + url: string; +} + +export class EndUserTypeInstance { + protected _solution: EndUserTypeContextSolution; + protected _context?: EndUserTypeContext; + + constructor(protected _version: V1, payload: EndUserTypeResource, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.machineName = (payload.machine_name); + this.fields = (payload.fields); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that identifies the End-User Type resource. + */ + sid: string; + /** + * A human-readable description that is assigned to describe the End-User Type resource. Examples can include first name, last name, email, business name, etc + */ + friendlyName: string; + /** + * A machine-readable description of the End-User Type resource. Examples can include first_name, last_name, email, business_name, etc. + */ + machineName: string; + /** + * The required information for creating an End-User. The required fields will change as regulatory needs change and will differ for businesses and individuals. + */ + fields: Array<any>; + /** + * The absolute URL of the End-User Type resource. + */ + url: string; + + private get _proxy(): EndUserTypeContext { + this._context = this._context || new EndUserTypeContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a EndUserTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserTypeInstance + */ + fetch(callback?: (error: Error | null, item?: EndUserTypeInstance) => any): Promise<EndUserTypeInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EndUserTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EndUserTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EndUserTypeInstance>) => any): Promise<ApiResponse<EndUserTypeInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + machineName: this.machineName, + fields: this.fields, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EndUserTypeSolution { +} + +export interface EndUserTypeListInstance { + _version: V1; + _solution: EndUserTypeSolution; + _uri: string; + + (sid: string, ): EndUserTypeContext; + get(sid: string, ): EndUserTypeContext; + + + + + + /** + * Streams EndUserTypeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EndUserTypeInstance, done: (err?: Error) => void) => void): void; + each(params: EndUserTypeListInstanceEachOptions, callback?: (item: EndUserTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EndUserTypeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EndUserTypeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EndUserTypeListInstanceEachOptions, callback?: (item: EndUserTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EndUserTypeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EndUserTypePage) => any): Promise<EndUserTypePage>; + /** + * Retrieve a single target page of EndUserTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EndUserTypePage>) => any): Promise<ApiResponse<EndUserTypePage>>; + /** + * Lists EndUserTypeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EndUserTypeInstance[]) => any): Promise<EndUserTypeInstance[]>; + list(params: EndUserTypeListInstanceOptions, callback?: (error: Error | null, items: EndUserTypeInstance[]) => any): Promise<EndUserTypeInstance[]>; + /** + * Lists EndUserTypeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EndUserTypeInstance[]>) => any): Promise<ApiResponse<EndUserTypeInstance[]>>; + listWithHttpInfo(params: EndUserTypeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EndUserTypeInstance[]>) => any): Promise<ApiResponse<EndUserTypeInstance[]>>; + /** + * Retrieve a single page of EndUserTypeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EndUserTypePage) => any): Promise<EndUserTypePage>; + page(params: EndUserTypeListInstancePageOptions, callback?: (error: Error | null, items: EndUserTypePage) => any): Promise<EndUserTypePage>; + /** + * Retrieve a single page of EndUserTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EndUserTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EndUserTypePage>) => any): Promise<ApiResponse<EndUserTypePage>>; + pageWithHttpInfo(params: EndUserTypeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EndUserTypePage>) => any): Promise<ApiResponse<EndUserTypePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EndUserTypeListInstance(version: V1): EndUserTypeListInstance { + const instance = ((sid, ) => instance.get(sid, )) as EndUserTypeListInstance; + + instance.get = function get(sid, ): EndUserTypeContext { + return new EndUserTypeContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/EndUserTypes`; + + instance.page = function page(params?: EndUserTypeListInstancePageOptions | ((error: Error | null, items: EndUserTypePage) => any), callback?: (error: Error | null, items: EndUserTypePage) => any): Promise<EndUserTypePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EndUserTypePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EndUserTypePage) => any): Promise<EndUserTypePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EndUserTypePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EndUserTypeListInstancePageOptions | ((error: Error | null, items: ApiResponse<EndUserTypePage>) => any), callback?: (error: Error | null, items: ApiResponse<EndUserTypePage>) => any): Promise<ApiResponse<EndUserTypePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EndUserTypePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EndUserTypePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EndUserTypePage>) => any): Promise<ApiResponse<EndUserTypePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EndUserTypePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EndUserTypePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EndUserTypePage extends Page<V1, EndUserTypePayload, EndUserTypeResource, EndUserTypeInstance> { +/** +* Initialize the EndUserTypePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: EndUserTypeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of EndUserTypeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EndUserTypeResource): EndUserTypeInstance { + + return new EndUserTypeInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/policies.ts b/rest/trusthub/v1/policies.ts new file mode 100644 index 000000000..d82fda507 --- /dev/null +++ b/rest/trusthub/v1/policies.ts @@ -0,0 +1,537 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface PoliciesListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PoliciesInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PoliciesListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PoliciesListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PoliciesContext { + + /** + * Fetch a PoliciesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PoliciesInstance + */ + fetch(callback?: (error: Error | null, item?: PoliciesInstance) => any): Promise<PoliciesInstance> + + /** + * Fetch a PoliciesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PoliciesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PoliciesInstance>) => any): Promise<ApiResponse<PoliciesInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PoliciesContextSolution { + "sid": string; +} + +export class PoliciesContextImpl implements PoliciesContext { + protected _solution: PoliciesContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Policies/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: PoliciesInstance) => any): Promise<PoliciesInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PoliciesInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PoliciesInstance>) => any): Promise<ApiResponse<PoliciesInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PoliciesResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<PoliciesInstance> => ({ + ...response, + body: new PoliciesInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PoliciesPayload extends TwilioResponsePayload { + results: PoliciesResource[]; +} + +interface PoliciesResource { + sid: string; + friendly_name: string; + requirements: any; + url: string; +} + +export class PoliciesInstance { + protected _solution: PoliciesContextSolution; + protected _context?: PoliciesContext; + + constructor(protected _version: V1, payload: PoliciesResource, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.requirements = (payload.requirements); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that identifies the Policy resource. + */ + sid: string; + /** + * A human-readable description that is assigned to describe the Policy resource. Examples can include Primary Customer profile policy + */ + friendlyName: string; + /** + * The SID of an object that holds the policy information + */ + requirements: any; + /** + * The absolute URL of the Policy resource. + */ + url: string; + + private get _proxy(): PoliciesContext { + this._context = this._context || new PoliciesContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a PoliciesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PoliciesInstance + */ + fetch(callback?: (error: Error | null, item?: PoliciesInstance) => any): Promise<PoliciesInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PoliciesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PoliciesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PoliciesInstance>) => any): Promise<ApiResponse<PoliciesInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + requirements: this.requirements, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PoliciesSolution { +} + +export interface PoliciesListInstance { + _version: V1; + _solution: PoliciesSolution; + _uri: string; + + (sid: string, ): PoliciesContext; + get(sid: string, ): PoliciesContext; + + + + + + /** + * Streams PoliciesInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PoliciesListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PoliciesInstance, done: (err?: Error) => void) => void): void; + each(params: PoliciesListInstanceEachOptions, callback?: (item: PoliciesInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PoliciesInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PoliciesListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PoliciesInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PoliciesListInstanceEachOptions, callback?: (item: PoliciesInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PoliciesInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PoliciesPage) => any): Promise<PoliciesPage>; + /** + * Retrieve a single target page of PoliciesInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<PoliciesPage>) => any): Promise<ApiResponse<PoliciesPage>>; + /** + * Lists PoliciesInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PoliciesListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PoliciesInstance[]) => any): Promise<PoliciesInstance[]>; + list(params: PoliciesListInstanceOptions, callback?: (error: Error | null, items: PoliciesInstance[]) => any): Promise<PoliciesInstance[]>; + /** + * Lists PoliciesInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PoliciesListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PoliciesInstance[]>) => any): Promise<ApiResponse<PoliciesInstance[]>>; + listWithHttpInfo(params: PoliciesListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<PoliciesInstance[]>) => any): Promise<ApiResponse<PoliciesInstance[]>>; + /** + * Retrieve a single page of PoliciesInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PoliciesListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PoliciesPage) => any): Promise<PoliciesPage>; + page(params: PoliciesListInstancePageOptions, callback?: (error: Error | null, items: PoliciesPage) => any): Promise<PoliciesPage>; + /** + * Retrieve a single page of PoliciesInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PoliciesListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PoliciesPage>) => any): Promise<ApiResponse<PoliciesPage>>; + pageWithHttpInfo(params: PoliciesListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<PoliciesPage>) => any): Promise<ApiResponse<PoliciesPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PoliciesListInstance(version: V1): PoliciesListInstance { + const instance = ((sid, ) => instance.get(sid, )) as PoliciesListInstance; + + instance.get = function get(sid, ): PoliciesContext { + return new PoliciesContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Policies`; + + instance.page = function page(params?: PoliciesListInstancePageOptions | ((error: Error | null, items: PoliciesPage) => any), callback?: (error: Error | null, items: PoliciesPage) => any): Promise<PoliciesPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PoliciesPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PoliciesPage) => any): Promise<PoliciesPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PoliciesPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PoliciesListInstancePageOptions | ((error: Error | null, items: ApiResponse<PoliciesPage>) => any), callback?: (error: Error | null, items: ApiResponse<PoliciesPage>) => any): Promise<ApiResponse<PoliciesPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<PoliciesPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PoliciesPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<PoliciesPage>) => any): Promise<ApiResponse<PoliciesPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<PoliciesPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PoliciesPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PoliciesPage extends Page<V1, PoliciesPayload, PoliciesResource, PoliciesInstance> { +/** +* Initialize the PoliciesPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: PoliciesSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PoliciesInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PoliciesResource): PoliciesInstance { + + return new PoliciesInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/supportingDocument.ts b/rest/trusthub/v1/supportingDocument.ts new file mode 100644 index 000000000..d8f291656 --- /dev/null +++ b/rest/trusthub/v1/supportingDocument.ts @@ -0,0 +1,945 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The verification status of the Supporting Document resource. + */ +export type SupportingDocumentStatus = 'DRAFT'|'PENDING_REVIEW'|'REJECTED'|'APPROVED'|'EXPIRED'|'PROVISIONALLY_APPROVED'; + + + + +/** + * Options to pass to update a SupportingDocumentInstance + */ +export interface SupportingDocumentContextUpdateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. */ + "attributes"?: any; +} + +/** + * Options to pass to create a SupportingDocumentInstance + */ +export interface SupportingDocumentListInstanceCreateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName": string; + /** The type of the Supporting Document. */ + "type": string; + /** The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. */ + "attributes"?: any; +} + +/** + * Options to pass to each + */ +export interface SupportingDocumentListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SupportingDocumentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SupportingDocumentListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SupportingDocumentListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SupportingDocumentContext { + + /** + * Remove a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + fetch(callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> + + /** + * Fetch a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> + + /** + * Update a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + update(callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance>; + /** + * Update a SupportingDocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + update(params: SupportingDocumentContextUpdateOptions, callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance>; + + /** + * Update a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>>; + /** + * Update a SupportingDocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(params: SupportingDocumentContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SupportingDocumentContextSolution { + "sid": string; +} + +export class SupportingDocumentContextImpl implements SupportingDocumentContext { + protected _solution: SupportingDocumentContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/SupportingDocuments/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SupportingDocumentInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SupportingDocumentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SupportingDocumentInstance> => ({ + ...response, + body: new SupportingDocumentInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SupportingDocumentContextUpdateOptions | ((error: Error | null, item?: SupportingDocumentInstance) => any),callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SupportingDocumentInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SupportingDocumentContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SupportingDocumentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SupportingDocumentInstance> => ({ + ...response, + body: new SupportingDocumentInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SupportingDocumentPayload extends TwilioResponsePayload { + results: SupportingDocumentResource[]; +} + +interface SupportingDocumentResource { + sid: string; + account_sid: string; + friendly_name: string; + mime_type: string; + status: SupportingDocumentStatus; + type: string; + attributes: any; + date_created: Date; + date_updated: Date; + url: string; +} + +export class SupportingDocumentInstance { + protected _solution: SupportingDocumentContextSolution; + protected _context?: SupportingDocumentContext; + + constructor(protected _version: V1, payload: SupportingDocumentResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.mimeType = (payload.mime_type); + this.status = payload.status; + this.type = (payload.type); + this.attributes = (payload.attributes); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string created by Twilio to identify the Supporting Document resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The image type uploaded in the Supporting Document container. + */ + mimeType: string; + status: SupportingDocumentStatus; + /** + * The type of the Supporting Document. + */ + type: string; + /** + * The set of parameters that are the attributes of the Supporting Documents resource which are listed in the Supporting Document Types. + */ + attributes: any; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Supporting Document resource. + */ + url: string; + + private get _proxy(): SupportingDocumentContext { + this._context = this._context || new SupportingDocumentContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + fetch(callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SupportingDocumentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + update(callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance>; + /** + * Update a SupportingDocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + update(params: SupportingDocumentContextUpdateOptions, callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SupportingDocumentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>>; + /** + * Update a SupportingDocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + updateWithHttpInfo(params: SupportingDocumentContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + mimeType: this.mimeType, + status: this.status, + type: this.type, + attributes: this.attributes, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SupportingDocumentSolution { +} + +export interface SupportingDocumentListInstance { + _version: V1; + _solution: SupportingDocumentSolution; + _uri: string; + + (sid: string, ): SupportingDocumentContext; + get(sid: string, ): SupportingDocumentContext; + + + + + + + + + /** + * Create a SupportingDocumentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance + */ + create(params: SupportingDocumentListInstanceCreateOptions, callback?: (error: Error | null, item?: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance>; + + /** + * Create a SupportingDocumentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentInstance with HTTP metadata + */ + createWithHttpInfo(params: SupportingDocumentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>>; + + + + + /** + * Streams SupportingDocumentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SupportingDocumentInstance, done: (err?: Error) => void) => void): void; + each(params: SupportingDocumentListInstanceEachOptions, callback?: (item: SupportingDocumentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SupportingDocumentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SupportingDocumentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SupportingDocumentListInstanceEachOptions, callback?: (item: SupportingDocumentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SupportingDocumentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SupportingDocumentPage) => any): Promise<SupportingDocumentPage>; + /** + * Retrieve a single target page of SupportingDocumentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentPage>) => any): Promise<ApiResponse<SupportingDocumentPage>>; + /** + * Lists SupportingDocumentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SupportingDocumentInstance[]) => any): Promise<SupportingDocumentInstance[]>; + list(params: SupportingDocumentListInstanceOptions, callback?: (error: Error | null, items: SupportingDocumentInstance[]) => any): Promise<SupportingDocumentInstance[]>; + /** + * Lists SupportingDocumentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SupportingDocumentInstance[]>) => any): Promise<ApiResponse<SupportingDocumentInstance[]>>; + listWithHttpInfo(params: SupportingDocumentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentInstance[]>) => any): Promise<ApiResponse<SupportingDocumentInstance[]>>; + /** + * Retrieve a single page of SupportingDocumentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SupportingDocumentPage) => any): Promise<SupportingDocumentPage>; + page(params: SupportingDocumentListInstancePageOptions, callback?: (error: Error | null, items: SupportingDocumentPage) => any): Promise<SupportingDocumentPage>; + /** + * Retrieve a single page of SupportingDocumentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SupportingDocumentPage>) => any): Promise<ApiResponse<SupportingDocumentPage>>; + pageWithHttpInfo(params: SupportingDocumentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentPage>) => any): Promise<ApiResponse<SupportingDocumentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SupportingDocumentListInstance(version: V1): SupportingDocumentListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SupportingDocumentListInstance; + + instance.get = function get(sid, ): SupportingDocumentContext { + return new SupportingDocumentContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/SupportingDocuments`; + + instance.create = function create(params: SupportingDocumentListInstanceCreateOptions, callback?: (error: Error | null, items: SupportingDocumentInstance) => any): Promise<SupportingDocumentInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SupportingDocumentInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SupportingDocumentListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentInstance>) => any): Promise<ApiResponse<SupportingDocumentInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["type"] === null || params["type"] === undefined) { + throw new Error('Required parameter "params[\'type\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Type"] = params["type"]; + if (params["attributes"] !== undefined) + data["Attributes"] = serialize.object(params["attributes"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SupportingDocumentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SupportingDocumentInstance> => ({ + ...response, + body: new SupportingDocumentInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SupportingDocumentListInstancePageOptions | ((error: Error | null, items: SupportingDocumentPage) => any), callback?: (error: Error | null, items: SupportingDocumentPage) => any): Promise<SupportingDocumentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SupportingDocumentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SupportingDocumentPage) => any): Promise<SupportingDocumentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SupportingDocumentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SupportingDocumentListInstancePageOptions | ((error: Error | null, items: ApiResponse<SupportingDocumentPage>) => any), callback?: (error: Error | null, items: ApiResponse<SupportingDocumentPage>) => any): Promise<ApiResponse<SupportingDocumentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SupportingDocumentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SupportingDocumentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SupportingDocumentPage>) => any): Promise<ApiResponse<SupportingDocumentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SupportingDocumentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SupportingDocumentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SupportingDocumentPage extends Page<V1, SupportingDocumentPayload, SupportingDocumentResource, SupportingDocumentInstance> { +/** +* Initialize the SupportingDocumentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SupportingDocumentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SupportingDocumentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SupportingDocumentResource): SupportingDocumentInstance { + + return new SupportingDocumentInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/supportingDocumentType.ts b/rest/trusthub/v1/supportingDocumentType.ts new file mode 100644 index 000000000..41467e74c --- /dev/null +++ b/rest/trusthub/v1/supportingDocumentType.ts @@ -0,0 +1,544 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to each + */ +export interface SupportingDocumentTypeListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SupportingDocumentTypeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SupportingDocumentTypeListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SupportingDocumentTypeListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SupportingDocumentTypeContext { + + /** + * Fetch a SupportingDocumentTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentTypeInstance + */ + fetch(callback?: (error: Error | null, item?: SupportingDocumentTypeInstance) => any): Promise<SupportingDocumentTypeInstance> + + /** + * Fetch a SupportingDocumentTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentTypeInstance>) => any): Promise<ApiResponse<SupportingDocumentTypeInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SupportingDocumentTypeContextSolution { + "sid": string; +} + +export class SupportingDocumentTypeContextImpl implements SupportingDocumentTypeContext { + protected _solution: SupportingDocumentTypeContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/SupportingDocumentTypes/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: SupportingDocumentTypeInstance) => any): Promise<SupportingDocumentTypeInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SupportingDocumentTypeInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentTypeInstance>) => any): Promise<ApiResponse<SupportingDocumentTypeInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SupportingDocumentTypeResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SupportingDocumentTypeInstance> => ({ + ...response, + body: new SupportingDocumentTypeInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SupportingDocumentTypePayload extends TwilioResponsePayload { + supporting_document_types: SupportingDocumentTypeResource[]; +} + +interface SupportingDocumentTypeResource { + sid: string; + friendly_name: string; + machine_name: string; + fields: Array<any>; + url: string; +} + +export class SupportingDocumentTypeInstance { + protected _solution: SupportingDocumentTypeContextSolution; + protected _context?: SupportingDocumentTypeContext; + + constructor(protected _version: V1, payload: SupportingDocumentTypeResource, sid?: string) { + + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.machineName = (payload.machine_name); + this.fields = (payload.fields); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that identifies the Supporting Document Type resource. + */ + sid: string; + /** + * A human-readable description of the Supporting Document Type resource. + */ + friendlyName: string; + /** + * The machine-readable description of the Supporting Document Type resource. + */ + machineName: string; + /** + * The required information for creating a Supporting Document. The required fields will change as regulatory needs change and will differ for businesses and individuals. + */ + fields: Array<any>; + /** + * The absolute URL of the Supporting Document Type resource. + */ + url: string; + + private get _proxy(): SupportingDocumentTypeContext { + this._context = this._context || new SupportingDocumentTypeContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a SupportingDocumentTypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentTypeInstance + */ + fetch(callback?: (error: Error | null, item?: SupportingDocumentTypeInstance) => any): Promise<SupportingDocumentTypeInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SupportingDocumentTypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SupportingDocumentTypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SupportingDocumentTypeInstance>) => any): Promise<ApiResponse<SupportingDocumentTypeInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + friendlyName: this.friendlyName, + machineName: this.machineName, + fields: this.fields, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SupportingDocumentTypeSolution { +} + +export interface SupportingDocumentTypeListInstance { + _version: V1; + _solution: SupportingDocumentTypeSolution; + _uri: string; + + (sid: string, ): SupportingDocumentTypeContext; + get(sid: string, ): SupportingDocumentTypeContext; + + + + + + /** + * Streams SupportingDocumentTypeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SupportingDocumentTypeInstance, done: (err?: Error) => void) => void): void; + each(params: SupportingDocumentTypeListInstanceEachOptions, callback?: (item: SupportingDocumentTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SupportingDocumentTypeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SupportingDocumentTypeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SupportingDocumentTypeListInstanceEachOptions, callback?: (item: SupportingDocumentTypeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SupportingDocumentTypeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SupportingDocumentTypePage) => any): Promise<SupportingDocumentTypePage>; + /** + * Retrieve a single target page of SupportingDocumentTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypePage>) => any): Promise<ApiResponse<SupportingDocumentTypePage>>; + /** + * Lists SupportingDocumentTypeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SupportingDocumentTypeInstance[]) => any): Promise<SupportingDocumentTypeInstance[]>; + list(params: SupportingDocumentTypeListInstanceOptions, callback?: (error: Error | null, items: SupportingDocumentTypeInstance[]) => any): Promise<SupportingDocumentTypeInstance[]>; + /** + * Lists SupportingDocumentTypeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypeInstance[]>) => any): Promise<ApiResponse<SupportingDocumentTypeInstance[]>>; + listWithHttpInfo(params: SupportingDocumentTypeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypeInstance[]>) => any): Promise<ApiResponse<SupportingDocumentTypeInstance[]>>; + /** + * Retrieve a single page of SupportingDocumentTypeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SupportingDocumentTypePage) => any): Promise<SupportingDocumentTypePage>; + page(params: SupportingDocumentTypeListInstancePageOptions, callback?: (error: Error | null, items: SupportingDocumentTypePage) => any): Promise<SupportingDocumentTypePage>; + /** + * Retrieve a single page of SupportingDocumentTypeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SupportingDocumentTypeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypePage>) => any): Promise<ApiResponse<SupportingDocumentTypePage>>; + pageWithHttpInfo(params: SupportingDocumentTypeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypePage>) => any): Promise<ApiResponse<SupportingDocumentTypePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SupportingDocumentTypeListInstance(version: V1): SupportingDocumentTypeListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SupportingDocumentTypeListInstance; + + instance.get = function get(sid, ): SupportingDocumentTypeContext { + return new SupportingDocumentTypeContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/SupportingDocumentTypes`; + + instance.page = function page(params?: SupportingDocumentTypeListInstancePageOptions | ((error: Error | null, items: SupportingDocumentTypePage) => any), callback?: (error: Error | null, items: SupportingDocumentTypePage) => any): Promise<SupportingDocumentTypePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SupportingDocumentTypePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SupportingDocumentTypePage) => any): Promise<SupportingDocumentTypePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SupportingDocumentTypePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SupportingDocumentTypeListInstancePageOptions | ((error: Error | null, items: ApiResponse<SupportingDocumentTypePage>) => any), callback?: (error: Error | null, items: ApiResponse<SupportingDocumentTypePage>) => any): Promise<ApiResponse<SupportingDocumentTypePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SupportingDocumentTypePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SupportingDocumentTypePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SupportingDocumentTypePage>) => any): Promise<ApiResponse<SupportingDocumentTypePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SupportingDocumentTypePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SupportingDocumentTypePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SupportingDocumentTypePage extends Page<V1, SupportingDocumentTypePayload, SupportingDocumentTypeResource, SupportingDocumentTypeInstance> { +/** +* Initialize the SupportingDocumentTypePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SupportingDocumentTypeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SupportingDocumentTypeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SupportingDocumentTypeResource): SupportingDocumentTypeInstance { + + return new SupportingDocumentTypeInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/trustProducts.ts b/rest/trusthub/v1/trustProducts.ts new file mode 100644 index 000000000..fdc1aef3f --- /dev/null +++ b/rest/trusthub/v1/trustProducts.ts @@ -0,0 +1,1067 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { TrustProductsChannelEndpointAssignmentListInstance } from "./trustProducts/trustProductsChannelEndpointAssignment"; +import { TrustProductsEntityAssignmentsListInstance } from "./trustProducts/trustProductsEntityAssignments"; +import { TrustProductsEvaluationsListInstance } from "./trustProducts/trustProductsEvaluations"; + + +/** + * The verification status of the Trust Product resource. + */ +export type TrustProductsStatus = 'draft'|'pending-review'|'in-review'|'twilio-rejected'|'twilio-approved'; + + + + +/** + * Options to pass to update a TrustProductsInstance + */ +export interface TrustProductsContextUpdateOptions { + /** */ + "status"?: TrustProductsStatus; + /** The URL we call to inform your application of status changes. */ + "statusCallback"?: string; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The email address that will receive updates when the Trust Product resource changes status. */ + "email"?: string; +} + +/** + * Options to pass to create a TrustProductsInstance + */ +export interface TrustProductsListInstanceCreateOptions { + /** The string that you assigned to describe the resource. */ + "friendlyName": string; + /** The email address that will receive updates when the Trust Product resource changes status. */ + "email": string; + /** The unique string of a policy that is associated to the Trust Product resource. */ + "policySid": string; + /** The URL we call to inform your application of status changes. */ + "statusCallback"?: string; +} + +/** + * Options to pass to each + */ +export interface TrustProductsListInstanceEachOptions { + /** The verification status of the Trust Product resource. */ + "status"?: TrustProductsStatus; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The unique string of a policy that is associated to the Trust Product resource. */ + "policySid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TrustProductsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TrustProductsListInstanceOptions { + /** The verification status of the Trust Product resource. */ + "status"?: TrustProductsStatus; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The unique string of a policy that is associated to the Trust Product resource. */ + "policySid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TrustProductsListInstancePageOptions { + /** The verification status of the Trust Product resource. */ + "status"?: TrustProductsStatus; + /** The string that you assigned to describe the resource. */ + "friendlyName"?: string; + /** The unique string of a policy that is associated to the Trust Product resource. */ + "policySid"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TrustProductsContext { + trustProductsChannelEndpointAssignment: TrustProductsChannelEndpointAssignmentListInstance; + trustProductsEntityAssignments: TrustProductsEntityAssignmentsListInstance; + trustProductsEvaluations: TrustProductsEvaluationsListInstance; + + /** + * Remove a TrustProductsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a TrustProductsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a TrustProductsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance + */ + fetch(callback?: (error: Error | null, item?: TrustProductsInstance) => any): Promise<TrustProductsInstance> + + /** + * Fetch a TrustProductsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>> + + /** + * Update a TrustProductsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance + */ + update(callback?: (error: Error | null, item?: TrustProductsInstance) => any): Promise<TrustProductsInstance>; + /** + * Update a TrustProductsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance + */ + update(params: TrustProductsContextUpdateOptions, callback?: (error: Error | null, item?: TrustProductsInstance) => any): Promise<TrustProductsInstance>; + + /** + * Update a TrustProductsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>>; + /** + * Update a TrustProductsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance with HTTP metadata + */ + updateWithHttpInfo(params: TrustProductsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TrustProductsContextSolution { + "sid": string; +} + +export class TrustProductsContextImpl implements TrustProductsContext { + protected _solution: TrustProductsContextSolution; + protected _uri: string; + + protected _trustProductsChannelEndpointAssignment?: TrustProductsChannelEndpointAssignmentListInstance; + protected _trustProductsEntityAssignments?: TrustProductsEntityAssignmentsListInstance; + protected _trustProductsEvaluations?: TrustProductsEvaluationsListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/TrustProducts/${sid}`; + } + + get trustProductsChannelEndpointAssignment(): TrustProductsChannelEndpointAssignmentListInstance { + this._trustProductsChannelEndpointAssignment = this._trustProductsChannelEndpointAssignment || TrustProductsChannelEndpointAssignmentListInstance(this._version, this._solution.sid); + return this._trustProductsChannelEndpointAssignment; + } + + get trustProductsEntityAssignments(): TrustProductsEntityAssignmentsListInstance { + this._trustProductsEntityAssignments = this._trustProductsEntityAssignments || TrustProductsEntityAssignmentsListInstance(this._version, this._solution.sid); + return this._trustProductsEntityAssignments; + } + + get trustProductsEvaluations(): TrustProductsEvaluationsListInstance { + this._trustProductsEvaluations = this._trustProductsEvaluations || TrustProductsEvaluationsListInstance(this._version, this._solution.sid); + return this._trustProductsEvaluations; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TrustProductsInstance) => any): Promise<TrustProductsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TrustProductsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TrustProductsInstance> => ({ + ...response, + body: new TrustProductsInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: TrustProductsContextUpdateOptions | ((error: Error | null, item?: TrustProductsInstance) => any),callback?: (error: Error | null, item?: TrustProductsInstance) => any): Promise<TrustProductsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: TrustProductsContextUpdateOptions | ((error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["email"] !== undefined) + data["Email"] = params["email"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<TrustProductsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TrustProductsInstance> => ({ + ...response, + body: new TrustProductsInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TrustProductsPayload extends TwilioResponsePayload { + results: TrustProductsResource[]; +} + +interface TrustProductsResource { + sid: string; + account_sid: string; + policy_sid: string; + friendly_name: string; + status: TrustProductsStatus; + valid_until: Date; + email: string; + status_callback: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; + errors: Array<any>; +} + +export class TrustProductsInstance { + protected _solution: TrustProductsContextSolution; + protected _context?: TrustProductsContext; + + constructor(protected _version: V1, payload: TrustProductsResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.policySid = (payload.policy_sid); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.validUntil = deserialize.iso8601DateTime(payload.valid_until); + this.email = (payload.email); + this.statusCallback = (payload.status_callback); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + this.errors = (payload.errors); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Trust Product resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Trust Product resource. + */ + accountSid: string; + /** + * The unique string of the policy that is associated with the Trust Product resource. + */ + policySid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + status: TrustProductsStatus; + /** + * The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format until which the resource will be valid. + */ + validUntil: Date; + /** + * The email address that will receive updates when the Trust Product resource changes status. + */ + email: string; + /** + * The URL we call to inform your application of status changes. + */ + statusCallback: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Trust Product resource. + */ + url: string; + /** + * The URLs of the Assigned Items of the Trust Product resource. + */ + links: Record<string, string>; + /** + * The error codes associated with the rejection of the Trust Product. + */ + errors: Array<any>; + + private get _proxy(): TrustProductsContext { + this._context = this._context || new TrustProductsContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a TrustProductsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TrustProductsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TrustProductsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance + */ + fetch(callback?: (error: Error | null, item?: TrustProductsInstance) => any): Promise<TrustProductsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TrustProductsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TrustProductsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance + */ + update(callback?: (error: Error | null, item?: TrustProductsInstance) => any): Promise<TrustProductsInstance>; + /** + * Update a TrustProductsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance + */ + update(params: TrustProductsContextUpdateOptions, callback?: (error: Error | null, item?: TrustProductsInstance) => any): Promise<TrustProductsInstance>; + + update(params?: any, callback?: (error: Error | null, item?: TrustProductsInstance) => any): Promise<TrustProductsInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a TrustProductsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>>; + /** + * Update a TrustProductsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance with HTTP metadata + */ + updateWithHttpInfo(params: TrustProductsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the trustProductsChannelEndpointAssignment. + */ + trustProductsChannelEndpointAssignment(): TrustProductsChannelEndpointAssignmentListInstance { + return this._proxy.trustProductsChannelEndpointAssignment; + } + + /** + * Access the trustProductsEntityAssignments. + */ + trustProductsEntityAssignments(): TrustProductsEntityAssignmentsListInstance { + return this._proxy.trustProductsEntityAssignments; + } + + /** + * Access the trustProductsEvaluations. + */ + trustProductsEvaluations(): TrustProductsEvaluationsListInstance { + return this._proxy.trustProductsEvaluations; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + policySid: this.policySid, + friendlyName: this.friendlyName, + status: this.status, + validUntil: this.validUntil, + email: this.email, + statusCallback: this.statusCallback, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + errors: this.errors, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TrustProductsSolution { +} + +export interface TrustProductsListInstance { + _version: V1; + _solution: TrustProductsSolution; + _uri: string; + + (sid: string, ): TrustProductsContext; + get(sid: string, ): TrustProductsContext; + + + + + + + + + /** + * Create a TrustProductsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance + */ + create(params: TrustProductsListInstanceCreateOptions, callback?: (error: Error | null, item?: TrustProductsInstance) => any): Promise<TrustProductsInstance>; + + /** + * Create a TrustProductsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsInstance with HTTP metadata + */ + createWithHttpInfo(params: TrustProductsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>>; + + + + + /** + * Streams TrustProductsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TrustProductsInstance, done: (err?: Error) => void) => void): void; + each(params: TrustProductsListInstanceEachOptions, callback?: (item: TrustProductsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TrustProductsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TrustProductsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TrustProductsListInstanceEachOptions, callback?: (item: TrustProductsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TrustProductsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TrustProductsPage) => any): Promise<TrustProductsPage>; + /** + * Retrieve a single target page of TrustProductsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TrustProductsPage>) => any): Promise<ApiResponse<TrustProductsPage>>; + /** + * Lists TrustProductsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TrustProductsInstance[]) => any): Promise<TrustProductsInstance[]>; + list(params: TrustProductsListInstanceOptions, callback?: (error: Error | null, items: TrustProductsInstance[]) => any): Promise<TrustProductsInstance[]>; + /** + * Lists TrustProductsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TrustProductsInstance[]>) => any): Promise<ApiResponse<TrustProductsInstance[]>>; + listWithHttpInfo(params: TrustProductsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsInstance[]>) => any): Promise<ApiResponse<TrustProductsInstance[]>>; + /** + * Retrieve a single page of TrustProductsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TrustProductsPage) => any): Promise<TrustProductsPage>; + page(params: TrustProductsListInstancePageOptions, callback?: (error: Error | null, items: TrustProductsPage) => any): Promise<TrustProductsPage>; + /** + * Retrieve a single page of TrustProductsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TrustProductsPage>) => any): Promise<ApiResponse<TrustProductsPage>>; + pageWithHttpInfo(params: TrustProductsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsPage>) => any): Promise<ApiResponse<TrustProductsPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TrustProductsListInstance(version: V1): TrustProductsListInstance { + const instance = ((sid, ) => instance.get(sid, )) as TrustProductsListInstance; + + instance.get = function get(sid, ): TrustProductsContext { + return new TrustProductsContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/TrustProducts`; + + instance.create = function create(params: TrustProductsListInstanceCreateOptions, callback?: (error: Error | null, items: TrustProductsInstance) => any): Promise<TrustProductsInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + if (params["policySid"] === null || params["policySid"] === undefined) { + throw new Error('Required parameter "params[\'policySid\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Email"] = params["email"]; + + data["PolicySid"] = params["policySid"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TrustProductsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsInstance>) => any): Promise<ApiResponse<TrustProductsInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["email"] === null || params["email"] === undefined) { + throw new Error('Required parameter "params[\'email\']" missing.'); + } + + if (params["policySid"] === null || params["policySid"] === undefined) { + throw new Error('Required parameter "params[\'policySid\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["Email"] = params["email"]; + + data["PolicySid"] = params["policySid"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TrustProductsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TrustProductsInstance> => ({ + ...response, + body: new TrustProductsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TrustProductsListInstancePageOptions | ((error: Error | null, items: TrustProductsPage) => any), callback?: (error: Error | null, items: TrustProductsPage) => any): Promise<TrustProductsPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["policySid"] !== undefined) + data["PolicySid"] = params["policySid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TrustProductsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TrustProductsPage) => any): Promise<TrustProductsPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TrustProductsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TrustProductsListInstancePageOptions | ((error: Error | null, items: ApiResponse<TrustProductsPage>) => any), callback?: (error: Error | null, items: ApiResponse<TrustProductsPage>) => any): Promise<ApiResponse<TrustProductsPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["policySid"] !== undefined) + data["PolicySid"] = params["policySid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TrustProductsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TrustProductsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TrustProductsPage>) => any): Promise<ApiResponse<TrustProductsPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TrustProductsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TrustProductsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TrustProductsPage extends Page<V1, TrustProductsPayload, TrustProductsResource, TrustProductsInstance> { +/** +* Initialize the TrustProductsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TrustProductsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TrustProductsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TrustProductsResource): TrustProductsInstance { + + return new TrustProductsInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/trustProducts/trustProductsChannelEndpointAssignment.ts b/rest/trusthub/v1/trustProducts/trustProductsChannelEndpointAssignment.ts new file mode 100644 index 000000000..372c2977e --- /dev/null +++ b/rest/trusthub/v1/trustProducts/trustProductsChannelEndpointAssignment.ts @@ -0,0 +1,780 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a TrustProductsChannelEndpointAssignmentInstance + */ +export interface TrustProductsChannelEndpointAssignmentListInstanceCreateOptions { + /** The type of channel endpoint. eg: phone-number */ + "channelEndpointType": string; + /** The SID of an channel endpoint */ + "channelEndpointSid": string; +} + +/** + * Options to pass to each + */ +export interface TrustProductsChannelEndpointAssignmentListInstanceEachOptions { + /** The SID of an channel endpoint */ + "channelEndpointSid"?: string; + /** comma separated list of channel endpoint sids */ + "channelEndpointSids"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TrustProductsChannelEndpointAssignmentInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TrustProductsChannelEndpointAssignmentListInstanceOptions { + /** The SID of an channel endpoint */ + "channelEndpointSid"?: string; + /** comma separated list of channel endpoint sids */ + "channelEndpointSids"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TrustProductsChannelEndpointAssignmentListInstancePageOptions { + /** The SID of an channel endpoint */ + "channelEndpointSid"?: string; + /** comma separated list of channel endpoint sids */ + "channelEndpointSids"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TrustProductsChannelEndpointAssignmentContext { + + /** + * Remove a TrustProductsChannelEndpointAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a TrustProductsChannelEndpointAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a TrustProductsChannelEndpointAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsChannelEndpointAssignmentInstance + */ + fetch(callback?: (error: Error | null, item?: TrustProductsChannelEndpointAssignmentInstance) => any): Promise<TrustProductsChannelEndpointAssignmentInstance> + + /** + * Fetch a TrustProductsChannelEndpointAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsChannelEndpointAssignmentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsChannelEndpointAssignmentInstance>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TrustProductsChannelEndpointAssignmentContextSolution { + "trustProductSid": string; + "sid": string; +} + +export class TrustProductsChannelEndpointAssignmentContextImpl implements TrustProductsChannelEndpointAssignmentContext { + protected _solution: TrustProductsChannelEndpointAssignmentContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, trustProductSid: string, sid: string) { + if (!isValidPathParam(trustProductSid)) { + throw new Error('Parameter \'trustProductSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { trustProductSid, sid, }; + this._uri = `/TrustProducts/${trustProductSid}/ChannelEndpointAssignments/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TrustProductsChannelEndpointAssignmentInstance) => any): Promise<TrustProductsChannelEndpointAssignmentInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsChannelEndpointAssignmentInstance(operationVersion, payload, instance._solution.trustProductSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsChannelEndpointAssignmentInstance>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TrustProductsChannelEndpointAssignmentResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TrustProductsChannelEndpointAssignmentInstance> => ({ + ...response, + body: new TrustProductsChannelEndpointAssignmentInstance(operationVersion, response.body, instance._solution.trustProductSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TrustProductsChannelEndpointAssignmentPayload extends TwilioResponsePayload { + results: TrustProductsChannelEndpointAssignmentResource[]; +} + +interface TrustProductsChannelEndpointAssignmentResource { + sid: string; + trust_product_sid: string; + account_sid: string; + channel_endpoint_type: string; + channel_endpoint_sid: string; + date_created: Date; + url: string; +} + +export class TrustProductsChannelEndpointAssignmentInstance { + protected _solution: TrustProductsChannelEndpointAssignmentContextSolution; + protected _context?: TrustProductsChannelEndpointAssignmentContext; + + constructor(protected _version: V1, payload: TrustProductsChannelEndpointAssignmentResource, trustProductSid: string, sid?: string) { + + this.sid = (payload.sid); + this.trustProductSid = (payload.trust_product_sid); + this.accountSid = (payload.account_sid); + this.channelEndpointType = (payload.channel_endpoint_type); + this.channelEndpointSid = (payload.channel_endpoint_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { trustProductSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Item Assignment resource. + */ + sid: string; + /** + * The unique string that we created to identify the CustomerProfile resource. + */ + trustProductSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + */ + accountSid: string; + /** + * The type of channel endpoint. eg: phone-number + */ + channelEndpointType: string; + /** + * The SID of an channel endpoint + */ + channelEndpointSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Identity resource. + */ + url: string; + + private get _proxy(): TrustProductsChannelEndpointAssignmentContext { + this._context = this._context || new TrustProductsChannelEndpointAssignmentContextImpl(this._version, this._solution.trustProductSid, this._solution.sid); + return this._context; + } + + /** + * Remove a TrustProductsChannelEndpointAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TrustProductsChannelEndpointAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TrustProductsChannelEndpointAssignmentInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsChannelEndpointAssignmentInstance + */ + fetch(callback?: (error: Error | null, item?: TrustProductsChannelEndpointAssignmentInstance) => any): Promise<TrustProductsChannelEndpointAssignmentInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TrustProductsChannelEndpointAssignmentInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsChannelEndpointAssignmentInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsChannelEndpointAssignmentInstance>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + trustProductSid: this.trustProductSid, + accountSid: this.accountSid, + channelEndpointType: this.channelEndpointType, + channelEndpointSid: this.channelEndpointSid, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TrustProductsChannelEndpointAssignmentSolution { + trustProductSid: string; +} + +export interface TrustProductsChannelEndpointAssignmentListInstance { + _version: V1; + _solution: TrustProductsChannelEndpointAssignmentSolution; + _uri: string; + + (sid: string, ): TrustProductsChannelEndpointAssignmentContext; + get(sid: string, ): TrustProductsChannelEndpointAssignmentContext; + + + + + + + /** + * Create a TrustProductsChannelEndpointAssignmentInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsChannelEndpointAssignmentInstance + */ + create(params: TrustProductsChannelEndpointAssignmentListInstanceCreateOptions, callback?: (error: Error | null, item?: TrustProductsChannelEndpointAssignmentInstance) => any): Promise<TrustProductsChannelEndpointAssignmentInstance>; + + /** + * Create a TrustProductsChannelEndpointAssignmentInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsChannelEndpointAssignmentInstance with HTTP metadata + */ + createWithHttpInfo(params: TrustProductsChannelEndpointAssignmentListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TrustProductsChannelEndpointAssignmentInstance>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentInstance>>; + + + + + /** + * Streams TrustProductsChannelEndpointAssignmentInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsChannelEndpointAssignmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TrustProductsChannelEndpointAssignmentInstance, done: (err?: Error) => void) => void): void; + each(params: TrustProductsChannelEndpointAssignmentListInstanceEachOptions, callback?: (item: TrustProductsChannelEndpointAssignmentInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TrustProductsChannelEndpointAssignmentInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsChannelEndpointAssignmentListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TrustProductsChannelEndpointAssignmentInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TrustProductsChannelEndpointAssignmentListInstanceEachOptions, callback?: (item: TrustProductsChannelEndpointAssignmentInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TrustProductsChannelEndpointAssignmentInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TrustProductsChannelEndpointAssignmentPage) => any): Promise<TrustProductsChannelEndpointAssignmentPage>; + /** + * Retrieve a single target page of TrustProductsChannelEndpointAssignmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TrustProductsChannelEndpointAssignmentPage>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentPage>>; + /** + * Lists TrustProductsChannelEndpointAssignmentInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsChannelEndpointAssignmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TrustProductsChannelEndpointAssignmentInstance[]) => any): Promise<TrustProductsChannelEndpointAssignmentInstance[]>; + list(params: TrustProductsChannelEndpointAssignmentListInstanceOptions, callback?: (error: Error | null, items: TrustProductsChannelEndpointAssignmentInstance[]) => any): Promise<TrustProductsChannelEndpointAssignmentInstance[]>; + /** + * Lists TrustProductsChannelEndpointAssignmentInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsChannelEndpointAssignmentListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TrustProductsChannelEndpointAssignmentInstance[]>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentInstance[]>>; + listWithHttpInfo(params: TrustProductsChannelEndpointAssignmentListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsChannelEndpointAssignmentInstance[]>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentInstance[]>>; + /** + * Retrieve a single page of TrustProductsChannelEndpointAssignmentInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsChannelEndpointAssignmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TrustProductsChannelEndpointAssignmentPage) => any): Promise<TrustProductsChannelEndpointAssignmentPage>; + page(params: TrustProductsChannelEndpointAssignmentListInstancePageOptions, callback?: (error: Error | null, items: TrustProductsChannelEndpointAssignmentPage) => any): Promise<TrustProductsChannelEndpointAssignmentPage>; + /** + * Retrieve a single page of TrustProductsChannelEndpointAssignmentInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsChannelEndpointAssignmentListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TrustProductsChannelEndpointAssignmentPage>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentPage>>; + pageWithHttpInfo(params: TrustProductsChannelEndpointAssignmentListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsChannelEndpointAssignmentPage>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TrustProductsChannelEndpointAssignmentListInstance(version: V1, trustProductSid: string): TrustProductsChannelEndpointAssignmentListInstance { + if (!isValidPathParam(trustProductSid)) { + throw new Error('Parameter \'trustProductSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as TrustProductsChannelEndpointAssignmentListInstance; + + instance.get = function get(sid, ): TrustProductsChannelEndpointAssignmentContext { + return new TrustProductsChannelEndpointAssignmentContextImpl(version, trustProductSid, sid); + } + + instance._version = version; + instance._solution = { trustProductSid, }; + instance._uri = `/TrustProducts/${trustProductSid}/ChannelEndpointAssignments`; + + instance.create = function create(params: TrustProductsChannelEndpointAssignmentListInstanceCreateOptions, callback?: (error: Error | null, items: TrustProductsChannelEndpointAssignmentInstance) => any): Promise<TrustProductsChannelEndpointAssignmentInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["channelEndpointType"] === null || params["channelEndpointType"] === undefined) { + throw new Error('Required parameter "params[\'channelEndpointType\']" missing.'); + } + + if (params["channelEndpointSid"] === null || params["channelEndpointSid"] === undefined) { + throw new Error('Required parameter "params[\'channelEndpointSid\']" missing.'); + } + + let data: any = {}; + + + + data["ChannelEndpointType"] = params["channelEndpointType"]; + + data["ChannelEndpointSid"] = params["channelEndpointSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsChannelEndpointAssignmentInstance(operationVersion, payload, instance._solution.trustProductSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TrustProductsChannelEndpointAssignmentListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsChannelEndpointAssignmentInstance>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["channelEndpointType"] === null || params["channelEndpointType"] === undefined) { + throw new Error('Required parameter "params[\'channelEndpointType\']" missing.'); + } + + if (params["channelEndpointSid"] === null || params["channelEndpointSid"] === undefined) { + throw new Error('Required parameter "params[\'channelEndpointSid\']" missing.'); + } + + let data: any = {}; + + + + data["ChannelEndpointType"] = params["channelEndpointType"]; + + data["ChannelEndpointSid"] = params["channelEndpointSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TrustProductsChannelEndpointAssignmentResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TrustProductsChannelEndpointAssignmentInstance> => ({ + ...response, + body: new TrustProductsChannelEndpointAssignmentInstance(operationVersion, response.body, instance._solution.trustProductSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TrustProductsChannelEndpointAssignmentListInstancePageOptions | ((error: Error | null, items: TrustProductsChannelEndpointAssignmentPage) => any), callback?: (error: Error | null, items: TrustProductsChannelEndpointAssignmentPage) => any): Promise<TrustProductsChannelEndpointAssignmentPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["channelEndpointSid"] !== undefined) + data["ChannelEndpointSid"] = params["channelEndpointSid"]; + if (params["channelEndpointSids"] !== undefined) + data["ChannelEndpointSids"] = params["channelEndpointSids"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TrustProductsChannelEndpointAssignmentPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TrustProductsChannelEndpointAssignmentPage) => any): Promise<TrustProductsChannelEndpointAssignmentPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TrustProductsChannelEndpointAssignmentPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TrustProductsChannelEndpointAssignmentListInstancePageOptions | ((error: Error | null, items: ApiResponse<TrustProductsChannelEndpointAssignmentPage>) => any), callback?: (error: Error | null, items: ApiResponse<TrustProductsChannelEndpointAssignmentPage>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["channelEndpointSid"] !== undefined) + data["ChannelEndpointSid"] = params["channelEndpointSid"]; + if (params["channelEndpointSids"] !== undefined) + data["ChannelEndpointSids"] = params["channelEndpointSids"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TrustProductsChannelEndpointAssignmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TrustProductsChannelEndpointAssignmentPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TrustProductsChannelEndpointAssignmentPage>) => any): Promise<ApiResponse<TrustProductsChannelEndpointAssignmentPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TrustProductsChannelEndpointAssignmentPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TrustProductsChannelEndpointAssignmentPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TrustProductsChannelEndpointAssignmentPage extends Page<V1, TrustProductsChannelEndpointAssignmentPayload, TrustProductsChannelEndpointAssignmentResource, TrustProductsChannelEndpointAssignmentInstance> { +/** +* Initialize the TrustProductsChannelEndpointAssignmentPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TrustProductsChannelEndpointAssignmentSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TrustProductsChannelEndpointAssignmentInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TrustProductsChannelEndpointAssignmentResource): TrustProductsChannelEndpointAssignmentInstance { + + return new TrustProductsChannelEndpointAssignmentInstance( + this._version, + payload, + this._solution.trustProductSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/trustProducts/trustProductsEntityAssignments.ts b/rest/trusthub/v1/trustProducts/trustProductsEntityAssignments.ts new file mode 100644 index 000000000..5a8d39356 --- /dev/null +++ b/rest/trusthub/v1/trustProducts/trustProductsEntityAssignments.ts @@ -0,0 +1,749 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a TrustProductsEntityAssignmentsInstance + */ +export interface TrustProductsEntityAssignmentsListInstanceCreateOptions { + /** The SID of an object bag that holds information of the different items. */ + "objectSid": string; +} + +/** + * Options to pass to each + */ +export interface TrustProductsEntityAssignmentsListInstanceEachOptions { + /** A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. */ + "objectType"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TrustProductsEntityAssignmentsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TrustProductsEntityAssignmentsListInstanceOptions { + /** A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. */ + "objectType"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TrustProductsEntityAssignmentsListInstancePageOptions { + /** A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. */ + "objectType"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TrustProductsEntityAssignmentsContext { + + /** + * Remove a TrustProductsEntityAssignmentsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a TrustProductsEntityAssignmentsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a TrustProductsEntityAssignmentsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEntityAssignmentsInstance + */ + fetch(callback?: (error: Error | null, item?: TrustProductsEntityAssignmentsInstance) => any): Promise<TrustProductsEntityAssignmentsInstance> + + /** + * Fetch a TrustProductsEntityAssignmentsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEntityAssignmentsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsEntityAssignmentsInstance>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TrustProductsEntityAssignmentsContextSolution { + "trustProductSid": string; + "sid": string; +} + +export class TrustProductsEntityAssignmentsContextImpl implements TrustProductsEntityAssignmentsContext { + protected _solution: TrustProductsEntityAssignmentsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, trustProductSid: string, sid: string) { + if (!isValidPathParam(trustProductSid)) { + throw new Error('Parameter \'trustProductSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { trustProductSid, sid, }; + this._uri = `/TrustProducts/${trustProductSid}/EntityAssignments/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TrustProductsEntityAssignmentsInstance) => any): Promise<TrustProductsEntityAssignmentsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsEntityAssignmentsInstance(operationVersion, payload, instance._solution.trustProductSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsEntityAssignmentsInstance>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TrustProductsEntityAssignmentsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TrustProductsEntityAssignmentsInstance> => ({ + ...response, + body: new TrustProductsEntityAssignmentsInstance(operationVersion, response.body, instance._solution.trustProductSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TrustProductsEntityAssignmentsPayload extends TwilioResponsePayload { + results: TrustProductsEntityAssignmentsResource[]; +} + +interface TrustProductsEntityAssignmentsResource { + sid: string; + trust_product_sid: string; + account_sid: string; + object_sid: string; + date_created: Date; + url: string; +} + +export class TrustProductsEntityAssignmentsInstance { + protected _solution: TrustProductsEntityAssignmentsContextSolution; + protected _context?: TrustProductsEntityAssignmentsContext; + + constructor(protected _version: V1, payload: TrustProductsEntityAssignmentsResource, trustProductSid: string, sid?: string) { + + this.sid = (payload.sid); + this.trustProductSid = (payload.trust_product_sid); + this.accountSid = (payload.account_sid); + this.objectSid = (payload.object_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { trustProductSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Item Assignment resource. + */ + sid: string; + /** + * The unique string that we created to identify the TrustProduct resource. + */ + trustProductSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + */ + accountSid: string; + /** + * The SID of an object bag that holds information of the different items. + */ + objectSid: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The absolute URL of the Identity resource. + */ + url: string; + + private get _proxy(): TrustProductsEntityAssignmentsContext { + this._context = this._context || new TrustProductsEntityAssignmentsContextImpl(this._version, this._solution.trustProductSid, this._solution.sid); + return this._context; + } + + /** + * Remove a TrustProductsEntityAssignmentsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TrustProductsEntityAssignmentsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TrustProductsEntityAssignmentsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEntityAssignmentsInstance + */ + fetch(callback?: (error: Error | null, item?: TrustProductsEntityAssignmentsInstance) => any): Promise<TrustProductsEntityAssignmentsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TrustProductsEntityAssignmentsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEntityAssignmentsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsEntityAssignmentsInstance>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + trustProductSid: this.trustProductSid, + accountSid: this.accountSid, + objectSid: this.objectSid, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TrustProductsEntityAssignmentsSolution { + trustProductSid: string; +} + +export interface TrustProductsEntityAssignmentsListInstance { + _version: V1; + _solution: TrustProductsEntityAssignmentsSolution; + _uri: string; + + (sid: string, ): TrustProductsEntityAssignmentsContext; + get(sid: string, ): TrustProductsEntityAssignmentsContext; + + + + + + + /** + * Create a TrustProductsEntityAssignmentsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEntityAssignmentsInstance + */ + create(params: TrustProductsEntityAssignmentsListInstanceCreateOptions, callback?: (error: Error | null, item?: TrustProductsEntityAssignmentsInstance) => any): Promise<TrustProductsEntityAssignmentsInstance>; + + /** + * Create a TrustProductsEntityAssignmentsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEntityAssignmentsInstance with HTTP metadata + */ + createWithHttpInfo(params: TrustProductsEntityAssignmentsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TrustProductsEntityAssignmentsInstance>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsInstance>>; + + + + + /** + * Streams TrustProductsEntityAssignmentsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEntityAssignmentsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TrustProductsEntityAssignmentsInstance, done: (err?: Error) => void) => void): void; + each(params: TrustProductsEntityAssignmentsListInstanceEachOptions, callback?: (item: TrustProductsEntityAssignmentsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TrustProductsEntityAssignmentsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEntityAssignmentsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TrustProductsEntityAssignmentsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TrustProductsEntityAssignmentsListInstanceEachOptions, callback?: (item: TrustProductsEntityAssignmentsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TrustProductsEntityAssignmentsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TrustProductsEntityAssignmentsPage) => any): Promise<TrustProductsEntityAssignmentsPage>; + /** + * Retrieve a single target page of TrustProductsEntityAssignmentsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TrustProductsEntityAssignmentsPage>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsPage>>; + /** + * Lists TrustProductsEntityAssignmentsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEntityAssignmentsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TrustProductsEntityAssignmentsInstance[]) => any): Promise<TrustProductsEntityAssignmentsInstance[]>; + list(params: TrustProductsEntityAssignmentsListInstanceOptions, callback?: (error: Error | null, items: TrustProductsEntityAssignmentsInstance[]) => any): Promise<TrustProductsEntityAssignmentsInstance[]>; + /** + * Lists TrustProductsEntityAssignmentsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEntityAssignmentsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TrustProductsEntityAssignmentsInstance[]>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsInstance[]>>; + listWithHttpInfo(params: TrustProductsEntityAssignmentsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsEntityAssignmentsInstance[]>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsInstance[]>>; + /** + * Retrieve a single page of TrustProductsEntityAssignmentsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEntityAssignmentsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TrustProductsEntityAssignmentsPage) => any): Promise<TrustProductsEntityAssignmentsPage>; + page(params: TrustProductsEntityAssignmentsListInstancePageOptions, callback?: (error: Error | null, items: TrustProductsEntityAssignmentsPage) => any): Promise<TrustProductsEntityAssignmentsPage>; + /** + * Retrieve a single page of TrustProductsEntityAssignmentsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEntityAssignmentsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TrustProductsEntityAssignmentsPage>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsPage>>; + pageWithHttpInfo(params: TrustProductsEntityAssignmentsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsEntityAssignmentsPage>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TrustProductsEntityAssignmentsListInstance(version: V1, trustProductSid: string): TrustProductsEntityAssignmentsListInstance { + if (!isValidPathParam(trustProductSid)) { + throw new Error('Parameter \'trustProductSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as TrustProductsEntityAssignmentsListInstance; + + instance.get = function get(sid, ): TrustProductsEntityAssignmentsContext { + return new TrustProductsEntityAssignmentsContextImpl(version, trustProductSid, sid); + } + + instance._version = version; + instance._solution = { trustProductSid, }; + instance._uri = `/TrustProducts/${trustProductSid}/EntityAssignments`; + + instance.create = function create(params: TrustProductsEntityAssignmentsListInstanceCreateOptions, callback?: (error: Error | null, items: TrustProductsEntityAssignmentsInstance) => any): Promise<TrustProductsEntityAssignmentsInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["objectSid"] === null || params["objectSid"] === undefined) { + throw new Error('Required parameter "params[\'objectSid\']" missing.'); + } + + let data: any = {}; + + + + data["ObjectSid"] = params["objectSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsEntityAssignmentsInstance(operationVersion, payload, instance._solution.trustProductSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TrustProductsEntityAssignmentsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsEntityAssignmentsInstance>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["objectSid"] === null || params["objectSid"] === undefined) { + throw new Error('Required parameter "params[\'objectSid\']" missing.'); + } + + let data: any = {}; + + + + data["ObjectSid"] = params["objectSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TrustProductsEntityAssignmentsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TrustProductsEntityAssignmentsInstance> => ({ + ...response, + body: new TrustProductsEntityAssignmentsInstance(operationVersion, response.body, instance._solution.trustProductSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TrustProductsEntityAssignmentsListInstancePageOptions | ((error: Error | null, items: TrustProductsEntityAssignmentsPage) => any), callback?: (error: Error | null, items: TrustProductsEntityAssignmentsPage) => any): Promise<TrustProductsEntityAssignmentsPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["objectType"] !== undefined) + data["ObjectType"] = params["objectType"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TrustProductsEntityAssignmentsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TrustProductsEntityAssignmentsPage) => any): Promise<TrustProductsEntityAssignmentsPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TrustProductsEntityAssignmentsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TrustProductsEntityAssignmentsListInstancePageOptions | ((error: Error | null, items: ApiResponse<TrustProductsEntityAssignmentsPage>) => any), callback?: (error: Error | null, items: ApiResponse<TrustProductsEntityAssignmentsPage>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["objectType"] !== undefined) + data["ObjectType"] = params["objectType"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TrustProductsEntityAssignmentsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TrustProductsEntityAssignmentsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TrustProductsEntityAssignmentsPage>) => any): Promise<ApiResponse<TrustProductsEntityAssignmentsPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TrustProductsEntityAssignmentsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TrustProductsEntityAssignmentsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TrustProductsEntityAssignmentsPage extends Page<V1, TrustProductsEntityAssignmentsPayload, TrustProductsEntityAssignmentsResource, TrustProductsEntityAssignmentsInstance> { +/** +* Initialize the TrustProductsEntityAssignmentsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TrustProductsEntityAssignmentsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TrustProductsEntityAssignmentsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TrustProductsEntityAssignmentsResource): TrustProductsEntityAssignmentsInstance { + + return new TrustProductsEntityAssignmentsInstance( + this._version, + payload, + this._solution.trustProductSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/trustProducts/trustProductsEvaluations.ts b/rest/trusthub/v1/trustProducts/trustProductsEvaluations.ts new file mode 100644 index 000000000..7488a1e8b --- /dev/null +++ b/rest/trusthub/v1/trustProducts/trustProductsEvaluations.ts @@ -0,0 +1,671 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The compliance status of the Evaluation resource. + */ +export type TrustProductsEvaluationsStatus = 'compliant'|'noncompliant'; + + + +/** + * Options to pass to create a TrustProductsEvaluationsInstance + */ +export interface TrustProductsEvaluationsListInstanceCreateOptions { + /** The unique string of a policy that is associated to the customer_profile resource. */ + "policySid": string; +} + +/** + * Options to pass to each + */ +export interface TrustProductsEvaluationsListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TrustProductsEvaluationsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TrustProductsEvaluationsListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TrustProductsEvaluationsListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TrustProductsEvaluationsContext { + + /** + * Fetch a TrustProductsEvaluationsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEvaluationsInstance + */ + fetch(callback?: (error: Error | null, item?: TrustProductsEvaluationsInstance) => any): Promise<TrustProductsEvaluationsInstance> + + /** + * Fetch a TrustProductsEvaluationsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEvaluationsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsEvaluationsInstance>) => any): Promise<ApiResponse<TrustProductsEvaluationsInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TrustProductsEvaluationsContextSolution { + "trustProductSid": string; + "sid": string; +} + +export class TrustProductsEvaluationsContextImpl implements TrustProductsEvaluationsContext { + protected _solution: TrustProductsEvaluationsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, trustProductSid: string, sid: string) { + if (!isValidPathParam(trustProductSid)) { + throw new Error('Parameter \'trustProductSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { trustProductSid, sid, }; + this._uri = `/TrustProducts/${trustProductSid}/Evaluations/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: TrustProductsEvaluationsInstance) => any): Promise<TrustProductsEvaluationsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsEvaluationsInstance(operationVersion, payload, instance._solution.trustProductSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsEvaluationsInstance>) => any): Promise<ApiResponse<TrustProductsEvaluationsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TrustProductsEvaluationsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TrustProductsEvaluationsInstance> => ({ + ...response, + body: new TrustProductsEvaluationsInstance(operationVersion, response.body, instance._solution.trustProductSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TrustProductsEvaluationsPayload extends TwilioResponsePayload { + results: TrustProductsEvaluationsResource[]; +} + +interface TrustProductsEvaluationsResource { + sid: string; + account_sid: string; + policy_sid: string; + trust_product_sid: string; + status: TrustProductsEvaluationsStatus; + results: Array<any>; + date_created: Date; + url: string; +} + +export class TrustProductsEvaluationsInstance { + protected _solution: TrustProductsEvaluationsContextSolution; + protected _context?: TrustProductsEvaluationsContext; + + constructor(protected _version: V1, payload: TrustProductsEvaluationsResource, trustProductSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.policySid = (payload.policy_sid); + this.trustProductSid = (payload.trust_product_sid); + this.status = payload.status; + this.results = (payload.results); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.url = (payload.url); + + this._solution = { trustProductSid, sid: sid, }; + } + + /** + * The unique string that identifies the Evaluation resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the trust_product resource. + */ + accountSid: string; + /** + * The unique string of a policy that is associated to the trust_product resource. + */ + policySid: string; + /** + * The unique string that we created to identify the trust_product resource. + */ + trustProductSid: string; + status: TrustProductsEvaluationsStatus; + /** + * The results of the Evaluation which includes the valid and invalid attributes. + */ + results: Array<any>; + dateCreated: Date; + url: string; + + private get _proxy(): TrustProductsEvaluationsContext { + this._context = this._context || new TrustProductsEvaluationsContextImpl(this._version, this._solution.trustProductSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a TrustProductsEvaluationsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEvaluationsInstance + */ + fetch(callback?: (error: Error | null, item?: TrustProductsEvaluationsInstance) => any): Promise<TrustProductsEvaluationsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TrustProductsEvaluationsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEvaluationsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsEvaluationsInstance>) => any): Promise<ApiResponse<TrustProductsEvaluationsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + policySid: this.policySid, + trustProductSid: this.trustProductSid, + status: this.status, + results: this.results, + dateCreated: this.dateCreated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TrustProductsEvaluationsSolution { + trustProductSid: string; +} + +export interface TrustProductsEvaluationsListInstance { + _version: V1; + _solution: TrustProductsEvaluationsSolution; + _uri: string; + + (sid: string, ): TrustProductsEvaluationsContext; + get(sid: string, ): TrustProductsEvaluationsContext; + + + + + /** + * Create a TrustProductsEvaluationsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEvaluationsInstance + */ + create(params: TrustProductsEvaluationsListInstanceCreateOptions, callback?: (error: Error | null, item?: TrustProductsEvaluationsInstance) => any): Promise<TrustProductsEvaluationsInstance>; + + /** + * Create a TrustProductsEvaluationsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsEvaluationsInstance with HTTP metadata + */ + createWithHttpInfo(params: TrustProductsEvaluationsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TrustProductsEvaluationsInstance>) => any): Promise<ApiResponse<TrustProductsEvaluationsInstance>>; + + + + + /** + * Streams TrustProductsEvaluationsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEvaluationsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TrustProductsEvaluationsInstance, done: (err?: Error) => void) => void): void; + each(params: TrustProductsEvaluationsListInstanceEachOptions, callback?: (item: TrustProductsEvaluationsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TrustProductsEvaluationsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEvaluationsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TrustProductsEvaluationsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TrustProductsEvaluationsListInstanceEachOptions, callback?: (item: TrustProductsEvaluationsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TrustProductsEvaluationsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TrustProductsEvaluationsPage) => any): Promise<TrustProductsEvaluationsPage>; + /** + * Retrieve a single target page of TrustProductsEvaluationsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TrustProductsEvaluationsPage>) => any): Promise<ApiResponse<TrustProductsEvaluationsPage>>; + /** + * Lists TrustProductsEvaluationsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEvaluationsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TrustProductsEvaluationsInstance[]) => any): Promise<TrustProductsEvaluationsInstance[]>; + list(params: TrustProductsEvaluationsListInstanceOptions, callback?: (error: Error | null, items: TrustProductsEvaluationsInstance[]) => any): Promise<TrustProductsEvaluationsInstance[]>; + /** + * Lists TrustProductsEvaluationsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEvaluationsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TrustProductsEvaluationsInstance[]>) => any): Promise<ApiResponse<TrustProductsEvaluationsInstance[]>>; + listWithHttpInfo(params: TrustProductsEvaluationsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsEvaluationsInstance[]>) => any): Promise<ApiResponse<TrustProductsEvaluationsInstance[]>>; + /** + * Retrieve a single page of TrustProductsEvaluationsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEvaluationsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TrustProductsEvaluationsPage) => any): Promise<TrustProductsEvaluationsPage>; + page(params: TrustProductsEvaluationsListInstancePageOptions, callback?: (error: Error | null, items: TrustProductsEvaluationsPage) => any): Promise<TrustProductsEvaluationsPage>; + /** + * Retrieve a single page of TrustProductsEvaluationsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TrustProductsEvaluationsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TrustProductsEvaluationsPage>) => any): Promise<ApiResponse<TrustProductsEvaluationsPage>>; + pageWithHttpInfo(params: TrustProductsEvaluationsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsEvaluationsPage>) => any): Promise<ApiResponse<TrustProductsEvaluationsPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TrustProductsEvaluationsListInstance(version: V1, trustProductSid: string): TrustProductsEvaluationsListInstance { + if (!isValidPathParam(trustProductSid)) { + throw new Error('Parameter \'trustProductSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as TrustProductsEvaluationsListInstance; + + instance.get = function get(sid, ): TrustProductsEvaluationsContext { + return new TrustProductsEvaluationsContextImpl(version, trustProductSid, sid); + } + + instance._version = version; + instance._solution = { trustProductSid, }; + instance._uri = `/TrustProducts/${trustProductSid}/Evaluations`; + + instance.create = function create(params: TrustProductsEvaluationsListInstanceCreateOptions, callback?: (error: Error | null, items: TrustProductsEvaluationsInstance) => any): Promise<TrustProductsEvaluationsInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["policySid"] === null || params["policySid"] === undefined) { + throw new Error('Required parameter "params[\'policySid\']" missing.'); + } + + let data: any = {}; + + + + data["PolicySid"] = params["policySid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsEvaluationsInstance(operationVersion, payload, instance._solution.trustProductSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: TrustProductsEvaluationsListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<TrustProductsEvaluationsInstance>) => any): Promise<ApiResponse<TrustProductsEvaluationsInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["policySid"] === null || params["policySid"] === undefined) { + throw new Error('Required parameter "params[\'policySid\']" missing.'); + } + + let data: any = {}; + + + + data["PolicySid"] = params["policySid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TrustProductsEvaluationsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TrustProductsEvaluationsInstance> => ({ + ...response, + body: new TrustProductsEvaluationsInstance(operationVersion, response.body, instance._solution.trustProductSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TrustProductsEvaluationsListInstancePageOptions | ((error: Error | null, items: TrustProductsEvaluationsPage) => any), callback?: (error: Error | null, items: TrustProductsEvaluationsPage) => any): Promise<TrustProductsEvaluationsPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TrustProductsEvaluationsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TrustProductsEvaluationsPage) => any): Promise<TrustProductsEvaluationsPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TrustProductsEvaluationsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TrustProductsEvaluationsListInstancePageOptions | ((error: Error | null, items: ApiResponse<TrustProductsEvaluationsPage>) => any), callback?: (error: Error | null, items: ApiResponse<TrustProductsEvaluationsPage>) => any): Promise<ApiResponse<TrustProductsEvaluationsPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TrustProductsEvaluationsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TrustProductsEvaluationsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TrustProductsEvaluationsPage>) => any): Promise<ApiResponse<TrustProductsEvaluationsPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TrustProductsEvaluationsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TrustProductsEvaluationsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TrustProductsEvaluationsPage extends Page<V1, TrustProductsEvaluationsPayload, TrustProductsEvaluationsResource, TrustProductsEvaluationsInstance> { +/** +* Initialize the TrustProductsEvaluationsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TrustProductsEvaluationsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TrustProductsEvaluationsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TrustProductsEvaluationsResource): TrustProductsEvaluationsInstance { + + return new TrustProductsEvaluationsInstance( + this._version, + payload, + this._solution.trustProductSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/trusthub/v1/trustProductsProvisionalCopy.ts b/rest/trusthub/v1/trustProductsProvisionalCopy.ts new file mode 100644 index 000000000..03219622c --- /dev/null +++ b/rest/trusthub/v1/trustProductsProvisionalCopy.ts @@ -0,0 +1,386 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Trusthub + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +export interface TrustProductsProvisionalCopyContext { + + /** + * Create a TrustProductsProvisionalCopyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsProvisionalCopyInstance + */ + create(callback?: (error: Error | null, item?: TrustProductsProvisionalCopyInstance) => any): Promise<TrustProductsProvisionalCopyInstance> + + /** + * Create a TrustProductsProvisionalCopyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsProvisionalCopyInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsProvisionalCopyInstance>) => any): Promise<ApiResponse<TrustProductsProvisionalCopyInstance>> + + /** + * Fetch a TrustProductsProvisionalCopyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsProvisionalCopyInstance + */ + fetch(callback?: (error: Error | null, item?: TrustProductsProvisionalCopyInstance) => any): Promise<TrustProductsProvisionalCopyInstance> + + /** + * Fetch a TrustProductsProvisionalCopyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsProvisionalCopyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsProvisionalCopyInstance>) => any): Promise<ApiResponse<TrustProductsProvisionalCopyInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TrustProductsProvisionalCopyContextSolution { + "trustProductSid": string; +} + +export class TrustProductsProvisionalCopyContextImpl implements TrustProductsProvisionalCopyContext { + protected _solution: TrustProductsProvisionalCopyContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, trustProductSid: string) { + if (!isValidPathParam(trustProductSid)) { + throw new Error('Parameter \'trustProductSid\' is not valid.'); + } + + this._solution = { trustProductSid, }; + this._uri = `/TrustProducts/${trustProductSid}/ProvisionalCopy`; + } + + create(callback?: (error: Error | null, item?: TrustProductsProvisionalCopyInstance) => any): Promise<TrustProductsProvisionalCopyInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsProvisionalCopyInstance(operationVersion, payload, instance._solution.trustProductSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsProvisionalCopyInstance>) => any): Promise<ApiResponse<TrustProductsProvisionalCopyInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TrustProductsProvisionalCopyResource>({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse<TrustProductsProvisionalCopyInstance> => ({ + ...response, + body: new TrustProductsProvisionalCopyInstance(operationVersion, response.body, instance._solution.trustProductSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TrustProductsProvisionalCopyInstance) => any): Promise<TrustProductsProvisionalCopyInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TrustProductsProvisionalCopyInstance(operationVersion, payload, instance._solution.trustProductSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsProvisionalCopyInstance>) => any): Promise<ApiResponse<TrustProductsProvisionalCopyInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TrustProductsProvisionalCopyResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TrustProductsProvisionalCopyInstance> => ({ + ...response, + body: new TrustProductsProvisionalCopyInstance(operationVersion, response.body, instance._solution.trustProductSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TrustProductsProvisionalCopyPayload extends TrustProductsProvisionalCopyResource {} + +interface TrustProductsProvisionalCopyResource { + trust_product_sid: string; + account_sid: string; + policy_sid: string; + friendly_name: string; + status: string; + email: string; + status_callback: string; + valid_until: Date; + date_created: Date; + date_updated: Date; + url: string; +} + +export class TrustProductsProvisionalCopyInstance { + protected _solution: TrustProductsProvisionalCopyContextSolution; + protected _context?: TrustProductsProvisionalCopyContext; + + constructor(protected _version: V1, payload: TrustProductsProvisionalCopyResource, trustProductSid?: string) { + + this.trustProductSid = (payload.trust_product_sid); + this.accountSid = (payload.account_sid); + this.policySid = (payload.policy_sid); + this.friendlyName = (payload.friendly_name); + this.status = (payload.status); + this.email = (payload.email); + this.statusCallback = (payload.status_callback); + this.validUntil = deserialize.iso8601DateTime(payload.valid_until); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { trustProductSid: trustProductSid, }; + } + + /** + * The unique SID identifier of the Trust Product. + */ + trustProductSid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Policy. + */ + policySid: string; + /** + * A human readable description of this resource, up to 64 characters. + */ + friendlyName: string; + /** + * The verification status of the Customer-Profile resource. + */ + status: string; + /** + * The email address that will receive updates when the trust product resource changes status. + */ + email: string; + /** + * The URL we call to inform your application of status changes. + */ + statusCallback: string; + /** + * The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + */ + validUntil: Date; + /** + * The date that this Trust Products Provisional Copy was created, given in ISO 8601 format. + */ + dateCreated: Date; + /** + * The date that this Trust Products Provisional Copy was updated, given in ISO 8601 format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): TrustProductsProvisionalCopyContext { + this._context = this._context || new TrustProductsProvisionalCopyContextImpl(this._version, this._solution.trustProductSid); + return this._context; + } + + /** + * Create a TrustProductsProvisionalCopyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsProvisionalCopyInstance + */ + create(callback?: (error: Error | null, item?: TrustProductsProvisionalCopyInstance) => any): Promise<TrustProductsProvisionalCopyInstance> + + { + return this._proxy.create(callback); + } + + /** + * Create a TrustProductsProvisionalCopyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsProvisionalCopyInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsProvisionalCopyInstance>) => any): Promise<ApiResponse<TrustProductsProvisionalCopyInstance>> + + { + return this._proxy.createWithHttpInfo(callback); + } + + /** + * Fetch a TrustProductsProvisionalCopyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsProvisionalCopyInstance + */ + fetch(callback?: (error: Error | null, item?: TrustProductsProvisionalCopyInstance) => any): Promise<TrustProductsProvisionalCopyInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TrustProductsProvisionalCopyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TrustProductsProvisionalCopyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TrustProductsProvisionalCopyInstance>) => any): Promise<ApiResponse<TrustProductsProvisionalCopyInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + trustProductSid: this.trustProductSid, + accountSid: this.accountSid, + policySid: this.policySid, + friendlyName: this.friendlyName, + status: this.status, + email: this.email, + statusCallback: this.statusCallback, + validUntil: this.validUntil, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TrustProductsProvisionalCopySolution { +} + +export interface TrustProductsProvisionalCopyListInstance { + _version: V1; + _solution: TrustProductsProvisionalCopySolution; + _uri: string; + + (trustProductSid: string, ): TrustProductsProvisionalCopyContext; + get(trustProductSid: string, ): TrustProductsProvisionalCopyContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TrustProductsProvisionalCopyListInstance(version: V1): TrustProductsProvisionalCopyListInstance { + const instance = ((trustProductSid, ) => instance.get(trustProductSid, )) as TrustProductsProvisionalCopyListInstance; + + instance.get = function get(trustProductSid, ): TrustProductsProvisionalCopyContext { + return new TrustProductsProvisionalCopyContextImpl(version, trustProductSid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/verify/V2.ts b/rest/verify/V2.ts new file mode 100644 index 000000000..56efde9eb --- /dev/null +++ b/rest/verify/V2.ts @@ -0,0 +1,83 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import VerifyBase from "../VerifyBase"; +import Version from "../../base/Version"; +import { FormListInstance } from "./v2/form"; +import { SafelistListInstance } from "./v2/safelist"; +import { ServiceListInstance } from "./v2/service"; +import { TemplateListInstance } from "./v2/template"; +import { VerificationAttemptListInstance } from "./v2/verificationAttempt"; +import { VerificationAttemptsSummaryListInstance } from "./v2/verificationAttemptsSummary"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Verify + * + * @param domain - The Twilio (Twilio.Verify) domain + */ + constructor(domain: VerifyBase) { + super(domain, "v2"); + } + + /** forms - { Twilio.Verify.V2.FormListInstance } resource */ + protected _forms?: FormListInstance; + /** safelist - { Twilio.Verify.V2.SafelistListInstance } resource */ + protected _safelist?: SafelistListInstance; + /** services - { Twilio.Verify.V2.ServiceListInstance } resource */ + protected _services?: ServiceListInstance; + /** templates - { Twilio.Verify.V2.TemplateListInstance } resource */ + protected _templates?: TemplateListInstance; + /** verificationAttempts - { Twilio.Verify.V2.VerificationAttemptListInstance } resource */ + protected _verificationAttempts?: VerificationAttemptListInstance; + /** verificationAttemptsSummary - { Twilio.Verify.V2.VerificationAttemptsSummaryListInstance } resource */ + protected _verificationAttemptsSummary?: VerificationAttemptsSummaryListInstance; + + /** Getter for forms resource */ + get forms(): FormListInstance { + this._forms = this._forms || FormListInstance(this); + return this._forms; + } + + /** Getter for safelist resource */ + get safelist(): SafelistListInstance { + this._safelist = this._safelist || SafelistListInstance(this); + return this._safelist; + } + + /** Getter for services resource */ + get services(): ServiceListInstance { + this._services = this._services || ServiceListInstance(this); + return this._services; + } + + /** Getter for templates resource */ + get templates(): TemplateListInstance { + this._templates = this._templates || TemplateListInstance(this); + return this._templates; + } + + /** Getter for verificationAttempts resource */ + get verificationAttempts(): VerificationAttemptListInstance { + this._verificationAttempts = this._verificationAttempts || VerificationAttemptListInstance(this); + return this._verificationAttempts; + } + + /** Getter for verificationAttemptsSummary resource */ + get verificationAttemptsSummary(): VerificationAttemptsSummaryListInstance { + this._verificationAttemptsSummary = this._verificationAttemptsSummary || VerificationAttemptsSummaryListInstance(this); + return this._verificationAttemptsSummary; + } + +} diff --git a/rest/verify/v2/form.ts b/rest/verify/v2/form.ts new file mode 100644 index 000000000..a8d6dd156 --- /dev/null +++ b/rest/verify/v2/form.ts @@ -0,0 +1,257 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The Type of this Form. Currently only `form-push` is supported. + */ +export type FormFormTypes = 'form-push'; + + + +export interface FormContext { + + /** + * Fetch a FormInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FormInstance + */ + fetch(callback?: (error: Error | null, item?: FormInstance) => any): Promise<FormInstance> + + /** + * Fetch a FormInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FormInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FormInstance>) => any): Promise<ApiResponse<FormInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FormContextSolution { + "formType": FormFormTypes; +} + +export class FormContextImpl implements FormContext { + protected _solution: FormContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, formType: FormFormTypes) { + if (!isValidPathParam(formType)) { + throw new Error('Parameter \'formType\' is not valid.'); + } + + this._solution = { formType, }; + this._uri = `/Forms/${formType}`; + } + + fetch(callback?: (error: Error | null, item?: FormInstance) => any): Promise<FormInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FormInstance(operationVersion, payload, instance._solution.formType)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FormInstance>) => any): Promise<ApiResponse<FormInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<FormResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<FormInstance> => ({ + ...response, + body: new FormInstance(operationVersion, response.body, instance._solution.formType) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FormPayload extends FormResource {} + +interface FormResource { + form_type: FormFormTypes; + forms: any; + form_meta: any; + url: string; +} + +export class FormInstance { + protected _solution: FormContextSolution; + protected _context?: FormContext; + + constructor(protected _version: V2, payload: FormResource, formType?: FormFormTypes) { + + this.formType = payload.form_type; + this.forms = (payload.forms); + this.formMeta = (payload.form_meta); + this.url = (payload.url); + + this._solution = { formType: formType, }; + } + + formType: FormFormTypes; + /** + * Object that contains the available forms for this type. This available forms are given in the standard [JSON Schema](https://json-schema.org/) format + */ + forms: any; + /** + * Additional information for the available forms for this type. E.g. The separator string used for `binding` in a Factor push. + */ + formMeta: any; + /** + * The URL to access the forms for this type. + */ + url: string; + + private get _proxy(): FormContext { + this._context = this._context || new FormContextImpl(this._version, this._solution.formType); + return this._context; + } + + /** + * Fetch a FormInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FormInstance + */ + fetch(callback?: (error: Error | null, item?: FormInstance) => any): Promise<FormInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FormInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FormInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FormInstance>) => any): Promise<ApiResponse<FormInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + formType: this.formType, + forms: this.forms, + formMeta: this.formMeta, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FormSolution { +} + +export interface FormListInstance { + _version: V2; + _solution: FormSolution; + _uri: string; + + (formType: FormFormTypes, ): FormContext; + get(formType: FormFormTypes, ): FormContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FormListInstance(version: V2): FormListInstance { + const instance = ((formType, ) => instance.get(formType, )) as FormListInstance; + + instance.get = function get(formType, ): FormContext { + return new FormContextImpl(version, formType); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/verify/v2/safelist.ts b/rest/verify/v2/safelist.ts new file mode 100644 index 000000000..336c7186d --- /dev/null +++ b/rest/verify/v2/safelist.ts @@ -0,0 +1,425 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to create a SafelistInstance + */ +export interface SafelistListInstanceCreateOptions { + /** The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). */ + "phoneNumber": string; +} + +export interface SafelistContext { + + /** + * Remove a SafelistInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SafelistInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SafelistInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance + */ + fetch(callback?: (error: Error | null, item?: SafelistInstance) => any): Promise<SafelistInstance> + + /** + * Fetch a SafelistInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SafelistInstance>) => any): Promise<ApiResponse<SafelistInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SafelistContextSolution { + "phoneNumber": string; +} + +export class SafelistContextImpl implements SafelistContext { + protected _solution: SafelistContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, phoneNumber: string) { + if (!isValidPathParam(phoneNumber)) { + throw new Error('Parameter \'phoneNumber\' is not valid.'); + } + + this._solution = { phoneNumber, }; + this._uri = `/SafeList/Numbers/${phoneNumber}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SafelistInstance) => any): Promise<SafelistInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SafelistInstance(operationVersion, payload, instance._solution.phoneNumber)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SafelistInstance>) => any): Promise<ApiResponse<SafelistInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SafelistResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SafelistInstance> => ({ + ...response, + body: new SafelistInstance(operationVersion, response.body, instance._solution.phoneNumber) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SafelistPayload extends SafelistResource {} + +interface SafelistResource { + sid: string; + phone_number: string; + url: string; +} + +export class SafelistInstance { + protected _solution: SafelistContextSolution; + protected _context?: SafelistContext; + + constructor(protected _version: V2, payload: SafelistResource, phoneNumber?: string) { + + this.sid = (payload.sid); + this.phoneNumber = (payload.phone_number); + this.url = (payload.url); + + this._solution = { phoneNumber: phoneNumber, }; + } + + /** + * The unique string that we created to identify the SafeList resource. + */ + sid: string; + /** + * The phone number in SafeList. + */ + phoneNumber: string; + /** + * The absolute URL of the SafeList resource. + */ + url: string; + + private get _proxy(): SafelistContext { + this._context = this._context || new SafelistContextImpl(this._version, this._solution.phoneNumber); + return this._context; + } + + /** + * Remove a SafelistInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SafelistInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SafelistInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance + */ + fetch(callback?: (error: Error | null, item?: SafelistInstance) => any): Promise<SafelistInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SafelistInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SafelistInstance>) => any): Promise<ApiResponse<SafelistInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + phoneNumber: this.phoneNumber, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SafelistSolution { +} + +export interface SafelistListInstance { + _version: V2; + _solution: SafelistSolution; + _uri: string; + + (phoneNumber: string, ): SafelistContext; + get(phoneNumber: string, ): SafelistContext; + + + + + + + /** + * Create a SafelistInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance + */ + create(params: SafelistListInstanceCreateOptions, callback?: (error: Error | null, item?: SafelistInstance) => any): Promise<SafelistInstance>; + + /** + * Create a SafelistInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SafelistInstance with HTTP metadata + */ + createWithHttpInfo(params: SafelistListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SafelistInstance>) => any): Promise<ApiResponse<SafelistInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SafelistListInstance(version: V2): SafelistListInstance { + const instance = ((phoneNumber, ) => instance.get(phoneNumber, )) as SafelistListInstance; + + instance.get = function get(phoneNumber, ): SafelistContext { + return new SafelistContextImpl(version, phoneNumber); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/SafeList/Numbers`; + + instance.create = function create(params: SafelistListInstanceCreateOptions, callback?: (error: Error | null, items: SafelistInstance) => any): Promise<SafelistInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SafelistInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SafelistListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<SafelistInstance>) => any): Promise<ApiResponse<SafelistInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["phoneNumber"] === null || params["phoneNumber"] === undefined) { + throw new Error('Required parameter "params[\'phoneNumber\']" missing.'); + } + + let data: any = {}; + + + + data["PhoneNumber"] = params["phoneNumber"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SafelistResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SafelistInstance> => ({ + ...response, + body: new SafelistInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/verify/v2/service.ts b/rest/verify/v2/service.ts new file mode 100644 index 000000000..86deb8e06 --- /dev/null +++ b/rest/verify/v2/service.ts @@ -0,0 +1,1450 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { AccessTokenListInstance } from "./service/accessToken"; +import { ApproveChallengeListInstance } from "./service/approveChallenge"; +import { EntityListInstance } from "./service/entity"; +import { MessagingConfigurationListInstance } from "./service/messagingConfiguration"; +import { NewChallengeListInstance } from "./service/newChallenge"; +import { NewFactorListInstance } from "./service/newFactor"; +import { NewVerifyFactorListInstance } from "./service/newVerifyFactor"; +import { RateLimitListInstance } from "./service/rateLimit"; +import { VerificationListInstance } from "./service/verification"; +import { VerificationCheckListInstance } from "./service/verificationCheck"; +import { WebhookListInstance } from "./service/webhook"; + + + + + +/** + * Options to pass to update a ServiceInstance + */ +export interface ServiceContextUpdateOptions { + /** A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** */ + "friendlyName"?: string; + /** The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. */ + "codeLength"?: number; + /** Whether to perform a lookup with each verification started and return info about the phone number. */ + "lookupEnabled"?: boolean; + /** Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. */ + "skipSmsToLandlines"?: boolean; + /** Whether to ask the user to press a number before delivering the verify code in a phone call. */ + "dtmfInputRequired"?: boolean; + /** The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. */ + "ttsName"?: string; + /** Whether to pass PSD2 transaction parameters when starting a verification. */ + "psd2Enabled"?: boolean; + /** Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** */ + "doNotShareWarningEnabled"?: boolean; + /** Whether to allow sending verifications with a custom code instead of a randomly generated one. */ + "customCodeEnabled"?: boolean; + /** Optional configuration for the Push factors. If true, include the date in the Challenge\\\'s response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. */ + "push.includeDate"?: boolean; + /** Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) */ + "push.apnCredentialSid"?: string; + /** Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) */ + "push.fcmCredentialSid"?: string; + /** Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. */ + "totp.issuer"?: string; + /** Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds */ + "totp.timeStep"?: number; + /** Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 */ + "totp.codeLength"?: number; + /** Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 */ + "totp.skew"?: number; + /** The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. */ + "defaultTemplateSid"?: string; + /** The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. */ + "whatsapp.msgServiceSid"?: string; + /** The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. */ + "whatsapp.from"?: string; + /** The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. */ + "passkeys.relyingParty.id"?: string; + /** The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. */ + "passkeys.relyingParty.name"?: string; + /** The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. */ + "passkeys.relyingParty.origins"?: string; + /** The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. */ + "passkeys.authenticatorAttachment"?: string; + /** Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. */ + "passkeys.discoverableCredentials"?: string; + /** The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. */ + "passkeys.userVerification"?: string; + /** Whether to allow verifications from the service to reach the stream-events sinks if configured */ + "verifyEventSubscriptionEnabled"?: boolean; +} + +/** + * Options to pass to create a ServiceInstance + */ +export interface ServiceListInstanceCreateOptions { + /** A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** */ + "friendlyName": string; + /** The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. */ + "codeLength"?: number; + /** Whether to perform a lookup with each verification started and return info about the phone number. */ + "lookupEnabled"?: boolean; + /** Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. */ + "skipSmsToLandlines"?: boolean; + /** Whether to ask the user to press a number before delivering the verify code in a phone call. */ + "dtmfInputRequired"?: boolean; + /** The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. */ + "ttsName"?: string; + /** Whether to pass PSD2 transaction parameters when starting a verification. */ + "psd2Enabled"?: boolean; + /** Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` */ + "doNotShareWarningEnabled"?: boolean; + /** Whether to allow sending verifications with a custom code instead of a randomly generated one. */ + "customCodeEnabled"?: boolean; + /** Optional configuration for the Push factors. If true, include the date in the Challenge\\\'s response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. This timestamp value is the same one as the one found in `date_created`, please use that one instead. */ + "push.includeDate"?: boolean; + /** Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) */ + "push.apnCredentialSid"?: string; + /** Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) */ + "push.fcmCredentialSid"?: string; + /** Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. Defaults to the service friendly name if not provided. */ + "totp.issuer"?: string; + /** Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds */ + "totp.timeStep"?: number; + /** Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 */ + "totp.codeLength"?: number; + /** Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 */ + "totp.skew"?: number; + /** The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. */ + "defaultTemplateSid"?: string; + /** The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. */ + "whatsapp.msgServiceSid"?: string; + /** The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. */ + "whatsapp.from"?: string; + /** The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. */ + "passkeys.relyingParty.id"?: string; + /** The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. */ + "passkeys.relyingParty.name"?: string; + /** The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. */ + "passkeys.relyingParty.origins"?: string; + /** The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. */ + "passkeys.authenticatorAttachment"?: string; + /** Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. */ + "passkeys.discoverableCredentials"?: string; + /** The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. */ + "passkeys.userVerification"?: string; + /** Whether to allow verifications from the service to reach the stream-events sinks if configured */ + "verifyEventSubscriptionEnabled"?: boolean; +} + +/** + * Options to pass to each + */ +export interface ServiceListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ServiceInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ServiceListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ServiceListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ServiceContext { + accessTokens: AccessTokenListInstance; + approveChallenge: ApproveChallengeListInstance; + entities: EntityListInstance; + messagingConfigurations: MessagingConfigurationListInstance; + newChallenge: NewChallengeListInstance; + newFactors: NewFactorListInstance; + newVerifyFactors: NewVerifyFactorListInstance; + rateLimits: RateLimitListInstance; + verifications: VerificationListInstance; + verificationChecks: VerificationCheckListInstance; + webhooks: WebhookListInstance; + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ServiceContextSolution { + "sid": string; +} + +export class ServiceContextImpl implements ServiceContext { + protected _solution: ServiceContextSolution; + protected _uri: string; + + protected _accessTokens?: AccessTokenListInstance; + protected _approveChallenge?: ApproveChallengeListInstance; + protected _entities?: EntityListInstance; + protected _messagingConfigurations?: MessagingConfigurationListInstance; + protected _newChallenge?: NewChallengeListInstance; + protected _newFactors?: NewFactorListInstance; + protected _newVerifyFactors?: NewVerifyFactorListInstance; + protected _rateLimits?: RateLimitListInstance; + protected _verifications?: VerificationListInstance; + protected _verificationChecks?: VerificationCheckListInstance; + protected _webhooks?: WebhookListInstance; + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Services/${sid}`; + } + + get accessTokens(): AccessTokenListInstance { + this._accessTokens = this._accessTokens || AccessTokenListInstance(this._version, this._solution.sid); + return this._accessTokens; + } + + get approveChallenge(): ApproveChallengeListInstance { + this._approveChallenge = this._approveChallenge || ApproveChallengeListInstance(this._version, this._solution.sid); + return this._approveChallenge; + } + + get entities(): EntityListInstance { + this._entities = this._entities || EntityListInstance(this._version, this._solution.sid); + return this._entities; + } + + get messagingConfigurations(): MessagingConfigurationListInstance { + this._messagingConfigurations = this._messagingConfigurations || MessagingConfigurationListInstance(this._version, this._solution.sid); + return this._messagingConfigurations; + } + + get newChallenge(): NewChallengeListInstance { + this._newChallenge = this._newChallenge || NewChallengeListInstance(this._version, this._solution.sid); + return this._newChallenge; + } + + get newFactors(): NewFactorListInstance { + this._newFactors = this._newFactors || NewFactorListInstance(this._version, this._solution.sid); + return this._newFactors; + } + + get newVerifyFactors(): NewVerifyFactorListInstance { + this._newVerifyFactors = this._newVerifyFactors || NewVerifyFactorListInstance(this._version, this._solution.sid); + return this._newVerifyFactors; + } + + get rateLimits(): RateLimitListInstance { + this._rateLimits = this._rateLimits || RateLimitListInstance(this._version, this._solution.sid); + return this._rateLimits; + } + + get verifications(): VerificationListInstance { + this._verifications = this._verifications || VerificationListInstance(this._version, this._solution.sid); + return this._verifications; + } + + get verificationChecks(): VerificationCheckListInstance { + this._verificationChecks = this._verificationChecks || VerificationCheckListInstance(this._version, this._solution.sid); + return this._verificationChecks; + } + + get webhooks(): WebhookListInstance { + this._webhooks = this._webhooks || WebhookListInstance(this._version, this._solution.sid); + return this._webhooks; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ServiceInstance) => any),callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["codeLength"] !== undefined) + data["CodeLength"] = params["codeLength"]; + if (params["lookupEnabled"] !== undefined) + data["LookupEnabled"] = serialize.bool(params["lookupEnabled"]); + if (params["skipSmsToLandlines"] !== undefined) + data["SkipSmsToLandlines"] = serialize.bool(params["skipSmsToLandlines"]); + if (params["dtmfInputRequired"] !== undefined) + data["DtmfInputRequired"] = serialize.bool(params["dtmfInputRequired"]); + if (params["ttsName"] !== undefined) + data["TtsName"] = params["ttsName"]; + if (params["psd2Enabled"] !== undefined) + data["Psd2Enabled"] = serialize.bool(params["psd2Enabled"]); + if (params["doNotShareWarningEnabled"] !== undefined) + data["DoNotShareWarningEnabled"] = serialize.bool(params["doNotShareWarningEnabled"]); + if (params["customCodeEnabled"] !== undefined) + data["CustomCodeEnabled"] = serialize.bool(params["customCodeEnabled"]); + if (params["push.includeDate"] !== undefined) + data["Push.IncludeDate"] = serialize.bool(params["push.includeDate"]); + if (params["push.apnCredentialSid"] !== undefined) + data["Push.ApnCredentialSid"] = params["push.apnCredentialSid"]; + if (params["push.fcmCredentialSid"] !== undefined) + data["Push.FcmCredentialSid"] = params["push.fcmCredentialSid"]; + if (params["totp.issuer"] !== undefined) + data["Totp.Issuer"] = params["totp.issuer"]; + if (params["totp.timeStep"] !== undefined) + data["Totp.TimeStep"] = params["totp.timeStep"]; + if (params["totp.codeLength"] !== undefined) + data["Totp.CodeLength"] = params["totp.codeLength"]; + if (params["totp.skew"] !== undefined) + data["Totp.Skew"] = params["totp.skew"]; + if (params["defaultTemplateSid"] !== undefined) + data["DefaultTemplateSid"] = params["defaultTemplateSid"]; + if (params["whatsapp.msgServiceSid"] !== undefined) + data["Whatsapp.MsgServiceSid"] = params["whatsapp.msgServiceSid"]; + if (params["whatsapp.from"] !== undefined) + data["Whatsapp.From"] = params["whatsapp.from"]; + if (params["passkeys.relyingParty.id"] !== undefined) + data["Passkeys.RelyingParty.Id"] = params["passkeys.relyingParty.id"]; + if (params["passkeys.relyingParty.name"] !== undefined) + data["Passkeys.RelyingParty.Name"] = params["passkeys.relyingParty.name"]; + if (params["passkeys.relyingParty.origins"] !== undefined) + data["Passkeys.RelyingParty.Origins"] = params["passkeys.relyingParty.origins"]; + if (params["passkeys.authenticatorAttachment"] !== undefined) + data["Passkeys.AuthenticatorAttachment"] = params["passkeys.authenticatorAttachment"]; + if (params["passkeys.discoverableCredentials"] !== undefined) + data["Passkeys.DiscoverableCredentials"] = params["passkeys.discoverableCredentials"]; + if (params["passkeys.userVerification"] !== undefined) + data["Passkeys.UserVerification"] = params["passkeys.userVerification"]; + if (params["verifyEventSubscriptionEnabled"] !== undefined) + data["VerifyEventSubscriptionEnabled"] = serialize.bool(params["verifyEventSubscriptionEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ServiceContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ServiceInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["codeLength"] !== undefined) + data["CodeLength"] = params["codeLength"]; + if (params["lookupEnabled"] !== undefined) + data["LookupEnabled"] = serialize.bool(params["lookupEnabled"]); + if (params["skipSmsToLandlines"] !== undefined) + data["SkipSmsToLandlines"] = serialize.bool(params["skipSmsToLandlines"]); + if (params["dtmfInputRequired"] !== undefined) + data["DtmfInputRequired"] = serialize.bool(params["dtmfInputRequired"]); + if (params["ttsName"] !== undefined) + data["TtsName"] = params["ttsName"]; + if (params["psd2Enabled"] !== undefined) + data["Psd2Enabled"] = serialize.bool(params["psd2Enabled"]); + if (params["doNotShareWarningEnabled"] !== undefined) + data["DoNotShareWarningEnabled"] = serialize.bool(params["doNotShareWarningEnabled"]); + if (params["customCodeEnabled"] !== undefined) + data["CustomCodeEnabled"] = serialize.bool(params["customCodeEnabled"]); + if (params["push.includeDate"] !== undefined) + data["Push.IncludeDate"] = serialize.bool(params["push.includeDate"]); + if (params["push.apnCredentialSid"] !== undefined) + data["Push.ApnCredentialSid"] = params["push.apnCredentialSid"]; + if (params["push.fcmCredentialSid"] !== undefined) + data["Push.FcmCredentialSid"] = params["push.fcmCredentialSid"]; + if (params["totp.issuer"] !== undefined) + data["Totp.Issuer"] = params["totp.issuer"]; + if (params["totp.timeStep"] !== undefined) + data["Totp.TimeStep"] = params["totp.timeStep"]; + if (params["totp.codeLength"] !== undefined) + data["Totp.CodeLength"] = params["totp.codeLength"]; + if (params["totp.skew"] !== undefined) + data["Totp.Skew"] = params["totp.skew"]; + if (params["defaultTemplateSid"] !== undefined) + data["DefaultTemplateSid"] = params["defaultTemplateSid"]; + if (params["whatsapp.msgServiceSid"] !== undefined) + data["Whatsapp.MsgServiceSid"] = params["whatsapp.msgServiceSid"]; + if (params["whatsapp.from"] !== undefined) + data["Whatsapp.From"] = params["whatsapp.from"]; + if (params["passkeys.relyingParty.id"] !== undefined) + data["Passkeys.RelyingParty.Id"] = params["passkeys.relyingParty.id"]; + if (params["passkeys.relyingParty.name"] !== undefined) + data["Passkeys.RelyingParty.Name"] = params["passkeys.relyingParty.name"]; + if (params["passkeys.relyingParty.origins"] !== undefined) + data["Passkeys.RelyingParty.Origins"] = params["passkeys.relyingParty.origins"]; + if (params["passkeys.authenticatorAttachment"] !== undefined) + data["Passkeys.AuthenticatorAttachment"] = params["passkeys.authenticatorAttachment"]; + if (params["passkeys.discoverableCredentials"] !== undefined) + data["Passkeys.DiscoverableCredentials"] = params["passkeys.discoverableCredentials"]; + if (params["passkeys.userVerification"] !== undefined) + data["Passkeys.UserVerification"] = params["passkeys.userVerification"]; + if (params["verifyEventSubscriptionEnabled"] !== undefined) + data["VerifyEventSubscriptionEnabled"] = serialize.bool(params["verifyEventSubscriptionEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ServicePayload extends TwilioResponsePayload { + services: ServiceResource[]; +} + +interface ServiceResource { + sid: string; + account_sid: string; + friendly_name: string; + code_length: number; + lookup_enabled: boolean; + psd2_enabled: boolean; + skip_sms_to_landlines: boolean; + dtmf_input_required: boolean; + tts_name: string; + do_not_share_warning_enabled: boolean; + custom_code_enabled: boolean; + push: any; + totp: any; + default_template_sid: string; + whatsapp: any; + passkeys: any; + verify_event_subscription_enabled: boolean; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class ServiceInstance { + protected _solution: ServiceContextSolution; + protected _context?: ServiceContext; + + constructor(protected _version: V2, payload: ServiceResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.codeLength = deserialize.integer(payload.code_length); + this.lookupEnabled = (payload.lookup_enabled); + this.psd2Enabled = (payload.psd2_enabled); + this.skipSmsToLandlines = (payload.skip_sms_to_landlines); + this.dtmfInputRequired = (payload.dtmf_input_required); + this.ttsName = (payload.tts_name); + this.doNotShareWarningEnabled = (payload.do_not_share_warning_enabled); + this.customCodeEnabled = (payload.custom_code_enabled); + this.push = (payload.push); + this.totp = (payload.totp); + this.defaultTemplateSid = (payload.default_template_sid); + this.whatsapp = (payload.whatsapp); + this.passkeys = (payload.passkeys); + this.verifyEventSubscriptionEnabled = (payload.verify_event_subscription_enabled); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Service resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + */ + accountSid: string; + /** + * The name that appears in the body of your verification messages. It can be up to 30 characters long and can include letters, numbers, spaces, dashes, underscores. Phone numbers, special characters or links are NOT allowed. It cannot contain more than 4 (consecutive or non-consecutive) digits. **This value should not contain PII.** + */ + friendlyName: string; + /** + * The length of the verification code to generate. + */ + codeLength: number; + /** + * Whether to perform a lookup with each verification started and return info about the phone number. + */ + lookupEnabled: boolean; + /** + * Whether to pass PSD2 transaction parameters when starting a verification. + */ + psd2Enabled: boolean; + /** + * Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + */ + skipSmsToLandlines: boolean; + /** + * Whether to ask the user to press a number before delivering the verify code in a phone call. + */ + dtmfInputRequired: boolean; + /** + * The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + */ + ttsName: string; + /** + * Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + */ + doNotShareWarningEnabled: boolean; + /** + * Whether to allow sending verifications with a custom code instead of a randomly generated one. + */ + customCodeEnabled: boolean; + /** + * Configurations for the Push factors (channel) created under this Service. + */ + push: any; + /** + * Configurations for the TOTP factors (channel) created under this Service. + */ + totp: any; + defaultTemplateSid: string; + whatsapp: any; + passkeys: any; + /** + * Whether to allow verifications from the service to reach the stream-events sinks if configured + */ + verifyEventSubscriptionEnabled: boolean; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): ServiceContext { + this._context = this._context || new ServiceContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + fetch(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ServiceInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + /** + * Update a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + update(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ServiceInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + /** + * Update a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + updateWithHttpInfo(params: ServiceContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the accessTokens. + */ + accessTokens(): AccessTokenListInstance { + return this._proxy.accessTokens; + } + + /** + * Access the approveChallenge. + */ + approveChallenge(): ApproveChallengeListInstance { + return this._proxy.approveChallenge; + } + + /** + * Access the entities. + */ + entities(): EntityListInstance { + return this._proxy.entities; + } + + /** + * Access the messagingConfigurations. + */ + messagingConfigurations(): MessagingConfigurationListInstance { + return this._proxy.messagingConfigurations; + } + + /** + * Access the newChallenge. + */ + newChallenge(): NewChallengeListInstance { + return this._proxy.newChallenge; + } + + /** + * Access the newFactors. + */ + newFactors(): NewFactorListInstance { + return this._proxy.newFactors; + } + + /** + * Access the newVerifyFactors. + */ + newVerifyFactors(): NewVerifyFactorListInstance { + return this._proxy.newVerifyFactors; + } + + /** + * Access the rateLimits. + */ + rateLimits(): RateLimitListInstance { + return this._proxy.rateLimits; + } + + /** + * Access the verifications. + */ + verifications(): VerificationListInstance { + return this._proxy.verifications; + } + + /** + * Access the verificationChecks. + */ + verificationChecks(): VerificationCheckListInstance { + return this._proxy.verificationChecks; + } + + /** + * Access the webhooks. + */ + webhooks(): WebhookListInstance { + return this._proxy.webhooks; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + codeLength: this.codeLength, + lookupEnabled: this.lookupEnabled, + psd2Enabled: this.psd2Enabled, + skipSmsToLandlines: this.skipSmsToLandlines, + dtmfInputRequired: this.dtmfInputRequired, + ttsName: this.ttsName, + doNotShareWarningEnabled: this.doNotShareWarningEnabled, + customCodeEnabled: this.customCodeEnabled, + push: this.push, + totp: this.totp, + defaultTemplateSid: this.defaultTemplateSid, + whatsapp: this.whatsapp, + passkeys: this.passkeys, + verifyEventSubscriptionEnabled: this.verifyEventSubscriptionEnabled, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ServiceSolution { +} + +export interface ServiceListInstance { + _version: V2; + _solution: ServiceSolution; + _uri: string; + + (sid: string, ): ServiceContext; + get(sid: string, ): ServiceContext; + + + + + + + + + /** + * Create a ServiceInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance + */ + create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ServiceInstance) => any): Promise<ServiceInstance>; + + /** + * Create a ServiceInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ServiceInstance with HTTP metadata + */ + createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>>; + + + + + /** + * Streams ServiceInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + each(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ServiceInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ServiceListInstanceEachOptions, callback?: (item: ServiceInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single target page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + /** + * Lists ServiceInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + list(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ServiceInstance[]) => any): Promise<ServiceInstance[]>; + /** + * Lists ServiceInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + listWithHttpInfo(params: ServiceListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ServiceInstance[]>) => any): Promise<ApiResponse<ServiceInstance[]>>; + /** + * Retrieve a single page of ServiceInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + page(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage>; + /** + * Retrieve a single page of ServiceInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ServiceListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + pageWithHttpInfo(params: ServiceListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ServiceListInstance(version: V2): ServiceListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ServiceListInstance; + + instance.get = function get(sid, ): ServiceContext { + return new ServiceContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Services`; + + instance.create = function create(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ServiceInstance) => any): Promise<ServiceInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["codeLength"] !== undefined) + data["CodeLength"] = params["codeLength"]; + if (params["lookupEnabled"] !== undefined) + data["LookupEnabled"] = serialize.bool(params["lookupEnabled"]); + if (params["skipSmsToLandlines"] !== undefined) + data["SkipSmsToLandlines"] = serialize.bool(params["skipSmsToLandlines"]); + if (params["dtmfInputRequired"] !== undefined) + data["DtmfInputRequired"] = serialize.bool(params["dtmfInputRequired"]); + if (params["ttsName"] !== undefined) + data["TtsName"] = params["ttsName"]; + if (params["psd2Enabled"] !== undefined) + data["Psd2Enabled"] = serialize.bool(params["psd2Enabled"]); + if (params["doNotShareWarningEnabled"] !== undefined) + data["DoNotShareWarningEnabled"] = serialize.bool(params["doNotShareWarningEnabled"]); + if (params["customCodeEnabled"] !== undefined) + data["CustomCodeEnabled"] = serialize.bool(params["customCodeEnabled"]); + if (params["push.includeDate"] !== undefined) + data["Push.IncludeDate"] = serialize.bool(params["push.includeDate"]); + if (params["push.apnCredentialSid"] !== undefined) + data["Push.ApnCredentialSid"] = params["push.apnCredentialSid"]; + if (params["push.fcmCredentialSid"] !== undefined) + data["Push.FcmCredentialSid"] = params["push.fcmCredentialSid"]; + if (params["totp.issuer"] !== undefined) + data["Totp.Issuer"] = params["totp.issuer"]; + if (params["totp.timeStep"] !== undefined) + data["Totp.TimeStep"] = params["totp.timeStep"]; + if (params["totp.codeLength"] !== undefined) + data["Totp.CodeLength"] = params["totp.codeLength"]; + if (params["totp.skew"] !== undefined) + data["Totp.Skew"] = params["totp.skew"]; + if (params["defaultTemplateSid"] !== undefined) + data["DefaultTemplateSid"] = params["defaultTemplateSid"]; + if (params["whatsapp.msgServiceSid"] !== undefined) + data["Whatsapp.MsgServiceSid"] = params["whatsapp.msgServiceSid"]; + if (params["whatsapp.from"] !== undefined) + data["Whatsapp.From"] = params["whatsapp.from"]; + if (params["passkeys.relyingParty.id"] !== undefined) + data["Passkeys.RelyingParty.Id"] = params["passkeys.relyingParty.id"]; + if (params["passkeys.relyingParty.name"] !== undefined) + data["Passkeys.RelyingParty.Name"] = params["passkeys.relyingParty.name"]; + if (params["passkeys.relyingParty.origins"] !== undefined) + data["Passkeys.RelyingParty.Origins"] = params["passkeys.relyingParty.origins"]; + if (params["passkeys.authenticatorAttachment"] !== undefined) + data["Passkeys.AuthenticatorAttachment"] = params["passkeys.authenticatorAttachment"]; + if (params["passkeys.discoverableCredentials"] !== undefined) + data["Passkeys.DiscoverableCredentials"] = params["passkeys.discoverableCredentials"]; + if (params["passkeys.userVerification"] !== undefined) + data["Passkeys.UserVerification"] = params["passkeys.userVerification"]; + if (params["verifyEventSubscriptionEnabled"] !== undefined) + data["VerifyEventSubscriptionEnabled"] = serialize.bool(params["verifyEventSubscriptionEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ServiceInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ServiceListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ServiceInstance>) => any): Promise<ApiResponse<ServiceInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["codeLength"] !== undefined) + data["CodeLength"] = params["codeLength"]; + if (params["lookupEnabled"] !== undefined) + data["LookupEnabled"] = serialize.bool(params["lookupEnabled"]); + if (params["skipSmsToLandlines"] !== undefined) + data["SkipSmsToLandlines"] = serialize.bool(params["skipSmsToLandlines"]); + if (params["dtmfInputRequired"] !== undefined) + data["DtmfInputRequired"] = serialize.bool(params["dtmfInputRequired"]); + if (params["ttsName"] !== undefined) + data["TtsName"] = params["ttsName"]; + if (params["psd2Enabled"] !== undefined) + data["Psd2Enabled"] = serialize.bool(params["psd2Enabled"]); + if (params["doNotShareWarningEnabled"] !== undefined) + data["DoNotShareWarningEnabled"] = serialize.bool(params["doNotShareWarningEnabled"]); + if (params["customCodeEnabled"] !== undefined) + data["CustomCodeEnabled"] = serialize.bool(params["customCodeEnabled"]); + if (params["push.includeDate"] !== undefined) + data["Push.IncludeDate"] = serialize.bool(params["push.includeDate"]); + if (params["push.apnCredentialSid"] !== undefined) + data["Push.ApnCredentialSid"] = params["push.apnCredentialSid"]; + if (params["push.fcmCredentialSid"] !== undefined) + data["Push.FcmCredentialSid"] = params["push.fcmCredentialSid"]; + if (params["totp.issuer"] !== undefined) + data["Totp.Issuer"] = params["totp.issuer"]; + if (params["totp.timeStep"] !== undefined) + data["Totp.TimeStep"] = params["totp.timeStep"]; + if (params["totp.codeLength"] !== undefined) + data["Totp.CodeLength"] = params["totp.codeLength"]; + if (params["totp.skew"] !== undefined) + data["Totp.Skew"] = params["totp.skew"]; + if (params["defaultTemplateSid"] !== undefined) + data["DefaultTemplateSid"] = params["defaultTemplateSid"]; + if (params["whatsapp.msgServiceSid"] !== undefined) + data["Whatsapp.MsgServiceSid"] = params["whatsapp.msgServiceSid"]; + if (params["whatsapp.from"] !== undefined) + data["Whatsapp.From"] = params["whatsapp.from"]; + if (params["passkeys.relyingParty.id"] !== undefined) + data["Passkeys.RelyingParty.Id"] = params["passkeys.relyingParty.id"]; + if (params["passkeys.relyingParty.name"] !== undefined) + data["Passkeys.RelyingParty.Name"] = params["passkeys.relyingParty.name"]; + if (params["passkeys.relyingParty.origins"] !== undefined) + data["Passkeys.RelyingParty.Origins"] = params["passkeys.relyingParty.origins"]; + if (params["passkeys.authenticatorAttachment"] !== undefined) + data["Passkeys.AuthenticatorAttachment"] = params["passkeys.authenticatorAttachment"]; + if (params["passkeys.discoverableCredentials"] !== undefined) + data["Passkeys.DiscoverableCredentials"] = params["passkeys.discoverableCredentials"]; + if (params["passkeys.userVerification"] !== undefined) + data["Passkeys.UserVerification"] = params["passkeys.userVerification"]; + if (params["verifyEventSubscriptionEnabled"] !== undefined) + data["VerifyEventSubscriptionEnabled"] = serialize.bool(params["verifyEventSubscriptionEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ServiceResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ServiceInstance> => ({ + ...response, + body: new ServiceInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ServicePage) => any), callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ServicePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ServicePage) => any): Promise<ServicePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ServicePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ServiceListInstancePageOptions | ((error: Error | null, items: ApiResponse<ServicePage>) => any), callback?: (error: Error | null, items: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ServicePage>) => any): Promise<ApiResponse<ServicePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ServicePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ServicePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ServicePage extends Page<V2, ServicePayload, ServiceResource, ServiceInstance> { +/** +* Initialize the ServicePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: ServiceSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ServiceInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ServiceResource): ServiceInstance { + + return new ServiceInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/verify/v2/service/accessToken.ts b/rest/verify/v2/service/accessToken.ts new file mode 100644 index 000000000..441ca8e41 --- /dev/null +++ b/rest/verify/v2/service/accessToken.ts @@ -0,0 +1,434 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The Type of the Factor. Currently only `push` is supported. + */ +export type AccessTokenFactorTypes = 'push'; + + + +/** + * Options to pass to create a AccessTokenInstance + */ +export interface AccessTokenListInstanceCreateOptions { + /** The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user\\\'s UUID, GUID, or SID. */ + "identity": string; + /** */ + "factorType": AccessTokenFactorTypes; + /** The friendly name of the factor that is going to be created with this access token */ + "factorFriendlyName"?: string; + /** How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. */ + "ttl"?: number; +} + +export interface AccessTokenContext { + + /** + * Fetch a AccessTokenInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccessTokenInstance + */ + fetch(callback?: (error: Error | null, item?: AccessTokenInstance) => any): Promise<AccessTokenInstance> + + /** + * Fetch a AccessTokenInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccessTokenInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccessTokenInstance>) => any): Promise<ApiResponse<AccessTokenInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AccessTokenContextSolution { + "serviceSid": string; + "sid": string; +} + +export class AccessTokenContextImpl implements AccessTokenContext { + protected _solution: AccessTokenContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/AccessTokens/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: AccessTokenInstance) => any): Promise<AccessTokenInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AccessTokenInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccessTokenInstance>) => any): Promise<ApiResponse<AccessTokenInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AccessTokenResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AccessTokenInstance> => ({ + ...response, + body: new AccessTokenInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AccessTokenPayload extends AccessTokenResource {} + +interface AccessTokenResource { + sid: string; + account_sid: string; + service_sid: string; + entity_identity: string; + factor_type: AccessTokenFactorTypes; + factor_friendly_name: string; + token: string; + url: string; + ttl: number; + date_created: Date; +} + +export class AccessTokenInstance { + protected _solution: AccessTokenContextSolution; + protected _context?: AccessTokenContext; + + constructor(protected _version: V2, payload: AccessTokenResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.entityIdentity = (payload.entity_identity); + this.factorType = payload.factor_type; + this.factorFriendlyName = (payload.factor_friendly_name); + this.token = (payload.token); + this.url = (payload.url); + this.ttl = deserialize.integer(payload.ttl); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this Access Token. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Verify Service. + */ + serviceSid: string; + /** + * The unique external identifier for the Entity of the Service. + */ + entityIdentity: string; + factorType: AccessTokenFactorTypes; + /** + * A human readable description of this factor, up to 64 characters. For a push factor, this can be the device\'s name. + */ + factorFriendlyName: string; + /** + * The access token generated for enrollment, this is an encrypted json web token. + */ + token: string; + /** + * The URL of this resource. + */ + url: string; + /** + * How long, in seconds, the access token is valid. Max: 5 minutes + */ + ttl: number; + /** + * The date that this access token was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + + private get _proxy(): AccessTokenContext { + this._context = this._context || new AccessTokenContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a AccessTokenInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccessTokenInstance + */ + fetch(callback?: (error: Error | null, item?: AccessTokenInstance) => any): Promise<AccessTokenInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AccessTokenInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccessTokenInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccessTokenInstance>) => any): Promise<ApiResponse<AccessTokenInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + entityIdentity: this.entityIdentity, + factorType: this.factorType, + factorFriendlyName: this.factorFriendlyName, + token: this.token, + url: this.url, + ttl: this.ttl, + dateCreated: this.dateCreated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AccessTokenSolution { + serviceSid: string; +} + +export interface AccessTokenListInstance { + _version: V2; + _solution: AccessTokenSolution; + _uri: string; + + (sid: string, ): AccessTokenContext; + get(sid: string, ): AccessTokenContext; + + + + + /** + * Create a AccessTokenInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccessTokenInstance + */ + create(params: AccessTokenListInstanceCreateOptions, callback?: (error: Error | null, item?: AccessTokenInstance) => any): Promise<AccessTokenInstance>; + + /** + * Create a AccessTokenInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccessTokenInstance with HTTP metadata + */ + createWithHttpInfo(params: AccessTokenListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<AccessTokenInstance>) => any): Promise<ApiResponse<AccessTokenInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AccessTokenListInstance(version: V2, serviceSid: string): AccessTokenListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as AccessTokenListInstance; + + instance.get = function get(sid, ): AccessTokenContext { + return new AccessTokenContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/AccessTokens`; + + instance.create = function create(params: AccessTokenListInstanceCreateOptions, callback?: (error: Error | null, items: AccessTokenInstance) => any): Promise<AccessTokenInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + if (params["factorType"] === null || params["factorType"] === undefined) { + throw new Error('Required parameter "params[\'factorType\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + + data["FactorType"] = params["factorType"]; + if (params["factorFriendlyName"] !== undefined) + data["FactorFriendlyName"] = params["factorFriendlyName"]; + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AccessTokenInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: AccessTokenListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<AccessTokenInstance>) => any): Promise<ApiResponse<AccessTokenInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + if (params["factorType"] === null || params["factorType"] === undefined) { + throw new Error('Required parameter "params[\'factorType\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + + data["FactorType"] = params["factorType"]; + if (params["factorFriendlyName"] !== undefined) + data["FactorFriendlyName"] = params["factorFriendlyName"]; + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<AccessTokenResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<AccessTokenInstance> => ({ + ...response, + body: new AccessTokenInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/verify/v2/service/approveChallenge.ts b/rest/verify/v2/service/approveChallenge.ts new file mode 100644 index 000000000..e3fe12f35 --- /dev/null +++ b/rest/verify/v2/service/approveChallenge.ts @@ -0,0 +1,379 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class ApprovePasskeysChallengeRequest { + /** + * A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + */ + "id": string; + /** + * The globally unique identifier for this `PublicKeyCredential`. + */ + "rawId": string; + /** + * A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + */ + "authenticatorAttachment": string; + /** + * The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + */ + "type"?: string; + "response": ApprovePasskeysChallengeRequestResponse; + + constructor(payload) { + this.id = payload["id"]; + this.rawId = payload["rawId"]; + this.authenticatorAttachment = payload["authenticatorAttachment"]; + this.type = payload["type"]; + this.response = payload["response"]; + } +} + + +/** + * The result of a WebAuthn authentication via a `navigator.credentials.get()` request, as specified in [AuthenticatorAttestationResponse](https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse). + */ +export class ApprovePasskeysChallengeRequestResponse { + /** + * The [authenticator data](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data) structure contains information from the authenticator about the processing of a credential creation or authentication request. + */ + "authenticatorData": string; + /** + * This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + */ + "clientDataJSON": string; + /** + * An assertion signature over `authenticatorData` and `clientDataJSON`. The assertion signature is created with the private key of the key pair that was created during the originating `navigator.credentials.create()` call and verified using the public key of that same key pair. + */ + "signature": string; + /** + * The user handle stored in the authenticator, specified as `user.id` in the options passed to the originating `navigator.credentials.create()` call. This property should contain a base64url-encoded entity SID. + */ + "userHandle"?: string; + + constructor(payload) { + this.authenticatorData = payload["authenticatorData"]; + this.clientDataJSON = payload["clientDataJSON"]; + this.signature = payload["signature"]; + this.userHandle = payload["userHandle"]; + } +} + + + +/** + * Options to pass to update a ApproveChallengeInstance + */ +export interface ApproveChallengeListInstanceUpdateOptions { + /** */ + "approvePasskeysChallengeRequest": ApprovePasskeysChallengeRequest; +} + + +export interface ApproveChallengeSolution { + serviceSid: string; +} + +export interface ApproveChallengeListInstance { + _version: V2; + _solution: ApproveChallengeSolution; + _uri: string; + + + + /** + * Update a ApproveChallengeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApproveChallengeInstance + */ + update(params: ApprovePasskeysChallengeRequest, headers?: any, callback?: (error: Error | null, item?: ApproveChallengeInstance) => any): Promise<ApproveChallengeInstance>; + + /** + * Update a ApproveChallengeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ApproveChallengeInstance with HTTP metadata + */ + updateWithHttpInfo(params: ApprovePasskeysChallengeRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ApproveChallengeInstance>) => any): Promise<ApiResponse<ApproveChallengeInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ApproveChallengeListInstance(version: V2, serviceSid: string): ApproveChallengeListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = {} as ApproveChallengeListInstance; + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Passkeys/ApproveChallenge`; + + instance.update = function update(params: ApprovePasskeysChallengeRequest, headers?: any, callback?: (error: Error | null, items: ApproveChallengeInstance) => any): Promise<ApproveChallengeInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ApproveChallengeInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.updateWithHttpInfo = function updateWithHttpInfo(params: ApprovePasskeysChallengeRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<ApproveChallengeInstance>) => any): Promise<ApiResponse<ApproveChallengeInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ApproveChallengeResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ApproveChallengeInstance> => ({ + ...response, + body: new ApproveChallengeInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface ApproveChallengePayload extends ApproveChallengeResource {} + +interface ApproveChallengeResource { + sid: string; + account_sid: string; + service_sid: string; + entity_sid: string; + identity: string; + factor_sid: string; + date_created: Date; + date_updated: Date; + date_responded: Date; + expiration_date: Date; + status: string; + responded_reason: string; + details: any; + hidden_details: any; + metadata: any; + factor_type: string; + url: string; + links: Record<string, string>; + options: Record<string, object>; +} + +export class ApproveChallengeInstance { + + constructor(protected _version: V2, payload: ApproveChallengeResource, serviceSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.entitySid = (payload.entity_sid); + this.identity = (payload.identity); + this.factorSid = (payload.factor_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.dateResponded = deserialize.iso8601DateTime(payload.date_responded); + this.expirationDate = deserialize.iso8601DateTime(payload.expiration_date); + this.status = (payload.status); + this.respondedReason = (payload.responded_reason); + this.details = (payload.details); + this.hiddenDetails = (payload.hidden_details); + this.metadata = (payload.metadata); + this.factorType = (payload.factor_type); + this.url = (payload.url); + this.links = (payload.links); + this.options = (payload.options); + + } + + /** + * A 34 character string that uniquely identifies this Challenge. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The unique SID identifier of the Entity. + */ + entitySid: string; + /** + * Customer unique identity for the Entity owner of the Challenge. + */ + identity: string; + /** + * The unique SID identifier of the Factor. + */ + factorSid: string; + /** + * The date that this Challenge was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date that this Challenge was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The date that this Challenge was responded, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateResponded: Date; + /** + * The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + expirationDate: Date; + /** + * The Status of this Challenge. One of `pending`, `expired`, `approved` or `denied`. + */ + status: string; + /** + * Reason for the Challenge to be in certain `status`. One of `none`, `not_needed` or `not_requested`. + */ + respondedReason: string; + /** + * Details provided to give context about the Challenge. + */ + details: any; + /** + * Details provided to give context about the Challenge. + */ + hiddenDetails: any; + /** + * Custom metadata associated with the challenge. + */ + metadata: any; + /** + * The Factor Type of this Challenge. Currently `push` and `totp` are supported. + */ + factorType: string; + /** + * The URL of this resource. + */ + url: string; + /** + * Contains a dictionary of URL links to nested resources of this Challenge. + */ + links: Record<string, string>; + /** + * An object that contains challenge options. Currently only used for `passkeys`. + */ + options: Record<string, object>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + entitySid: this.entitySid, + identity: this.identity, + factorSid: this.factorSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + dateResponded: this.dateResponded, + expirationDate: this.expirationDate, + status: this.status, + respondedReason: this.respondedReason, + details: this.details, + hiddenDetails: this.hiddenDetails, + metadata: this.metadata, + factorType: this.factorType, + url: this.url, + links: this.links, + options: this.options, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/verify/v2/service/entity.ts b/rest/verify/v2/service/entity.ts new file mode 100644 index 000000000..e528f9a99 --- /dev/null +++ b/rest/verify/v2/service/entity.ts @@ -0,0 +1,798 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { ChallengeListInstance } from "./entity/challenge"; +import { FactorListInstance } from "./entity/factor"; +import { NewFactorListInstance } from "./entity/newFactor"; + + + + + +/** + * Options to pass to create a EntityInstance + */ +export interface EntityListInstanceCreateOptions { + /** The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user\\\'s UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. */ + "identity": string; +} + +/** + * Options to pass to each + */ +export interface EntityListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: EntityInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface EntityListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface EntityListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface EntityContext { + challenges: ChallengeListInstance; + factors: FactorListInstance; + newFactors: NewFactorListInstance; + + /** + * Remove a EntityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a EntityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a EntityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EntityInstance + */ + fetch(callback?: (error: Error | null, item?: EntityInstance) => any): Promise<EntityInstance> + + /** + * Fetch a EntityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EntityInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EntityInstance>) => any): Promise<ApiResponse<EntityInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface EntityContextSolution { + "serviceSid": string; + "identity": string; +} + +export class EntityContextImpl implements EntityContext { + protected _solution: EntityContextSolution; + protected _uri: string; + + protected _challenges?: ChallengeListInstance; + protected _factors?: FactorListInstance; + protected _newFactors?: NewFactorListInstance; + + constructor(protected _version: V2, serviceSid: string, identity: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(identity)) { + throw new Error('Parameter \'identity\' is not valid.'); + } + + this._solution = { serviceSid, identity, }; + this._uri = `/Services/${serviceSid}/Entities/${identity}`; + } + + get challenges(): ChallengeListInstance { + this._challenges = this._challenges || ChallengeListInstance(this._version, this._solution.serviceSid, this._solution.identity); + return this._challenges; + } + + get factors(): FactorListInstance { + this._factors = this._factors || FactorListInstance(this._version, this._solution.serviceSid, this._solution.identity); + return this._factors; + } + + get newFactors(): NewFactorListInstance { + this._newFactors = this._newFactors || NewFactorListInstance(this._version, this._solution.serviceSid, this._solution.identity); + return this._newFactors; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: EntityInstance) => any): Promise<EntityInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new EntityInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.identity)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EntityInstance>) => any): Promise<ApiResponse<EntityInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<EntityResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<EntityInstance> => ({ + ...response, + body: new EntityInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.identity) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface EntityPayload extends TwilioResponsePayload { + entities: EntityResource[]; +} + +interface EntityResource { + sid: string; + identity: string; + account_sid: string; + service_sid: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class EntityInstance { + protected _solution: EntityContextSolution; + protected _context?: EntityContext; + + constructor(protected _version: V2, payload: EntityResource, serviceSid: string, identity?: string) { + + this.sid = (payload.sid); + this.identity = (payload.identity); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, identity: identity, }; + } + + /** + * A 34 character string that uniquely identifies this Entity. + */ + sid: string; + /** + * The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user\'s UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + */ + identity: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The date that this Entity was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date that this Entity was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + /** + * Contains a dictionary of URL links to nested resources of this Entity. + */ + links: Record<string, string>; + + private get _proxy(): EntityContext { + this._context = this._context || new EntityContextImpl(this._version, this._solution.serviceSid, this._solution.identity); + return this._context; + } + + /** + * Remove a EntityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a EntityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a EntityInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EntityInstance + */ + fetch(callback?: (error: Error | null, item?: EntityInstance) => any): Promise<EntityInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a EntityInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EntityInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<EntityInstance>) => any): Promise<ApiResponse<EntityInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the challenges. + */ + challenges(): ChallengeListInstance { + return this._proxy.challenges; + } + + /** + * Access the factors. + */ + factors(): FactorListInstance { + return this._proxy.factors; + } + + /** + * Access the newFactors. + */ + newFactors(): NewFactorListInstance { + return this._proxy.newFactors; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + identity: this.identity, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface EntitySolution { + serviceSid: string; +} + +export interface EntityListInstance { + _version: V2; + _solution: EntitySolution; + _uri: string; + + (identity: string, ): EntityContext; + get(identity: string, ): EntityContext; + + + + + + + /** + * Create a EntityInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EntityInstance + */ + create(params: EntityListInstanceCreateOptions, callback?: (error: Error | null, item?: EntityInstance) => any): Promise<EntityInstance>; + + /** + * Create a EntityInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed EntityInstance with HTTP metadata + */ + createWithHttpInfo(params: EntityListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<EntityInstance>) => any): Promise<ApiResponse<EntityInstance>>; + + + + + /** + * Streams EntityInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EntityListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: EntityInstance, done: (err?: Error) => void) => void): void; + each(params: EntityListInstanceEachOptions, callback?: (item: EntityInstance, done: (err?: Error) => void) => void): void; + /** + * Streams EntityInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EntityListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: EntityInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: EntityListInstanceEachOptions, callback?: (item: EntityInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of EntityInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: EntityPage) => any): Promise<EntityPage>; + /** + * Retrieve a single target page of EntityInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<EntityPage>) => any): Promise<ApiResponse<EntityPage>>; + /** + * Lists EntityInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EntityListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: EntityInstance[]) => any): Promise<EntityInstance[]>; + list(params: EntityListInstanceOptions, callback?: (error: Error | null, items: EntityInstance[]) => any): Promise<EntityInstance[]>; + /** + * Lists EntityInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EntityListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EntityInstance[]>) => any): Promise<ApiResponse<EntityInstance[]>>; + listWithHttpInfo(params: EntityListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<EntityInstance[]>) => any): Promise<ApiResponse<EntityInstance[]>>; + /** + * Retrieve a single page of EntityInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EntityListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: EntityPage) => any): Promise<EntityPage>; + page(params: EntityListInstancePageOptions, callback?: (error: Error | null, items: EntityPage) => any): Promise<EntityPage>; + /** + * Retrieve a single page of EntityInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { EntityListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<EntityPage>) => any): Promise<ApiResponse<EntityPage>>; + pageWithHttpInfo(params: EntityListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<EntityPage>) => any): Promise<ApiResponse<EntityPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function EntityListInstance(version: V2, serviceSid: string): EntityListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((identity, ) => instance.get(identity, )) as EntityListInstance; + + instance.get = function get(identity, ): EntityContext { + return new EntityContextImpl(version, serviceSid, identity); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Entities`; + + instance.create = function create(params: EntityListInstanceCreateOptions, callback?: (error: Error | null, items: EntityInstance) => any): Promise<EntityInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new EntityInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: EntityListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<EntityInstance>) => any): Promise<ApiResponse<EntityInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["identity"] === null || params["identity"] === undefined) { + throw new Error('Required parameter "params[\'identity\']" missing.'); + } + + let data: any = {}; + + + + data["Identity"] = params["identity"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<EntityResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<EntityInstance> => ({ + ...response, + body: new EntityInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: EntityListInstancePageOptions | ((error: Error | null, items: EntityPage) => any), callback?: (error: Error | null, items: EntityPage) => any): Promise<EntityPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new EntityPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: EntityPage) => any): Promise<EntityPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new EntityPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: EntityListInstancePageOptions | ((error: Error | null, items: ApiResponse<EntityPage>) => any), callback?: (error: Error | null, items: ApiResponse<EntityPage>) => any): Promise<ApiResponse<EntityPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<EntityPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EntityPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<EntityPage>) => any): Promise<ApiResponse<EntityPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<EntityPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new EntityPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class EntityPage extends Page<V2, EntityPayload, EntityResource, EntityInstance> { +/** +* Initialize the EntityPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: EntitySolution) { + super(version, response, solution); + } + + /** + * Build an instance of EntityInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: EntityResource): EntityInstance { + + return new EntityInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/verify/v2/service/entity/challenge.ts b/rest/verify/v2/service/entity/challenge.ts new file mode 100644 index 000000000..036e61de9 --- /dev/null +++ b/rest/verify/v2/service/entity/challenge.ts @@ -0,0 +1,1006 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; +import { NotificationListInstance } from "./challenge/notification"; + + +/** + * Reason for the Challenge to be in certain `status`. One of `none`, `not_needed` or `not_requested`. + */ +export type ChallengeChallengeReasons = 'none'|'not_needed'|'not_requested'; + +/** + * The Status of this Challenge. One of `pending`, `expired`, `approved` or `denied`. + */ +export type ChallengeChallengeStatuses = 'pending'|'expired'|'approved'|'denied'; + +/** + * The Factor Type of this Challenge. Currently `push` and `totp` are supported. + */ +export type ChallengeFactorTypes = 'push'|'totp'|'passkeys'; + +export type ChallengeListOrders = 'asc'|'desc'; + + + +/** + * Options to pass to update a ChallengeInstance + */ +export interface ChallengeContextUpdateOptions { + /** The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length */ + "authPayload"?: string; + /** Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. */ + "metadata"?: any; +} + +/** + * Options to pass to create a ChallengeInstance + */ +export interface ChallengeListInstanceCreateOptions { + /** The unique SID identifier of the Factor. */ + "factorSid": string; + /** The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. */ + "expirationDate"?: Date; + /** Shown to the user when the push notification arrives. Required when `factor_type` is `push`. Can be up to 256 characters in length */ + "details.message"?: string; + /** A list of objects that describe the Fields included in the Challenge. Each object contains the label and value of the field, the label can be up to 36 characters in length and the value can be up to 128 characters in length. Used when `factor_type` is `push`. There can be up to 20 details fields. */ + "details.fields"?: Array<any>; + /** Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length */ + "hiddenDetails"?: any; + /** Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. */ + "authPayload"?: string; +} + +/** + * Options to pass to each + */ +export interface ChallengeListInstanceEachOptions { + /** The unique SID identifier of the Factor. */ + "factorSid"?: string; + /** The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. */ + "status"?: ChallengeChallengeStatuses; + /** The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. */ + "order"?: ChallengeListOrders; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ChallengeInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ChallengeListInstanceOptions { + /** The unique SID identifier of the Factor. */ + "factorSid"?: string; + /** The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. */ + "status"?: ChallengeChallengeStatuses; + /** The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. */ + "order"?: ChallengeListOrders; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ChallengeListInstancePageOptions { + /** The unique SID identifier of the Factor. */ + "factorSid"?: string; + /** The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. */ + "status"?: ChallengeChallengeStatuses; + /** The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. */ + "order"?: ChallengeListOrders; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ChallengeContext { + notifications: NotificationListInstance; + + /** + * Fetch a ChallengeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance + */ + fetch(callback?: (error: Error | null, item?: ChallengeInstance) => any): Promise<ChallengeInstance> + + /** + * Fetch a ChallengeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>> + + /** + * Update a ChallengeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance + */ + update(callback?: (error: Error | null, item?: ChallengeInstance) => any): Promise<ChallengeInstance>; + /** + * Update a ChallengeInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance + */ + update(params: ChallengeContextUpdateOptions, callback?: (error: Error | null, item?: ChallengeInstance) => any): Promise<ChallengeInstance>; + + /** + * Update a ChallengeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>>; + /** + * Update a ChallengeInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChallengeContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ChallengeContextSolution { + "serviceSid": string; + "identity": string; + "sid": string; +} + +export class ChallengeContextImpl implements ChallengeContext { + protected _solution: ChallengeContextSolution; + protected _uri: string; + + protected _notifications?: NotificationListInstance; + + constructor(protected _version: V2, serviceSid: string, identity: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(identity)) { + throw new Error('Parameter \'identity\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, identity, sid, }; + this._uri = `/Services/${serviceSid}/Entities/${identity}/Challenges/${sid}`; + } + + get notifications(): NotificationListInstance { + this._notifications = this._notifications || NotificationListInstance(this._version, this._solution.serviceSid, this._solution.identity, this._solution.sid); + return this._notifications; + } + + fetch(callback?: (error: Error | null, item?: ChallengeInstance) => any): Promise<ChallengeInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ChallengeInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.identity, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ChallengeResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ChallengeInstance> => ({ + ...response, + body: new ChallengeInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.identity, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ChallengeContextUpdateOptions | ((error: Error | null, item?: ChallengeInstance) => any),callback?: (error: Error | null, item?: ChallengeInstance) => any): Promise<ChallengeInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["authPayload"] !== undefined) + data["AuthPayload"] = params["authPayload"]; + if (params["metadata"] !== undefined) + data["Metadata"] = serialize.object(params["metadata"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChallengeInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.identity, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ChallengeContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ChallengeInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["authPayload"] !== undefined) + data["AuthPayload"] = params["authPayload"]; + if (params["metadata"] !== undefined) + data["Metadata"] = serialize.object(params["metadata"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ChallengeResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ChallengeInstance> => ({ + ...response, + body: new ChallengeInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.identity, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ChallengePayload extends TwilioResponsePayload { + challenges: ChallengeResource[]; +} + +interface ChallengeResource { + sid: string; + account_sid: string; + service_sid: string; + entity_sid: string; + identity: string; + factor_sid: string; + date_created: Date; + date_updated: Date; + date_responded: Date; + expiration_date: Date; + status: ChallengeChallengeStatuses; + responded_reason: ChallengeChallengeReasons; + details: any; + hidden_details: any; + metadata: any; + factor_type: ChallengeFactorTypes; + url: string; + links: Record<string, string>; +} + +export class ChallengeInstance { + protected _solution: ChallengeContextSolution; + protected _context?: ChallengeContext; + + constructor(protected _version: V2, payload: ChallengeResource, serviceSid: string, identity: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.entitySid = (payload.entity_sid); + this.identity = (payload.identity); + this.factorSid = (payload.factor_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.dateResponded = deserialize.iso8601DateTime(payload.date_responded); + this.expirationDate = deserialize.iso8601DateTime(payload.expiration_date); + this.status = payload.status; + this.respondedReason = payload.responded_reason; + this.details = (payload.details); + this.hiddenDetails = (payload.hidden_details); + this.metadata = (payload.metadata); + this.factorType = payload.factor_type; + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, identity, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this Challenge. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The unique SID identifier of the Entity. + */ + entitySid: string; + /** + * Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user\'s UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + */ + identity: string; + /** + * The unique SID identifier of the Factor. + */ + factorSid: string; + /** + * The date that this Challenge was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date that this Challenge was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The date that this Challenge was responded, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateResponded: Date; + /** + * The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. + */ + expirationDate: Date; + status: ChallengeChallengeStatuses; + respondedReason: ChallengeChallengeReasons; + /** + * Details provided to give context about the Challenge. Intended to be shown to the end user. + */ + details: any; + /** + * Details provided to give context about the Challenge. Intended to be hidden from the end user. It must be a stringified JSON with only strings values eg. `{\"ip\": \"172.168.1.234\"}` + */ + hiddenDetails: any; + /** + * Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\"os\": \"Android\"}`. Can be up to 1024 characters in length. + */ + metadata: any; + factorType: ChallengeFactorTypes; + /** + * The URL of this resource. + */ + url: string; + /** + * Contains a dictionary of URL links to nested resources of this Challenge. + */ + links: Record<string, string>; + + private get _proxy(): ChallengeContext { + this._context = this._context || new ChallengeContextImpl(this._version, this._solution.serviceSid, this._solution.identity, this._solution.sid); + return this._context; + } + + /** + * Fetch a ChallengeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance + */ + fetch(callback?: (error: Error | null, item?: ChallengeInstance) => any): Promise<ChallengeInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ChallengeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ChallengeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance + */ + update(callback?: (error: Error | null, item?: ChallengeInstance) => any): Promise<ChallengeInstance>; + /** + * Update a ChallengeInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance + */ + update(params: ChallengeContextUpdateOptions, callback?: (error: Error | null, item?: ChallengeInstance) => any): Promise<ChallengeInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ChallengeInstance) => any): Promise<ChallengeInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ChallengeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>>; + /** + * Update a ChallengeInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance with HTTP metadata + */ + updateWithHttpInfo(params: ChallengeContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the notifications. + */ + notifications(): NotificationListInstance { + return this._proxy.notifications; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + entitySid: this.entitySid, + identity: this.identity, + factorSid: this.factorSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + dateResponded: this.dateResponded, + expirationDate: this.expirationDate, + status: this.status, + respondedReason: this.respondedReason, + details: this.details, + hiddenDetails: this.hiddenDetails, + metadata: this.metadata, + factorType: this.factorType, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ChallengeSolution { + serviceSid: string; + identity: string; +} + +export interface ChallengeListInstance { + _version: V2; + _solution: ChallengeSolution; + _uri: string; + + (sid: string, ): ChallengeContext; + get(sid: string, ): ChallengeContext; + + + + + + + /** + * Create a ChallengeInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance + */ + create(params: ChallengeListInstanceCreateOptions, callback?: (error: Error | null, item?: ChallengeInstance) => any): Promise<ChallengeInstance>; + + /** + * Create a ChallengeInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ChallengeInstance with HTTP metadata + */ + createWithHttpInfo(params: ChallengeListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>>; + + + + + /** + * Streams ChallengeInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChallengeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ChallengeInstance, done: (err?: Error) => void) => void): void; + each(params: ChallengeListInstanceEachOptions, callback?: (item: ChallengeInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ChallengeInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChallengeListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ChallengeInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ChallengeListInstanceEachOptions, callback?: (item: ChallengeInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ChallengeInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ChallengePage) => any): Promise<ChallengePage>; + /** + * Retrieve a single target page of ChallengeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ChallengePage>) => any): Promise<ApiResponse<ChallengePage>>; + /** + * Lists ChallengeInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChallengeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ChallengeInstance[]) => any): Promise<ChallengeInstance[]>; + list(params: ChallengeListInstanceOptions, callback?: (error: Error | null, items: ChallengeInstance[]) => any): Promise<ChallengeInstance[]>; + /** + * Lists ChallengeInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChallengeListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ChallengeInstance[]>) => any): Promise<ApiResponse<ChallengeInstance[]>>; + listWithHttpInfo(params: ChallengeListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ChallengeInstance[]>) => any): Promise<ApiResponse<ChallengeInstance[]>>; + /** + * Retrieve a single page of ChallengeInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChallengeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ChallengePage) => any): Promise<ChallengePage>; + page(params: ChallengeListInstancePageOptions, callback?: (error: Error | null, items: ChallengePage) => any): Promise<ChallengePage>; + /** + * Retrieve a single page of ChallengeInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ChallengeListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ChallengePage>) => any): Promise<ApiResponse<ChallengePage>>; + pageWithHttpInfo(params: ChallengeListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ChallengePage>) => any): Promise<ApiResponse<ChallengePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ChallengeListInstance(version: V2, serviceSid: string, identity: string): ChallengeListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(identity)) { + throw new Error('Parameter \'identity\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ChallengeListInstance; + + instance.get = function get(sid, ): ChallengeContext { + return new ChallengeContextImpl(version, serviceSid, identity, sid); + } + + instance._version = version; + instance._solution = { serviceSid, identity, }; + instance._uri = `/Services/${serviceSid}/Entities/${identity}/Challenges`; + + instance.create = function create(params: ChallengeListInstanceCreateOptions, callback?: (error: Error | null, items: ChallengeInstance) => any): Promise<ChallengeInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["factorSid"] === null || params["factorSid"] === undefined) { + throw new Error('Required parameter "params[\'factorSid\']" missing.'); + } + + let data: any = {}; + + + + data["FactorSid"] = params["factorSid"]; + if (params["expirationDate"] !== undefined) + data["ExpirationDate"] = serialize.iso8601DateTime(params["expirationDate"]); + if (params["details.message"] !== undefined) + data["Details.Message"] = params["details.message"]; + if (params["details.fields"] !== undefined) + data["Details.Fields"] = serialize.map(params["details.fields"], (e: any) => serialize.object(e)); + if (params["hiddenDetails"] !== undefined) + data["HiddenDetails"] = serialize.object(params["hiddenDetails"]); + if (params["authPayload"] !== undefined) + data["AuthPayload"] = params["authPayload"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ChallengeInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.identity)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ChallengeListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ChallengeInstance>) => any): Promise<ApiResponse<ChallengeInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["factorSid"] === null || params["factorSid"] === undefined) { + throw new Error('Required parameter "params[\'factorSid\']" missing.'); + } + + let data: any = {}; + + + + data["FactorSid"] = params["factorSid"]; + if (params["expirationDate"] !== undefined) + data["ExpirationDate"] = serialize.iso8601DateTime(params["expirationDate"]); + if (params["details.message"] !== undefined) + data["Details.Message"] = params["details.message"]; + if (params["details.fields"] !== undefined) + data["Details.Fields"] = serialize.map(params["details.fields"], (e: any) => serialize.object(e)); + if (params["hiddenDetails"] !== undefined) + data["HiddenDetails"] = serialize.object(params["hiddenDetails"]); + if (params["authPayload"] !== undefined) + data["AuthPayload"] = params["authPayload"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ChallengeResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ChallengeInstance> => ({ + ...response, + body: new ChallengeInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.identity) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ChallengeListInstancePageOptions | ((error: Error | null, items: ChallengePage) => any), callback?: (error: Error | null, items: ChallengePage) => any): Promise<ChallengePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["factorSid"] !== undefined) + data["FactorSid"] = params["factorSid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ChallengePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ChallengePage) => any): Promise<ChallengePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ChallengePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ChallengeListInstancePageOptions | ((error: Error | null, items: ApiResponse<ChallengePage>) => any), callback?: (error: Error | null, items: ApiResponse<ChallengePage>) => any): Promise<ApiResponse<ChallengePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["factorSid"] !== undefined) + data["FactorSid"] = params["factorSid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["order"] !== undefined) + data["Order"] = params["order"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ChallengePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChallengePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ChallengePage>) => any): Promise<ApiResponse<ChallengePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ChallengePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ChallengePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ChallengePage extends Page<V2, ChallengePayload, ChallengeResource, ChallengeInstance> { +/** +* Initialize the ChallengePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: ChallengeSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ChallengeInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ChallengeResource): ChallengeInstance { + + return new ChallengeInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.identity, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/verify/v2/service/entity/challenge/notification.ts b/rest/verify/v2/service/entity/challenge/notification.ts new file mode 100644 index 000000000..33e47e678 --- /dev/null +++ b/rest/verify/v2/service/entity/challenge/notification.ts @@ -0,0 +1,280 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../../../V2"; +const deserialize = require("../../../../../../base/deserialize"); +const serialize = require("../../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../../base/utility"; +import { ApiResponse } from "../../../../../../base/ApiResponse"; + + + +/** + * Options to pass to create a NotificationInstance + */ +export interface NotificationListInstanceCreateOptions { + /** How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. */ + "ttl"?: number; +} + + +export interface NotificationSolution { + serviceSid: string; + identity: string; + challengeSid: string; +} + +export interface NotificationListInstance { + _version: V2; + _solution: NotificationSolution; + _uri: string; + + + + /** + * Create a NotificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + create(callback?: (error: Error | null, item?: NotificationInstance) => any): Promise<NotificationInstance>; + /** + * Create a NotificationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance + */ + create(params: NotificationListInstanceCreateOptions, callback?: (error: Error | null, item?: NotificationInstance) => any): Promise<NotificationInstance>; + + /** + * Create a NotificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<NotificationInstance>) => any): Promise<ApiResponse<NotificationInstance>>; + /** + * Create a NotificationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NotificationInstance with HTTP metadata + */ + createWithHttpInfo(params: NotificationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<NotificationInstance>) => any): Promise<ApiResponse<NotificationInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NotificationListInstance(version: V2, serviceSid: string, identity: string, challengeSid: string): NotificationListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(identity)) { + throw new Error('Parameter \'identity\' is not valid.'); + } + + if (!isValidPathParam(challengeSid)) { + throw new Error('Parameter \'challengeSid\' is not valid.'); + } + + const instance = {} as NotificationListInstance; + + instance._version = version; + instance._solution = { serviceSid, identity, challengeSid, }; + instance._uri = `/Services/${serviceSid}/Entities/${identity}/Challenges/${challengeSid}/Notifications`; + + instance.create = function create(params?: NotificationListInstanceCreateOptions | ((error: Error | null, items: NotificationInstance) => any), callback?: (error: Error | null, items: NotificationInstance) => any): Promise<NotificationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NotificationInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.identity, instance._solution.challengeSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: NotificationListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<NotificationInstance>) => any), callback?: (error: Error | null, items: ApiResponse<NotificationInstance>) => any): Promise<ApiResponse<NotificationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["ttl"] !== undefined) + data["Ttl"] = params["ttl"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<NotificationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<NotificationInstance> => ({ + ...response, + body: new NotificationInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.identity, instance._solution.challengeSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface NotificationPayload extends NotificationResource {} + +interface NotificationResource { + sid: string; + account_sid: string; + service_sid: string; + entity_sid: string; + identity: string; + challenge_sid: string; + priority: string; + ttl: number; + date_created: Date; +} + +export class NotificationInstance { + + constructor(protected _version: V2, payload: NotificationResource, serviceSid: string, identity: string, challengeSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.entitySid = (payload.entity_sid); + this.identity = (payload.identity); + this.challengeSid = (payload.challenge_sid); + this.priority = (payload.priority); + this.ttl = deserialize.integer(payload.ttl); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + + } + + /** + * A 34 character string that uniquely identifies this Notification. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The unique SID identifier of the Entity. + */ + entitySid: string; + /** + * Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user\'s UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + */ + identity: string; + /** + * The unique SID identifier of the Challenge. + */ + challengeSid: string; + /** + * The priority of the notification. For `push` Challenges it\'s always `high` which sends the notification immediately, and can wake up a sleeping device. + */ + priority: string; + /** + * How long, in seconds, the notification is valid. Max: 5 minutes + */ + ttl: number; + /** + * The date that this Notification was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + entitySid: this.entitySid, + identity: this.identity, + challengeSid: this.challengeSid, + priority: this.priority, + ttl: this.ttl, + dateCreated: this.dateCreated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/verify/v2/service/entity/factor.ts b/rest/verify/v2/service/entity/factor.ts new file mode 100644 index 000000000..7c40d716d --- /dev/null +++ b/rest/verify/v2/service/entity/factor.ts @@ -0,0 +1,915 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The Status of this Factor. One of `unverified` or `verified`. + */ +export type FactorFactorStatuses = 'unverified'|'verified'; + +/** + * The Type of this Factor. Currently `push` and `totp` are supported. + */ +export type FactorFactorTypes = 'push'|'totp'|'passkeys'; + +export type FactorTotpAlgorithms = 'sha1'|'sha256'|'sha512'; + + + + +/** + * Options to pass to update a FactorInstance + */ +export interface FactorContextUpdateOptions { + /** The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. */ + "authPayload"?: string; + /** The new friendly name of this Factor. It can be up to 64 characters. */ + "friendlyName"?: string; + /** For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. */ + "config.notificationToken"?: string; + /** The Verify Push SDK version used to configure the factor */ + "config.sdkVersion"?: string; + /** Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive */ + "config.timeStep"?: number; + /** The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive */ + "config.skew"?: number; + /** Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive */ + "config.codeLength"?: number; + /** */ + "config.alg"?: FactorTotpAlgorithms; + /** The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. */ + "config.notificationPlatform"?: string; +} + +/** + * Options to pass to each + */ +export interface FactorListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: FactorInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface FactorListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface FactorListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface FactorContext { + + /** + * Remove a FactorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a FactorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a FactorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance + */ + fetch(callback?: (error: Error | null, item?: FactorInstance) => any): Promise<FactorInstance> + + /** + * Fetch a FactorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FactorInstance>) => any): Promise<ApiResponse<FactorInstance>> + + /** + * Update a FactorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance + */ + update(callback?: (error: Error | null, item?: FactorInstance) => any): Promise<FactorInstance>; + /** + * Update a FactorInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance + */ + update(params: FactorContextUpdateOptions, callback?: (error: Error | null, item?: FactorInstance) => any): Promise<FactorInstance>; + + /** + * Update a FactorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FactorInstance>) => any): Promise<ApiResponse<FactorInstance>>; + /** + * Update a FactorInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance with HTTP metadata + */ + updateWithHttpInfo(params: FactorContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FactorInstance>) => any): Promise<ApiResponse<FactorInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface FactorContextSolution { + "serviceSid": string; + "identity": string; + "sid": string; +} + +export class FactorContextImpl implements FactorContext { + protected _solution: FactorContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, identity: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(identity)) { + throw new Error('Parameter \'identity\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, identity, sid, }; + this._uri = `/Services/${serviceSid}/Entities/${identity}/Factors/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: FactorInstance) => any): Promise<FactorInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new FactorInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.identity, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FactorInstance>) => any): Promise<ApiResponse<FactorInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<FactorResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<FactorInstance> => ({ + ...response, + body: new FactorInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.identity, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: FactorContextUpdateOptions | ((error: Error | null, item?: FactorInstance) => any),callback?: (error: Error | null, item?: FactorInstance) => any): Promise<FactorInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["authPayload"] !== undefined) + data["AuthPayload"] = params["authPayload"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["config.notificationToken"] !== undefined) + data["Config.NotificationToken"] = params["config.notificationToken"]; + if (params["config.sdkVersion"] !== undefined) + data["Config.SdkVersion"] = params["config.sdkVersion"]; + if (params["config.timeStep"] !== undefined) + data["Config.TimeStep"] = params["config.timeStep"]; + if (params["config.skew"] !== undefined) + data["Config.Skew"] = params["config.skew"]; + if (params["config.codeLength"] !== undefined) + data["Config.CodeLength"] = params["config.codeLength"]; + if (params["config.alg"] !== undefined) + data["Config.Alg"] = params["config.alg"]; + if (params["config.notificationPlatform"] !== undefined) + data["Config.NotificationPlatform"] = params["config.notificationPlatform"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new FactorInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.identity, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: FactorContextUpdateOptions | ((error: Error | null, item?: ApiResponse<FactorInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<FactorInstance>) => any): Promise<ApiResponse<FactorInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["authPayload"] !== undefined) + data["AuthPayload"] = params["authPayload"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["config.notificationToken"] !== undefined) + data["Config.NotificationToken"] = params["config.notificationToken"]; + if (params["config.sdkVersion"] !== undefined) + data["Config.SdkVersion"] = params["config.sdkVersion"]; + if (params["config.timeStep"] !== undefined) + data["Config.TimeStep"] = params["config.timeStep"]; + if (params["config.skew"] !== undefined) + data["Config.Skew"] = params["config.skew"]; + if (params["config.codeLength"] !== undefined) + data["Config.CodeLength"] = params["config.codeLength"]; + if (params["config.alg"] !== undefined) + data["Config.Alg"] = params["config.alg"]; + if (params["config.notificationPlatform"] !== undefined) + data["Config.NotificationPlatform"] = params["config.notificationPlatform"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<FactorResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<FactorInstance> => ({ + ...response, + body: new FactorInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.identity, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface FactorPayload extends TwilioResponsePayload { + factors: FactorResource[]; +} + +interface FactorResource { + sid: string; + account_sid: string; + service_sid: string; + entity_sid: string; + identity: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + status: FactorFactorStatuses; + factor_type: FactorFactorTypes; + config: any; + metadata: any; + url: string; +} + +export class FactorInstance { + protected _solution: FactorContextSolution; + protected _context?: FactorContext; + + constructor(protected _version: V2, payload: FactorResource, serviceSid: string, identity: string, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.entitySid = (payload.entity_sid); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.factorType = payload.factor_type; + this.config = (payload.config); + this.metadata = (payload.metadata); + this.url = (payload.url); + + this._solution = { serviceSid, identity, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this Factor. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The unique SID identifier of the Entity. + */ + entitySid: string; + /** + * Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user\'s UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + */ + identity: string; + /** + * The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * A human readable description of this resource, up to 64 characters. For a push factor, this can be the device\'s name. + */ + friendlyName: string; + status: FactorFactorStatuses; + factorType: FactorFactorTypes; + /** + * An object that contains configurations specific to a `factor_type`. + */ + config: any; + /** + * Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\"os\": \"Android\"}`. Can be up to 1024 characters in length. + */ + metadata: any; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): FactorContext { + this._context = this._context || new FactorContextImpl(this._version, this._solution.serviceSid, this._solution.identity, this._solution.sid); + return this._context; + } + + /** + * Remove a FactorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a FactorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a FactorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance + */ + fetch(callback?: (error: Error | null, item?: FactorInstance) => any): Promise<FactorInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a FactorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FactorInstance>) => any): Promise<ApiResponse<FactorInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a FactorInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance + */ + update(callback?: (error: Error | null, item?: FactorInstance) => any): Promise<FactorInstance>; + /** + * Update a FactorInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance + */ + update(params: FactorContextUpdateOptions, callback?: (error: Error | null, item?: FactorInstance) => any): Promise<FactorInstance>; + + update(params?: any, callback?: (error: Error | null, item?: FactorInstance) => any): Promise<FactorInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a FactorInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<FactorInstance>) => any): Promise<ApiResponse<FactorInstance>>; + /** + * Update a FactorInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed FactorInstance with HTTP metadata + */ + updateWithHttpInfo(params: FactorContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<FactorInstance>) => any): Promise<ApiResponse<FactorInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<FactorInstance>) => any): Promise<ApiResponse<FactorInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + entitySid: this.entitySid, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + status: this.status, + factorType: this.factorType, + config: this.config, + metadata: this.metadata, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface FactorSolution { + serviceSid: string; + identity: string; +} + +export interface FactorListInstance { + _version: V2; + _solution: FactorSolution; + _uri: string; + + (sid: string, ): FactorContext; + get(sid: string, ): FactorContext; + + + + + + + + + + /** + * Streams FactorInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FactorListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: FactorInstance, done: (err?: Error) => void) => void): void; + each(params: FactorListInstanceEachOptions, callback?: (item: FactorInstance, done: (err?: Error) => void) => void): void; + /** + * Streams FactorInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FactorListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: FactorInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: FactorListInstanceEachOptions, callback?: (item: FactorInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of FactorInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: FactorPage) => any): Promise<FactorPage>; + /** + * Retrieve a single target page of FactorInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<FactorPage>) => any): Promise<ApiResponse<FactorPage>>; + /** + * Lists FactorInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FactorListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: FactorInstance[]) => any): Promise<FactorInstance[]>; + list(params: FactorListInstanceOptions, callback?: (error: Error | null, items: FactorInstance[]) => any): Promise<FactorInstance[]>; + /** + * Lists FactorInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FactorListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FactorInstance[]>) => any): Promise<ApiResponse<FactorInstance[]>>; + listWithHttpInfo(params: FactorListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<FactorInstance[]>) => any): Promise<ApiResponse<FactorInstance[]>>; + /** + * Retrieve a single page of FactorInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FactorListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: FactorPage) => any): Promise<FactorPage>; + page(params: FactorListInstancePageOptions, callback?: (error: Error | null, items: FactorPage) => any): Promise<FactorPage>; + /** + * Retrieve a single page of FactorInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { FactorListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<FactorPage>) => any): Promise<ApiResponse<FactorPage>>; + pageWithHttpInfo(params: FactorListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<FactorPage>) => any): Promise<ApiResponse<FactorPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function FactorListInstance(version: V2, serviceSid: string, identity: string): FactorListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(identity)) { + throw new Error('Parameter \'identity\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as FactorListInstance; + + instance.get = function get(sid, ): FactorContext { + return new FactorContextImpl(version, serviceSid, identity, sid); + } + + instance._version = version; + instance._solution = { serviceSid, identity, }; + instance._uri = `/Services/${serviceSid}/Entities/${identity}/Factors`; + + instance.page = function page(params?: FactorListInstancePageOptions | ((error: Error | null, items: FactorPage) => any), callback?: (error: Error | null, items: FactorPage) => any): Promise<FactorPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new FactorPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: FactorPage) => any): Promise<FactorPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new FactorPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: FactorListInstancePageOptions | ((error: Error | null, items: ApiResponse<FactorPage>) => any), callback?: (error: Error | null, items: ApiResponse<FactorPage>) => any): Promise<ApiResponse<FactorPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<FactorPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FactorPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<FactorPage>) => any): Promise<ApiResponse<FactorPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<FactorPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new FactorPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class FactorPage extends Page<V2, FactorPayload, FactorResource, FactorInstance> { +/** +* Initialize the FactorPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: FactorSolution) { + super(version, response, solution); + } + + /** + * Build an instance of FactorInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: FactorResource): FactorInstance { + + return new FactorInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.identity, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/verify/v2/service/entity/newFactor.ts b/rest/verify/v2/service/entity/newFactor.ts new file mode 100644 index 000000000..6b1dbc882 --- /dev/null +++ b/rest/verify/v2/service/entity/newFactor.ts @@ -0,0 +1,394 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The Status of this Factor. One of `unverified` or `verified`. + */ +export type NewFactorFactorStatuses = 'unverified'|'verified'; + +/** + * The Type of this Factor. Currently `push` and `totp` are supported. + */ +export type NewFactorFactorTypes = 'push'|'totp'|'passkeys'; + +export type NewFactorNotificationPlatforms = 'apn'|'fcm'|'none'; + +export type NewFactorTotpAlgorithms = 'sha1'|'sha256'|'sha512'; + + +/** + * Options to pass to create a NewFactorInstance + */ +export interface NewFactorListInstanceCreateOptions { + /** The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. */ + "friendlyName": string; + /** */ + "factorType": NewFactorFactorTypes; + /** The algorithm used when `factor_type` is `push`. Algorithm supported: `ES256` */ + "binding.alg"?: string; + /** The Ecdsa public key in PKIX, ASN.1 DER format encoded in Base64. Required when `factor_type` is `push` */ + "binding.publicKey"?: string; + /** The ID that uniquely identifies your app in the Google or Apple store, such as `com.example.myapp`. It can be up to 100 characters long. Required when `factor_type` is `push`. */ + "config.appId"?: string; + /** */ + "config.notificationPlatform"?: NewFactorNotificationPlatforms; + /** For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Must be between 32 and 255 characters long. Required when `factor_type` is `push`. */ + "config.notificationToken"?: string; + /** The Verify Push SDK version used to configure the factor Required when `factor_type` is `push` */ + "config.sdkVersion"?: string; + /** The shared secret for TOTP factors encoded in Base32. This can be provided when creating the Factor, otherwise it will be generated. Used when `factor_type` is `totp` */ + "binding.secret"?: string; + /** Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. The default value is defined at the service level in the property `totp.time_step`. Defaults to 30 seconds if not configured. Used when `factor_type` is `totp` */ + "config.timeStep"?: number; + /** The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. The default value is defined at the service level in the property `totp.skew`. If not configured defaults to 1. Used when `factor_type` is `totp` */ + "config.skew"?: number; + /** Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. The default value is defined at the service level in the property `totp.code_length`. If not configured defaults to 6. Used when `factor_type` is `totp` */ + "config.codeLength"?: number; + /** */ + "config.alg"?: NewFactorTotpAlgorithms; + /** Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. */ + "metadata"?: any; +} + + +export interface NewFactorSolution { + serviceSid: string; + identity: string; +} + +export interface NewFactorListInstance { + _version: V2; + _solution: NewFactorSolution; + _uri: string; + + + + /** + * Create a NewFactorInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewFactorInstance + */ + create(params: NewFactorListInstanceCreateOptions, callback?: (error: Error | null, item?: NewFactorInstance) => any): Promise<NewFactorInstance>; + + /** + * Create a NewFactorInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewFactorInstance with HTTP metadata + */ + createWithHttpInfo(params: NewFactorListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<NewFactorInstance>) => any): Promise<ApiResponse<NewFactorInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NewFactorListInstance(version: V2, serviceSid: string, identity: string): NewFactorListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(identity)) { + throw new Error('Parameter \'identity\' is not valid.'); + } + + const instance = {} as NewFactorListInstance; + + instance._version = version; + instance._solution = { serviceSid, identity, }; + instance._uri = `/Services/${serviceSid}/Entities/${identity}/Factors`; + + instance.create = function create(params: NewFactorListInstanceCreateOptions, callback?: (error: Error | null, items: NewFactorInstance) => any): Promise<NewFactorInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["factorType"] === null || params["factorType"] === undefined) { + throw new Error('Required parameter "params[\'factorType\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["FactorType"] = params["factorType"]; + if (params["binding.alg"] !== undefined) + data["Binding.Alg"] = params["binding.alg"]; + if (params["binding.publicKey"] !== undefined) + data["Binding.PublicKey"] = params["binding.publicKey"]; + if (params["config.appId"] !== undefined) + data["Config.AppId"] = params["config.appId"]; + if (params["config.notificationPlatform"] !== undefined) + data["Config.NotificationPlatform"] = params["config.notificationPlatform"]; + if (params["config.notificationToken"] !== undefined) + data["Config.NotificationToken"] = params["config.notificationToken"]; + if (params["config.sdkVersion"] !== undefined) + data["Config.SdkVersion"] = params["config.sdkVersion"]; + if (params["binding.secret"] !== undefined) + data["Binding.Secret"] = params["binding.secret"]; + if (params["config.timeStep"] !== undefined) + data["Config.TimeStep"] = params["config.timeStep"]; + if (params["config.skew"] !== undefined) + data["Config.Skew"] = params["config.skew"]; + if (params["config.codeLength"] !== undefined) + data["Config.CodeLength"] = params["config.codeLength"]; + if (params["config.alg"] !== undefined) + data["Config.Alg"] = params["config.alg"]; + if (params["metadata"] !== undefined) + data["Metadata"] = serialize.object(params["metadata"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NewFactorInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.identity)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: NewFactorListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<NewFactorInstance>) => any): Promise<ApiResponse<NewFactorInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["factorType"] === null || params["factorType"] === undefined) { + throw new Error('Required parameter "params[\'factorType\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["FactorType"] = params["factorType"]; + if (params["binding.alg"] !== undefined) + data["Binding.Alg"] = params["binding.alg"]; + if (params["binding.publicKey"] !== undefined) + data["Binding.PublicKey"] = params["binding.publicKey"]; + if (params["config.appId"] !== undefined) + data["Config.AppId"] = params["config.appId"]; + if (params["config.notificationPlatform"] !== undefined) + data["Config.NotificationPlatform"] = params["config.notificationPlatform"]; + if (params["config.notificationToken"] !== undefined) + data["Config.NotificationToken"] = params["config.notificationToken"]; + if (params["config.sdkVersion"] !== undefined) + data["Config.SdkVersion"] = params["config.sdkVersion"]; + if (params["binding.secret"] !== undefined) + data["Binding.Secret"] = params["binding.secret"]; + if (params["config.timeStep"] !== undefined) + data["Config.TimeStep"] = params["config.timeStep"]; + if (params["config.skew"] !== undefined) + data["Config.Skew"] = params["config.skew"]; + if (params["config.codeLength"] !== undefined) + data["Config.CodeLength"] = params["config.codeLength"]; + if (params["config.alg"] !== undefined) + data["Config.Alg"] = params["config.alg"]; + if (params["metadata"] !== undefined) + data["Metadata"] = serialize.object(params["metadata"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<NewFactorResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<NewFactorInstance> => ({ + ...response, + body: new NewFactorInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.identity) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface NewFactorPayload extends NewFactorResource {} + +interface NewFactorResource { + sid: string; + account_sid: string; + service_sid: string; + entity_sid: string; + identity: string; + binding: any; + options: any; + date_created: Date; + date_updated: Date; + friendly_name: string; + status: NewFactorFactorStatuses; + factor_type: NewFactorFactorTypes; + config: any; + metadata: any; + url: string; +} + +export class NewFactorInstance { + + constructor(protected _version: V2, payload: NewFactorResource, serviceSid: string, identity: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.entitySid = (payload.entity_sid); + this.identity = (payload.identity); + this.binding = (payload.binding); + this.options = (payload.options); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.status = payload.status; + this.factorType = payload.factor_type; + this.config = (payload.config); + this.metadata = (payload.metadata); + this.url = (payload.url); + + } + + /** + * A 34 character string that uniquely identifies this Factor. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The unique SID identifier of the Entity. + */ + entitySid: string; + /** + * Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user\'s UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + */ + identity: string; + /** + * Contains the `factor_type` specific secret and metadata. For push, this is `binding.public_key` and `binding.alg`. For totp, this is `binding.secret` and `binding.uri`. The `binding.uri` property is generated following the [google authenticator key URI format](https://github.com/google/google-authenticator/wiki/Key-Uri-Format), and `Factor.friendly_name` is used for the “accountname” value and `Service.friendly_name` or `Service.totp.issuer` is used for the `issuer` value. The Binding property is ONLY returned upon Factor creation. + */ + binding: any; + options: any; + /** + * The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. + */ + friendlyName: string; + status: NewFactorFactorStatuses; + factorType: NewFactorFactorTypes; + /** + * An object that contains configurations specific to a `factor_type`. + */ + config: any; + /** + * Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\"os\": \"Android\"}`. Can be up to 1024 characters in length. + */ + metadata: any; + /** + * The URL of this resource. + */ + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + entitySid: this.entitySid, + identity: this.identity, + binding: this.binding, + options: this.options, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + status: this.status, + factorType: this.factorType, + config: this.config, + metadata: this.metadata, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/verify/v2/service/messagingConfiguration.ts b/rest/verify/v2/service/messagingConfiguration.ts new file mode 100644 index 000000000..949f8cc30 --- /dev/null +++ b/rest/verify/v2/service/messagingConfiguration.ts @@ -0,0 +1,891 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a MessagingConfigurationInstance + */ +export interface MessagingConfigurationContextUpdateOptions { + /** The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. */ + "messagingServiceSid": string; +} + +/** + * Options to pass to create a MessagingConfigurationInstance + */ +export interface MessagingConfigurationListInstanceCreateOptions { + /** The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. */ + "country": string; + /** The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. */ + "messagingServiceSid": string; +} + +/** + * Options to pass to each + */ +export interface MessagingConfigurationListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: MessagingConfigurationInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface MessagingConfigurationListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface MessagingConfigurationListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface MessagingConfigurationContext { + + /** + * Remove a MessagingConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a MessagingConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a MessagingConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: MessagingConfigurationInstance) => any): Promise<MessagingConfigurationInstance> + + /** + * Fetch a MessagingConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<MessagingConfigurationInstance>) => any): Promise<ApiResponse<MessagingConfigurationInstance>> + + /** + * Update a MessagingConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingConfigurationInstance + */ + update(params: MessagingConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: MessagingConfigurationInstance) => any): Promise<MessagingConfigurationInstance>; + + /** + * Update a MessagingConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessagingConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<MessagingConfigurationInstance>) => any): Promise<ApiResponse<MessagingConfigurationInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface MessagingConfigurationContextSolution { + "serviceSid": string; + "country": string; +} + +export class MessagingConfigurationContextImpl implements MessagingConfigurationContext { + protected _solution: MessagingConfigurationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, country: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(country)) { + throw new Error('Parameter \'country\' is not valid.'); + } + + this._solution = { serviceSid, country, }; + this._uri = `/Services/${serviceSid}/MessagingConfigurations/${country}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: MessagingConfigurationInstance) => any): Promise<MessagingConfigurationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new MessagingConfigurationInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.country)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<MessagingConfigurationInstance>) => any): Promise<ApiResponse<MessagingConfigurationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<MessagingConfigurationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<MessagingConfigurationInstance> => ({ + ...response, + body: new MessagingConfigurationInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.country) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: MessagingConfigurationContextUpdateOptions,callback?: (error: Error | null, item?: MessagingConfigurationInstance) => any): Promise<MessagingConfigurationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["messagingServiceSid"] === null || params["messagingServiceSid"] === undefined) { + throw new Error('Required parameter "params[\'messagingServiceSid\']" missing.'); + } + + let data: any = {}; + + + + data["MessagingServiceSid"] = params["messagingServiceSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessagingConfigurationInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.country)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: MessagingConfigurationContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<MessagingConfigurationInstance>) => any): Promise<ApiResponse<MessagingConfigurationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["messagingServiceSid"] === null || params["messagingServiceSid"] === undefined) { + throw new Error('Required parameter "params[\'messagingServiceSid\']" missing.'); + } + + let data: any = {}; + + + + data["MessagingServiceSid"] = params["messagingServiceSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<MessagingConfigurationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<MessagingConfigurationInstance> => ({ + ...response, + body: new MessagingConfigurationInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.country) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface MessagingConfigurationPayload extends TwilioResponsePayload { + messaging_configurations: MessagingConfigurationResource[]; +} + +interface MessagingConfigurationResource { + account_sid: string; + service_sid: string; + country: string; + messaging_service_sid: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class MessagingConfigurationInstance { + protected _solution: MessagingConfigurationContextSolution; + protected _context?: MessagingConfigurationContext; + + constructor(protected _version: V2, payload: MessagingConfigurationResource, serviceSid: string, country?: string) { + + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.country = (payload.country); + this.messagingServiceSid = (payload.messaging_service_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, country: country, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/verify/api/service) that the resource is associated with. + */ + serviceSid: string; + /** + * The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + */ + country: string; + /** + * The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + */ + messagingServiceSid: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): MessagingConfigurationContext { + this._context = this._context || new MessagingConfigurationContextImpl(this._version, this._solution.serviceSid, this._solution.country); + return this._context; + } + + /** + * Remove a MessagingConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a MessagingConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a MessagingConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: MessagingConfigurationInstance) => any): Promise<MessagingConfigurationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a MessagingConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<MessagingConfigurationInstance>) => any): Promise<ApiResponse<MessagingConfigurationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a MessagingConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingConfigurationInstance + */ + update(params: MessagingConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: MessagingConfigurationInstance) => any): Promise<MessagingConfigurationInstance>; + + update(params?: any, callback?: (error: Error | null, item?: MessagingConfigurationInstance) => any): Promise<MessagingConfigurationInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a MessagingConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: MessagingConfigurationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<MessagingConfigurationInstance>) => any): Promise<ApiResponse<MessagingConfigurationInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<MessagingConfigurationInstance>) => any): Promise<ApiResponse<MessagingConfigurationInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + serviceSid: this.serviceSid, + country: this.country, + messagingServiceSid: this.messagingServiceSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface MessagingConfigurationSolution { + serviceSid: string; +} + +export interface MessagingConfigurationListInstance { + _version: V2; + _solution: MessagingConfigurationSolution; + _uri: string; + + (country: string, ): MessagingConfigurationContext; + get(country: string, ): MessagingConfigurationContext; + + + + + + + + + /** + * Create a MessagingConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingConfigurationInstance + */ + create(params: MessagingConfigurationListInstanceCreateOptions, callback?: (error: Error | null, item?: MessagingConfigurationInstance) => any): Promise<MessagingConfigurationInstance>; + + /** + * Create a MessagingConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed MessagingConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: MessagingConfigurationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<MessagingConfigurationInstance>) => any): Promise<ApiResponse<MessagingConfigurationInstance>>; + + + + + /** + * Streams MessagingConfigurationInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessagingConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: MessagingConfigurationInstance, done: (err?: Error) => void) => void): void; + each(params: MessagingConfigurationListInstanceEachOptions, callback?: (item: MessagingConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Streams MessagingConfigurationInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessagingConfigurationListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: MessagingConfigurationInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: MessagingConfigurationListInstanceEachOptions, callback?: (item: MessagingConfigurationInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of MessagingConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: MessagingConfigurationPage) => any): Promise<MessagingConfigurationPage>; + /** + * Retrieve a single target page of MessagingConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<MessagingConfigurationPage>) => any): Promise<ApiResponse<MessagingConfigurationPage>>; + /** + * Lists MessagingConfigurationInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessagingConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: MessagingConfigurationInstance[]) => any): Promise<MessagingConfigurationInstance[]>; + list(params: MessagingConfigurationListInstanceOptions, callback?: (error: Error | null, items: MessagingConfigurationInstance[]) => any): Promise<MessagingConfigurationInstance[]>; + /** + * Lists MessagingConfigurationInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessagingConfigurationListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<MessagingConfigurationInstance[]>) => any): Promise<ApiResponse<MessagingConfigurationInstance[]>>; + listWithHttpInfo(params: MessagingConfigurationListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<MessagingConfigurationInstance[]>) => any): Promise<ApiResponse<MessagingConfigurationInstance[]>>; + /** + * Retrieve a single page of MessagingConfigurationInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessagingConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: MessagingConfigurationPage) => any): Promise<MessagingConfigurationPage>; + page(params: MessagingConfigurationListInstancePageOptions, callback?: (error: Error | null, items: MessagingConfigurationPage) => any): Promise<MessagingConfigurationPage>; + /** + * Retrieve a single page of MessagingConfigurationInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { MessagingConfigurationListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<MessagingConfigurationPage>) => any): Promise<ApiResponse<MessagingConfigurationPage>>; + pageWithHttpInfo(params: MessagingConfigurationListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<MessagingConfigurationPage>) => any): Promise<ApiResponse<MessagingConfigurationPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function MessagingConfigurationListInstance(version: V2, serviceSid: string): MessagingConfigurationListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((country, ) => instance.get(country, )) as MessagingConfigurationListInstance; + + instance.get = function get(country, ): MessagingConfigurationContext { + return new MessagingConfigurationContextImpl(version, serviceSid, country); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/MessagingConfigurations`; + + instance.create = function create(params: MessagingConfigurationListInstanceCreateOptions, callback?: (error: Error | null, items: MessagingConfigurationInstance) => any): Promise<MessagingConfigurationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["country"] === null || params["country"] === undefined) { + throw new Error('Required parameter "params[\'country\']" missing.'); + } + + if (params["messagingServiceSid"] === null || params["messagingServiceSid"] === undefined) { + throw new Error('Required parameter "params[\'messagingServiceSid\']" missing.'); + } + + let data: any = {}; + + + + data["Country"] = params["country"]; + + data["MessagingServiceSid"] = params["messagingServiceSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new MessagingConfigurationInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: MessagingConfigurationListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<MessagingConfigurationInstance>) => any): Promise<ApiResponse<MessagingConfigurationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["country"] === null || params["country"] === undefined) { + throw new Error('Required parameter "params[\'country\']" missing.'); + } + + if (params["messagingServiceSid"] === null || params["messagingServiceSid"] === undefined) { + throw new Error('Required parameter "params[\'messagingServiceSid\']" missing.'); + } + + let data: any = {}; + + + + data["Country"] = params["country"]; + + data["MessagingServiceSid"] = params["messagingServiceSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<MessagingConfigurationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<MessagingConfigurationInstance> => ({ + ...response, + body: new MessagingConfigurationInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: MessagingConfigurationListInstancePageOptions | ((error: Error | null, items: MessagingConfigurationPage) => any), callback?: (error: Error | null, items: MessagingConfigurationPage) => any): Promise<MessagingConfigurationPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new MessagingConfigurationPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: MessagingConfigurationPage) => any): Promise<MessagingConfigurationPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new MessagingConfigurationPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: MessagingConfigurationListInstancePageOptions | ((error: Error | null, items: ApiResponse<MessagingConfigurationPage>) => any), callback?: (error: Error | null, items: ApiResponse<MessagingConfigurationPage>) => any): Promise<ApiResponse<MessagingConfigurationPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<MessagingConfigurationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagingConfigurationPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<MessagingConfigurationPage>) => any): Promise<ApiResponse<MessagingConfigurationPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<MessagingConfigurationPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new MessagingConfigurationPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class MessagingConfigurationPage extends Page<V2, MessagingConfigurationPayload, MessagingConfigurationResource, MessagingConfigurationInstance> { +/** +* Initialize the MessagingConfigurationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: MessagingConfigurationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of MessagingConfigurationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: MessagingConfigurationResource): MessagingConfigurationInstance { + + return new MessagingConfigurationInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/verify/v2/service/newChallenge.ts b/rest/verify/v2/service/newChallenge.ts new file mode 100644 index 000000000..6410f6087 --- /dev/null +++ b/rest/verify/v2/service/newChallenge.ts @@ -0,0 +1,421 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class CreatePasskeysChallengeRequest { + "identity"?: string; + "factorSid"?: string; + + constructor(payload) { + this.identity = payload["identity"]; + this.factorSid = payload["factor_sid"]; + } +} + + + +/** + * Options to pass to create a NewChallengeInstance + */ +export interface NewChallengeContextCreateOptions { + /** */ + "createPasskeysChallengeRequest": CreatePasskeysChallengeRequest; +} + +export interface NewChallengeContext { + + /** + * Create a NewChallengeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewChallengeInstance + */ + create(params: CreatePasskeysChallengeRequest, headers?: any, callback?: (error: Error | null, item?: NewChallengeInstance) => any): Promise<NewChallengeInstance>; + + /** + * Create a NewChallengeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewChallengeInstance with HTTP metadata + */ + createWithHttpInfo(params: CreatePasskeysChallengeRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<NewChallengeInstance>) => any): Promise<ApiResponse<NewChallengeInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface NewChallengeContextSolution { + "serviceSid": string; +} + +export class NewChallengeContextImpl implements NewChallengeContext { + protected _solution: NewChallengeContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + this._solution = { serviceSid, }; + this._uri = `/Services/${serviceSid}/Passkeys/Challenges`; + } + + create(params: CreatePasskeysChallengeRequest, headers?: any,callback?: (error: Error | null, item?: NewChallengeInstance) => any): Promise<NewChallengeInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NewChallengeInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params: CreatePasskeysChallengeRequest, headers?: any,callback?: (error: Error | null, item?: ApiResponse<NewChallengeInstance>) => any): Promise<ApiResponse<NewChallengeInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<NewChallengeResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<NewChallengeInstance> => ({ + ...response, + body: new NewChallengeInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface NewChallengePayload extends NewChallengeResource {} + +interface NewChallengeResource { + sid: string; + account_sid: string; + service_sid: string; + entity_sid: string; + identity: string; + factor_sid: string; + date_created: Date; + date_updated: Date; + date_responded: Date; + expiration_date: Date; + status: string; + responded_reason: string; + details: any; + hidden_details: any; + metadata: any; + factor_type: string; + url: string; + links: Record<string, string>; + options: Record<string, object>; +} + +export class NewChallengeInstance { + protected _solution: NewChallengeContextSolution; + protected _context?: NewChallengeContext; + + constructor(protected _version: V2, payload: NewChallengeResource, serviceSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.entitySid = (payload.entity_sid); + this.identity = (payload.identity); + this.factorSid = (payload.factor_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.dateResponded = deserialize.iso8601DateTime(payload.date_responded); + this.expirationDate = deserialize.iso8601DateTime(payload.expiration_date); + this.status = (payload.status); + this.respondedReason = (payload.responded_reason); + this.details = (payload.details); + this.hiddenDetails = (payload.hidden_details); + this.metadata = (payload.metadata); + this.factorType = (payload.factor_type); + this.url = (payload.url); + this.links = (payload.links); + this.options = (payload.options); + + this._solution = { serviceSid, }; + } + + /** + * A 34 character string that uniquely identifies this Challenge. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The unique SID identifier of the Entity. + */ + entitySid: string; + /** + * Customer unique identity for the Entity owner of the Challenge. + */ + identity: string; + /** + * The unique SID identifier of the Factor. + */ + factorSid: string; + /** + * The date that this Challenge was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date that this Challenge was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The date that this Challenge was responded, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateResponded: Date; + /** + * The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + expirationDate: Date; + /** + * The Status of this Challenge. One of `pending`, `expired`, `approved` or `denied`. + */ + status: string; + /** + * Reason for the Challenge to be in certain `status`. One of `none`, `not_needed` or `not_requested`. + */ + respondedReason: string; + /** + * Details provided to give context about the Challenge. + */ + details: any; + /** + * Details provided to give context about the Challenge. + */ + hiddenDetails: any; + /** + * Custom metadata associated with the challenge. + */ + metadata: any; + /** + * The Factor Type of this Challenge. Currently `push` and `totp` are supported. + */ + factorType: string; + /** + * The URL of this resource. + */ + url: string; + /** + * Contains a dictionary of URL links to nested resources of this Challenge. + */ + links: Record<string, string>; + /** + * An object that contains challenge options. Currently only used for `passkeys`. + */ + options: Record<string, object>; + + private get _proxy(): NewChallengeContext { + this._context = this._context || new NewChallengeContextImpl(this._version, this._solution.serviceSid); + return this._context; + } + + /** + * Create a NewChallengeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewChallengeInstance + */ + create(params: CreatePasskeysChallengeRequest, headers?: any, callback?: (error: Error | null, item?: NewChallengeInstance) => any): Promise<NewChallengeInstance>; + + create(params?: any, callback?: (error: Error | null, item?: NewChallengeInstance) => any): Promise<NewChallengeInstance> + { + return this._proxy.create(params, callback); + } + + /** + * Create a NewChallengeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewChallengeInstance with HTTP metadata + */ + createWithHttpInfo(params: CreatePasskeysChallengeRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<NewChallengeInstance>) => any): Promise<ApiResponse<NewChallengeInstance>>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<NewChallengeInstance>) => any): Promise<ApiResponse<NewChallengeInstance>> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + entitySid: this.entitySid, + identity: this.identity, + factorSid: this.factorSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + dateResponded: this.dateResponded, + expirationDate: this.expirationDate, + status: this.status, + respondedReason: this.respondedReason, + details: this.details, + hiddenDetails: this.hiddenDetails, + metadata: this.metadata, + factorType: this.factorType, + url: this.url, + links: this.links, + options: this.options, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface NewChallengeSolution { + serviceSid: string; +} + +export interface NewChallengeListInstance { + _version: V2; + _solution: NewChallengeSolution; + _uri: string; + + (): NewChallengeContext; + get(): NewChallengeContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NewChallengeListInstance(version: V2, serviceSid: string): NewChallengeListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = (() => instance.get()) as NewChallengeListInstance; + + instance.get = function get(): NewChallengeContext { + return new NewChallengeContextImpl(version, serviceSid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/verify/v2/service/newFactor.ts b/rest/verify/v2/service/newFactor.ts new file mode 100644 index 000000000..5f4998a7e --- /dev/null +++ b/rest/verify/v2/service/newFactor.ts @@ -0,0 +1,333 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class CreateNewPasskeysFactorRequest { + "friendlyName": string; + "identity": string; + "config"?: CreateNewPasskeysFactorRequestConfig; + + constructor(payload) { + this.friendlyName = payload["friendly_name"]; + this.identity = payload["identity"]; + this.config = payload["config"]; + } +} + + +export class CreateNewPasskeysFactorRequestConfig { + "relyingParty"?: CreateNewPasskeysFactorRequestConfigRelyingParty; + "authenticatorAttachment"?: string; + "discoverableCredentials"?: string; + "userVerification"?: string; + + constructor(payload) { + this.relyingParty = payload["relying_party"]; + this.authenticatorAttachment = payload["authenticator_attachment"]; + this.discoverableCredentials = payload["discoverable_credentials"]; + this.userVerification = payload["user_verification"]; + } +} + + +/** + * Contains the information of the party requesting the user for authentication + */ +export class CreateNewPasskeysFactorRequestConfigRelyingParty { + "id"?: string; + "name"?: string; + "origins"?: Array<string>; + + constructor(payload) { + this.id = payload["id"]; + this.name = payload["name"]; + this.origins = payload["origins"]; + } +} + + + +/** + * Options to pass to create a NewFactorInstance + */ +export interface NewFactorListInstanceCreateOptions { + /** */ + "createNewPasskeysFactorRequest": CreateNewPasskeysFactorRequest; +} + + +export interface NewFactorSolution { + serviceSid: string; +} + +export interface NewFactorListInstance { + _version: V2; + _solution: NewFactorSolution; + _uri: string; + + + + /** + * Create a NewFactorInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewFactorInstance + */ + create(params: CreateNewPasskeysFactorRequest, headers?: any, callback?: (error: Error | null, item?: NewFactorInstance) => any): Promise<NewFactorInstance>; + + /** + * Create a NewFactorInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewFactorInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateNewPasskeysFactorRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<NewFactorInstance>) => any): Promise<ApiResponse<NewFactorInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NewFactorListInstance(version: V2, serviceSid: string): NewFactorListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = {} as NewFactorListInstance; + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Passkeys/Factors`; + + instance.create = function create(params: CreateNewPasskeysFactorRequest, headers?: any, callback?: (error: Error | null, items: NewFactorInstance) => any): Promise<NewFactorInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NewFactorInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateNewPasskeysFactorRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<NewFactorInstance>) => any): Promise<ApiResponse<NewFactorInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<NewFactorResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<NewFactorInstance> => ({ + ...response, + body: new NewFactorInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface NewFactorPayload extends NewFactorResource {} + +interface NewFactorResource { + sid: string; + account_sid: string; + service_sid: string; + entity_sid: string; + identity: string; + binding: any; + options: any; + date_created: Date; + date_updated: Date; + friendly_name: string; + status: string; + factor_type: string; + config: any; + metadata: any; + url: string; +} + +export class NewFactorInstance { + + constructor(protected _version: V2, payload: NewFactorResource, serviceSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.entitySid = (payload.entity_sid); + this.identity = (payload.identity); + this.binding = (payload.binding); + this.options = (payload.options); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.status = (payload.status); + this.factorType = (payload.factor_type); + this.config = (payload.config); + this.metadata = (payload.metadata); + this.url = (payload.url); + + } + + /** + * A 34 character string that uniquely identifies this Factor. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The unique SID identifier of the Entity. + */ + entitySid: string; + /** + * Customer unique identity for the Entity owner of the Factor. + */ + identity: string; + /** + * Contains the `factor_type` specific secret and metadata. The Binding property is ONLY returned upon Factor creation. + */ + binding: any; + options: any; + /** + * The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. + */ + friendlyName: string; + /** + * The Status of this Factor. One of `unverified` or `verified`. + */ + status: string; + /** + * The Type of this Factor. Currently `push` and `totp` are supported. + */ + factorType: string; + /** + * An object that contains configurations specific to a `factor_type`. + */ + config: any; + /** + * Custom metadata associated with the factor. + */ + metadata: any; + /** + * The URL of this resource. + */ + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + entitySid: this.entitySid, + identity: this.identity, + binding: this.binding, + options: this.options, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + status: this.status, + factorType: this.factorType, + config: this.config, + metadata: this.metadata, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/verify/v2/service/newVerifyFactor.ts b/rest/verify/v2/service/newVerifyFactor.ts new file mode 100644 index 000000000..04106b319 --- /dev/null +++ b/rest/verify/v2/service/newVerifyFactor.ts @@ -0,0 +1,332 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class VerifyPasskeysFactorRequest { + /** + * A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + */ + "id"?: string; + /** + * The globally unique identifier for this `PublicKeyCredential`. + */ + "rawId"?: string; + /** + * A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + */ + "authenticatorAttachment"?: string; + /** + * The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + */ + "type"?: string; + "response": VerifyPasskeysFactorRequestResponse; + + constructor(payload) { + this.id = payload["id"]; + this.rawId = payload["rawId"]; + this.authenticatorAttachment = payload["authenticatorAttachment"]; + this.type = payload["type"]; + this.response = payload["response"]; + } +} + + +/** + * The result of a WebAuthn credential registration via `navigator.credentials.create()`, as specified in [AuthenticatorAttestationResponse](https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse). + */ +export class VerifyPasskeysFactorRequestResponse { + /** + * The authenticator data and an attestation statement for a new key pair generated by the authenticator. + */ + "attestationObject"?: string; + /** + * This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + */ + "clientDataJSON"?: string; + /** + * An array of strings providing hints as to the methods the client could use to communicate with the relevant authenticator of the public key credential to retrieve. + */ + "transports"?: Array<string>; + + constructor(payload) { + this.attestationObject = payload["attestationObject"]; + this.clientDataJSON = payload["clientDataJSON"]; + this.transports = payload["transports"]; + } +} + + + +/** + * Options to pass to update a NewVerifyFactorInstance + */ +export interface NewVerifyFactorListInstanceUpdateOptions { + /** */ + "verifyPasskeysFactorRequest": VerifyPasskeysFactorRequest; +} + + +export interface NewVerifyFactorSolution { + serviceSid: string; +} + +export interface NewVerifyFactorListInstance { + _version: V2; + _solution: NewVerifyFactorSolution; + _uri: string; + + + + /** + * Update a NewVerifyFactorInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewVerifyFactorInstance + */ + update(params: VerifyPasskeysFactorRequest, headers?: any, callback?: (error: Error | null, item?: NewVerifyFactorInstance) => any): Promise<NewVerifyFactorInstance>; + + /** + * Update a NewVerifyFactorInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed NewVerifyFactorInstance with HTTP metadata + */ + updateWithHttpInfo(params: VerifyPasskeysFactorRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<NewVerifyFactorInstance>) => any): Promise<ApiResponse<NewVerifyFactorInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function NewVerifyFactorListInstance(version: V2, serviceSid: string): NewVerifyFactorListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = {} as NewVerifyFactorListInstance; + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Passkeys/VerifyFactor`; + + instance.update = function update(params: VerifyPasskeysFactorRequest, headers?: any, callback?: (error: Error | null, items: NewVerifyFactorInstance) => any): Promise<NewVerifyFactorInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new NewVerifyFactorInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.updateWithHttpInfo = function updateWithHttpInfo(params: VerifyPasskeysFactorRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<NewVerifyFactorInstance>) => any): Promise<ApiResponse<NewVerifyFactorInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<NewVerifyFactorResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<NewVerifyFactorInstance> => ({ + ...response, + body: new NewVerifyFactorInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface NewVerifyFactorPayload extends NewVerifyFactorResource {} + +interface NewVerifyFactorResource { + sid: string; + account_sid: string; + service_sid: string; + entity_sid: string; + identity: string; + date_created: Date; + date_updated: Date; + friendly_name: string; + status: string; + factor_type: string; + config: any; + metadata: any; + url: string; +} + +export class NewVerifyFactorInstance { + + constructor(protected _version: V2, payload: NewVerifyFactorResource, serviceSid: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.entitySid = (payload.entity_sid); + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.friendlyName = (payload.friendly_name); + this.status = (payload.status); + this.factorType = (payload.factor_type); + this.config = (payload.config); + this.metadata = (payload.metadata); + this.url = (payload.url); + + } + + /** + * A 34 character string that uniquely identifies this Factor. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The unique SID identifier of the Entity. + */ + entitySid: string; + /** + * Customer unique identity for the Entity owner of the Factor. + */ + identity: string; + /** + * The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * A human readable description of this resource, up to 64 characters. + */ + friendlyName: string; + /** + * The Status of this Factor. One of `unverified` or `verified`. + */ + status: string; + /** + * The Type of this Factor. Currently `push` and `totp` are supported. + */ + factorType: string; + /** + * An object that contains configurations specific to a `factor_type`. + */ + config: any; + /** + * Custom metadata associated with the factor. + */ + metadata: any; + /** + * The URL of this resource. + */ + url: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + entitySid: this.entitySid, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + friendlyName: this.friendlyName, + status: this.status, + factorType: this.factorType, + config: this.config, + metadata: this.metadata, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/verify/v2/service/rateLimit.ts b/rest/verify/v2/service/rateLimit.ts new file mode 100644 index 000000000..19accf57a --- /dev/null +++ b/rest/verify/v2/service/rateLimit.ts @@ -0,0 +1,942 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { BucketListInstance } from "./rateLimit/bucket"; + + + + + +/** + * Options to pass to update a RateLimitInstance + */ +export interface RateLimitContextUpdateOptions { + /** Description of this Rate Limit */ + "description"?: string; +} + +/** + * Options to pass to create a RateLimitInstance + */ +export interface RateLimitListInstanceCreateOptions { + /** Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** */ + "uniqueName": string; + /** Description of this Rate Limit */ + "description"?: string; +} + +/** + * Options to pass to each + */ +export interface RateLimitListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RateLimitInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RateLimitListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RateLimitListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RateLimitContext { + buckets: BucketListInstance; + + /** + * Remove a RateLimitInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a RateLimitInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a RateLimitInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance + */ + fetch(callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance> + + /** + * Fetch a RateLimitInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>> + + /** + * Update a RateLimitInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance + */ + update(callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance>; + /** + * Update a RateLimitInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance + */ + update(params: RateLimitContextUpdateOptions, callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance>; + + /** + * Update a RateLimitInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>>; + /** + * Update a RateLimitInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance with HTTP metadata + */ + updateWithHttpInfo(params: RateLimitContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RateLimitContextSolution { + "serviceSid": string; + "sid": string; +} + +export class RateLimitContextImpl implements RateLimitContext { + protected _solution: RateLimitContextSolution; + protected _uri: string; + + protected _buckets?: BucketListInstance; + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/RateLimits/${sid}`; + } + + get buckets(): BucketListInstance { + this._buckets = this._buckets || BucketListInstance(this._version, this._solution.serviceSid, this._solution.sid); + return this._buckets; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RateLimitInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RateLimitResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<RateLimitInstance> => ({ + ...response, + body: new RateLimitInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: RateLimitContextUpdateOptions | ((error: Error | null, item?: RateLimitInstance) => any),callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RateLimitInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: RateLimitContextUpdateOptions | ((error: Error | null, item?: ApiResponse<RateLimitInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<RateLimitResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RateLimitInstance> => ({ + ...response, + body: new RateLimitInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RateLimitPayload extends TwilioResponsePayload { + rate_limits: RateLimitResource[]; +} + +interface RateLimitResource { + sid: string; + service_sid: string; + account_sid: string; + unique_name: string; + description: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class RateLimitInstance { + protected _solution: RateLimitContextSolution; + protected _context?: RateLimitContext; + + constructor(protected _version: V2, payload: RateLimitResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.serviceSid = (payload.service_sid); + this.accountSid = (payload.account_sid); + this.uniqueName = (payload.unique_name); + this.description = (payload.description); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this Rate Limit. + */ + sid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Rate Limit resource. + */ + accountSid: string; + /** + * Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + */ + uniqueName: string; + /** + * Description of this Rate Limit + */ + description: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): RateLimitContext { + this._context = this._context || new RateLimitContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RateLimitInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RateLimitInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RateLimitInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance + */ + fetch(callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RateLimitInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RateLimitInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance + */ + update(callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance>; + /** + * Update a RateLimitInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance + */ + update(params: RateLimitContextUpdateOptions, callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance>; + + update(params?: any, callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a RateLimitInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>>; + /** + * Update a RateLimitInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance with HTTP metadata + */ + updateWithHttpInfo(params: RateLimitContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the buckets. + */ + buckets(): BucketListInstance { + return this._proxy.buckets; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + serviceSid: this.serviceSid, + accountSid: this.accountSid, + uniqueName: this.uniqueName, + description: this.description, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RateLimitSolution { + serviceSid: string; +} + +export interface RateLimitListInstance { + _version: V2; + _solution: RateLimitSolution; + _uri: string; + + (sid: string, ): RateLimitContext; + get(sid: string, ): RateLimitContext; + + + + + + + + + /** + * Create a RateLimitInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance + */ + create(params: RateLimitListInstanceCreateOptions, callback?: (error: Error | null, item?: RateLimitInstance) => any): Promise<RateLimitInstance>; + + /** + * Create a RateLimitInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RateLimitInstance with HTTP metadata + */ + createWithHttpInfo(params: RateLimitListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>>; + + + + + /** + * Streams RateLimitInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RateLimitListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RateLimitInstance, done: (err?: Error) => void) => void): void; + each(params: RateLimitListInstanceEachOptions, callback?: (item: RateLimitInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RateLimitInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RateLimitListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RateLimitInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RateLimitListInstanceEachOptions, callback?: (item: RateLimitInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RateLimitInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RateLimitPage) => any): Promise<RateLimitPage>; + /** + * Retrieve a single target page of RateLimitInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RateLimitPage>) => any): Promise<ApiResponse<RateLimitPage>>; + /** + * Lists RateLimitInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RateLimitListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RateLimitInstance[]) => any): Promise<RateLimitInstance[]>; + list(params: RateLimitListInstanceOptions, callback?: (error: Error | null, items: RateLimitInstance[]) => any): Promise<RateLimitInstance[]>; + /** + * Lists RateLimitInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RateLimitListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RateLimitInstance[]>) => any): Promise<ApiResponse<RateLimitInstance[]>>; + listWithHttpInfo(params: RateLimitListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RateLimitInstance[]>) => any): Promise<ApiResponse<RateLimitInstance[]>>; + /** + * Retrieve a single page of RateLimitInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RateLimitListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RateLimitPage) => any): Promise<RateLimitPage>; + page(params: RateLimitListInstancePageOptions, callback?: (error: Error | null, items: RateLimitPage) => any): Promise<RateLimitPage>; + /** + * Retrieve a single page of RateLimitInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RateLimitListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RateLimitPage>) => any): Promise<ApiResponse<RateLimitPage>>; + pageWithHttpInfo(params: RateLimitListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RateLimitPage>) => any): Promise<ApiResponse<RateLimitPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RateLimitListInstance(version: V2, serviceSid: string): RateLimitListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RateLimitListInstance; + + instance.get = function get(sid, ): RateLimitContext { + return new RateLimitContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/RateLimits`; + + instance.create = function create(params: RateLimitListInstanceCreateOptions, callback?: (error: Error | null, items: RateLimitInstance) => any): Promise<RateLimitInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RateLimitInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: RateLimitListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<RateLimitInstance>) => any): Promise<ApiResponse<RateLimitInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["uniqueName"] === null || params["uniqueName"] === undefined) { + throw new Error('Required parameter "params[\'uniqueName\']" missing.'); + } + + let data: any = {}; + + + + data["UniqueName"] = params["uniqueName"]; + if (params["description"] !== undefined) + data["Description"] = params["description"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<RateLimitResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RateLimitInstance> => ({ + ...response, + body: new RateLimitInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RateLimitListInstancePageOptions | ((error: Error | null, items: RateLimitPage) => any), callback?: (error: Error | null, items: RateLimitPage) => any): Promise<RateLimitPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RateLimitPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RateLimitPage) => any): Promise<RateLimitPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RateLimitPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RateLimitListInstancePageOptions | ((error: Error | null, items: ApiResponse<RateLimitPage>) => any), callback?: (error: Error | null, items: ApiResponse<RateLimitPage>) => any): Promise<ApiResponse<RateLimitPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RateLimitPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RateLimitPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RateLimitPage>) => any): Promise<ApiResponse<RateLimitPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RateLimitPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RateLimitPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RateLimitPage extends Page<V2, RateLimitPayload, RateLimitResource, RateLimitInstance> { +/** +* Initialize the RateLimitPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: RateLimitSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RateLimitInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RateLimitResource): RateLimitInstance { + + return new RateLimitInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/verify/v2/service/rateLimit/bucket.ts b/rest/verify/v2/service/rateLimit/bucket.ts new file mode 100644 index 000000000..4104bd6e8 --- /dev/null +++ b/rest/verify/v2/service/rateLimit/bucket.ts @@ -0,0 +1,952 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V2 from "../../../V2"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a BucketInstance + */ +export interface BucketContextUpdateOptions { + /** Maximum number of requests permitted in during the interval. */ + "max"?: number; + /** Number of seconds that the rate limit will be enforced over. */ + "interval"?: number; +} + +/** + * Options to pass to create a BucketInstance + */ +export interface BucketListInstanceCreateOptions { + /** Maximum number of requests permitted in during the interval. */ + "max": number; + /** Number of seconds that the rate limit will be enforced over. */ + "interval": number; +} + +/** + * Options to pass to each + */ +export interface BucketListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: BucketInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface BucketListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface BucketListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface BucketContext { + + /** + * Remove a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + fetch(callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance> + + /** + * Fetch a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> + + /** + * Update a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + update(callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance>; + /** + * Update a BucketInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + update(params: BucketContextUpdateOptions, callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance>; + + /** + * Update a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>>; + /** + * Update a BucketInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + updateWithHttpInfo(params: BucketContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface BucketContextSolution { + "serviceSid": string; + "rateLimitSid": string; + "sid": string; +} + +export class BucketContextImpl implements BucketContext { + protected _solution: BucketContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, rateLimitSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(rateLimitSid)) { + throw new Error('Parameter \'rateLimitSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, rateLimitSid, sid, }; + this._uri = `/Services/${serviceSid}/RateLimits/${rateLimitSid}/Buckets/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new BucketInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.rateLimitSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<BucketResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<BucketInstance> => ({ + ...response, + body: new BucketInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.rateLimitSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: BucketContextUpdateOptions | ((error: Error | null, item?: BucketInstance) => any),callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["max"] !== undefined) + data["Max"] = params["max"]; + if (params["interval"] !== undefined) + data["Interval"] = params["interval"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BucketInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.rateLimitSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: BucketContextUpdateOptions | ((error: Error | null, item?: ApiResponse<BucketInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["max"] !== undefined) + data["Max"] = params["max"]; + if (params["interval"] !== undefined) + data["Interval"] = params["interval"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<BucketResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BucketInstance> => ({ + ...response, + body: new BucketInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.rateLimitSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface BucketPayload extends TwilioResponsePayload { + buckets: BucketResource[]; +} + +interface BucketResource { + sid: string; + rate_limit_sid: string; + service_sid: string; + account_sid: string; + max: number; + interval: number; + date_created: Date; + date_updated: Date; + url: string; +} + +export class BucketInstance { + protected _solution: BucketContextSolution; + protected _context?: BucketContext; + + constructor(protected _version: V2, payload: BucketResource, serviceSid: string, rateLimitSid: string, sid?: string) { + + this.sid = (payload.sid); + this.rateLimitSid = (payload.rate_limit_sid); + this.serviceSid = (payload.service_sid); + this.accountSid = (payload.account_sid); + this.max = deserialize.integer(payload.max); + this.interval = deserialize.integer(payload.interval); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, rateLimitSid, sid: sid, }; + } + + /** + * A 34 character string that uniquely identifies this Bucket. + */ + sid: string; + /** + * The Twilio-provided string that uniquely identifies the Rate Limit resource. + */ + rateLimitSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Rate Limit resource. + */ + accountSid: string; + /** + * Maximum number of requests permitted in during the interval. + */ + max: number; + /** + * Number of seconds that the rate limit will be enforced over. + */ + interval: number; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The URL of this resource. + */ + url: string; + + private get _proxy(): BucketContext { + this._context = this._context || new BucketContextImpl(this._version, this._solution.serviceSid, this._solution.rateLimitSid, this._solution.sid); + return this._context; + } + + /** + * Remove a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + fetch(callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a BucketInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + update(callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance>; + /** + * Update a BucketInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + update(params: BucketContextUpdateOptions, callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance>; + + update(params?: any, callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a BucketInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>>; + /** + * Update a BucketInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + updateWithHttpInfo(params: BucketContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + rateLimitSid: this.rateLimitSid, + serviceSid: this.serviceSid, + accountSid: this.accountSid, + max: this.max, + interval: this.interval, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface BucketSolution { + serviceSid: string; + rateLimitSid: string; +} + +export interface BucketListInstance { + _version: V2; + _solution: BucketSolution; + _uri: string; + + (sid: string, ): BucketContext; + get(sid: string, ): BucketContext; + + + + + + + + + /** + * Create a BucketInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance + */ + create(params: BucketListInstanceCreateOptions, callback?: (error: Error | null, item?: BucketInstance) => any): Promise<BucketInstance>; + + /** + * Create a BucketInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BucketInstance with HTTP metadata + */ + createWithHttpInfo(params: BucketListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>>; + + + + + /** + * Streams BucketInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BucketListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: BucketInstance, done: (err?: Error) => void) => void): void; + each(params: BucketListInstanceEachOptions, callback?: (item: BucketInstance, done: (err?: Error) => void) => void): void; + /** + * Streams BucketInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BucketListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: BucketInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: BucketListInstanceEachOptions, callback?: (item: BucketInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of BucketInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: BucketPage) => any): Promise<BucketPage>; + /** + * Retrieve a single target page of BucketInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<BucketPage>) => any): Promise<ApiResponse<BucketPage>>; + /** + * Lists BucketInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BucketListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: BucketInstance[]) => any): Promise<BucketInstance[]>; + list(params: BucketListInstanceOptions, callback?: (error: Error | null, items: BucketInstance[]) => any): Promise<BucketInstance[]>; + /** + * Lists BucketInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BucketListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BucketInstance[]>) => any): Promise<ApiResponse<BucketInstance[]>>; + listWithHttpInfo(params: BucketListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<BucketInstance[]>) => any): Promise<ApiResponse<BucketInstance[]>>; + /** + * Retrieve a single page of BucketInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BucketListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: BucketPage) => any): Promise<BucketPage>; + page(params: BucketListInstancePageOptions, callback?: (error: Error | null, items: BucketPage) => any): Promise<BucketPage>; + /** + * Retrieve a single page of BucketInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { BucketListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<BucketPage>) => any): Promise<ApiResponse<BucketPage>>; + pageWithHttpInfo(params: BucketListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<BucketPage>) => any): Promise<ApiResponse<BucketPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BucketListInstance(version: V2, serviceSid: string, rateLimitSid: string): BucketListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(rateLimitSid)) { + throw new Error('Parameter \'rateLimitSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as BucketListInstance; + + instance.get = function get(sid, ): BucketContext { + return new BucketContextImpl(version, serviceSid, rateLimitSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, rateLimitSid, }; + instance._uri = `/Services/${serviceSid}/RateLimits/${rateLimitSid}/Buckets`; + + instance.create = function create(params: BucketListInstanceCreateOptions, callback?: (error: Error | null, items: BucketInstance) => any): Promise<BucketInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["max"] === null || params["max"] === undefined) { + throw new Error('Required parameter "params[\'max\']" missing.'); + } + + if (params["interval"] === null || params["interval"] === undefined) { + throw new Error('Required parameter "params[\'interval\']" missing.'); + } + + let data: any = {}; + + + + data["Max"] = params["max"]; + + data["Interval"] = params["interval"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BucketInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.rateLimitSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: BucketListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<BucketInstance>) => any): Promise<ApiResponse<BucketInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["max"] === null || params["max"] === undefined) { + throw new Error('Required parameter "params[\'max\']" missing.'); + } + + if (params["interval"] === null || params["interval"] === undefined) { + throw new Error('Required parameter "params[\'interval\']" missing.'); + } + + let data: any = {}; + + + + data["Max"] = params["max"]; + + data["Interval"] = params["interval"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BucketResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BucketInstance> => ({ + ...response, + body: new BucketInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.rateLimitSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: BucketListInstancePageOptions | ((error: Error | null, items: BucketPage) => any), callback?: (error: Error | null, items: BucketPage) => any): Promise<BucketPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new BucketPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: BucketPage) => any): Promise<BucketPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new BucketPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: BucketListInstancePageOptions | ((error: Error | null, items: ApiResponse<BucketPage>) => any), callback?: (error: Error | null, items: ApiResponse<BucketPage>) => any): Promise<ApiResponse<BucketPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<BucketPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BucketPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<BucketPage>) => any): Promise<ApiResponse<BucketPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<BucketPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new BucketPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class BucketPage extends Page<V2, BucketPayload, BucketResource, BucketInstance> { +/** +* Initialize the BucketPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: BucketSolution) { + super(version, response, solution); + } + + /** + * Build an instance of BucketInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: BucketResource): BucketInstance { + + return new BucketInstance( + this._version, + payload, + this._solution.serviceSid, + this._solution.rateLimitSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/verify/v2/service/verification.ts b/rest/verify/v2/service/verification.ts new file mode 100644 index 000000000..d52130e67 --- /dev/null +++ b/rest/verify/v2/service/verification.ts @@ -0,0 +1,694 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The verification method used. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna`, or `rcs`. + */ +export type VerificationChannel = 'sms'|'call'|'email'|'whatsapp'|'sna'; + +/** + * Risk_check overrides Fraud Prevention measures like Fraud Guard, Geo Permissions etc per verification attempt basis, allowing Verify to block traffic considered fraudulent if enabled or bypass active protections if disabled. Can be: `enable`(default) or `disable`. For SMS channel only. + */ +export type VerificationRiskCheck = 'enable'|'disable'; + +/** + * The status of the verification. Can be: `pending`, `approved`, `canceled`, `max_attempts_reached`, `deleted`, `failed` or `expired`. + */ +export type VerificationStatus = 'canceled'|'approved'; + + + +/** + * Options to pass to update a VerificationInstance + */ +export interface VerificationContextUpdateOptions { + /** */ + "status": VerificationStatus; +} + +/** + * Options to pass to create a VerificationInstance + */ +export interface VerificationListInstanceCreateOptions { + /** The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). */ + "to": string; + /** The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. */ + "channel": string; + /** A custom user defined friendly name that overwrites the existing one in the verification message */ + "customFriendlyName"?: string; + /** The text of a custom message to use for the verification [DEPRECATED]. */ + "customMessage"?: string; + /** The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). */ + "sendDigits"?: string; + /** Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). */ + "locale"?: string; + /** A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. */ + "customCode"?: string; + /** The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. */ + "amount"?: string; + /** The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. */ + "payee"?: string; + /** The custom key-value pairs of Programmable Rate Limits. Keys correspond to `unique_name` fields defined when [creating your Rate Limit](https://www.twilio.com/docs/verify/api/service-rate-limits). Associated value pairs represent values in the request that you are rate limiting on. You may include multiple Rate Limit values in each request. */ + "rateLimits"?: any; + /** [`email`](https://www.twilio.com/docs/verify/email) channel configuration in json format. The fields \\\'from\\\' and \\\'from_name\\\' are optional but if included the \\\'from\\\' field must have a valid email address. */ + "channelConfiguration"?: any; + /** Your [App Hash](https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string) to be appended at the end of your verification SMS body. Applies only to SMS. Example SMS body: `<#> Your AppName verification code is: 1234 He42w354ol9`. */ + "appHash"?: string; + /** The message [template](https://www.twilio.com/docs/verify/api/templates). If provided, will override the default template for the Service. SMS and Voice channels only. */ + "templateSid"?: string; + /** A stringified JSON object in which the keys are the template\\\'s special variables and the values are the variables substitutions. */ + "templateCustomSubstitutions"?: string; + /** Strongly encouraged if using the auto channel. The IP address of the client\\\'s device. If provided, it has to be a valid IPv4 or IPv6 address. */ + "deviceIp"?: string; + /** An optional Boolean value to indicate the requirement of sna client token in the SNA URL invocation response for added security. This token must match in the Verification Check request to confirm phone number verification. */ + "enableSnaClientToken"?: boolean; + /** */ + "riskCheck"?: VerificationRiskCheck; + /** A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The tags will also be included as part of the verification and message status event type payloads. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. **This value should not contain PII.** */ + "tags"?: string; +} + +export interface VerificationContext { + + /** + * Fetch a VerificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationInstance + */ + fetch(callback?: (error: Error | null, item?: VerificationInstance) => any): Promise<VerificationInstance> + + /** + * Fetch a VerificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VerificationInstance>) => any): Promise<ApiResponse<VerificationInstance>> + + /** + * Update a VerificationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationInstance + */ + update(params: VerificationContextUpdateOptions, callback?: (error: Error | null, item?: VerificationInstance) => any): Promise<VerificationInstance>; + + /** + * Update a VerificationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationInstance with HTTP metadata + */ + updateWithHttpInfo(params: VerificationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<VerificationInstance>) => any): Promise<ApiResponse<VerificationInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface VerificationContextSolution { + "serviceSid": string; + "sid": string; +} + +export class VerificationContextImpl implements VerificationContext { + protected _solution: VerificationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Verifications/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: VerificationInstance) => any): Promise<VerificationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new VerificationInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VerificationInstance>) => any): Promise<ApiResponse<VerificationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<VerificationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<VerificationInstance> => ({ + ...response, + body: new VerificationInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: VerificationContextUpdateOptions,callback?: (error: Error | null, item?: VerificationInstance) => any): Promise<VerificationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new VerificationInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: VerificationContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<VerificationInstance>) => any): Promise<ApiResponse<VerificationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<VerificationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<VerificationInstance> => ({ + ...response, + body: new VerificationInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface VerificationPayload extends VerificationResource {} + +interface VerificationResource { + sid: string; + service_sid: string; + account_sid: string; + to: string; + channel: VerificationChannel; + status: string; + valid: boolean; + lookup: any; + amount: string; + payee: string; + send_code_attempts: Array<any>; + date_created: Date; + date_updated: Date; + sna: any; + url: string; +} + +export class VerificationInstance { + protected _solution: VerificationContextSolution; + protected _context?: VerificationContext; + + constructor(protected _version: V2, payload: VerificationResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.serviceSid = (payload.service_sid); + this.accountSid = (payload.account_sid); + this.to = (payload.to); + this.channel = payload.channel; + this.status = (payload.status); + this.valid = (payload.valid); + this.lookup = (payload.lookup); + this.amount = (payload.amount); + this.payee = (payload.payee); + this.sendCodeAttempts = (payload.send_code_attempts); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.sna = (payload.sna); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Verification resource. + */ + sid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Verification resource. + */ + accountSid: string; + /** + * The phone number or [email](https://www.twilio.com/docs/verify/email) being verified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + */ + to: string; + channel: VerificationChannel; + /** + * The status of the verification. Can be: `pending`, `approved`, `canceled`, `max_attempts_reached`, `deleted`, `failed` or `expired`. + */ + status: string; + /** + * Use \"status\" instead. Legacy property indicating whether the verification was successful. + */ + valid: boolean; + /** + * Information about the phone number being verified. + */ + lookup: any; + /** + * The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + */ + amount: string; + /** + * The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + */ + payee: string; + /** + * An array of verification attempt objects containing the channel attempted and the channel-specific transaction SID. + */ + sendCodeAttempts: Array<any>; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The set of fields used for a silent network auth (`sna`) verification. Contains a single field with the URL to be invoked to verify the phone number. + */ + sna: any; + /** + * The absolute URL of the Verification resource. + */ + url: string; + + private get _proxy(): VerificationContext { + this._context = this._context || new VerificationContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a VerificationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationInstance + */ + fetch(callback?: (error: Error | null, item?: VerificationInstance) => any): Promise<VerificationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a VerificationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VerificationInstance>) => any): Promise<ApiResponse<VerificationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a VerificationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationInstance + */ + update(params: VerificationContextUpdateOptions, callback?: (error: Error | null, item?: VerificationInstance) => any): Promise<VerificationInstance>; + + update(params?: any, callback?: (error: Error | null, item?: VerificationInstance) => any): Promise<VerificationInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a VerificationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationInstance with HTTP metadata + */ + updateWithHttpInfo(params: VerificationContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<VerificationInstance>) => any): Promise<ApiResponse<VerificationInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<VerificationInstance>) => any): Promise<ApiResponse<VerificationInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + serviceSid: this.serviceSid, + accountSid: this.accountSid, + to: this.to, + channel: this.channel, + status: this.status, + valid: this.valid, + lookup: this.lookup, + amount: this.amount, + payee: this.payee, + sendCodeAttempts: this.sendCodeAttempts, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + sna: this.sna, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface VerificationSolution { + serviceSid: string; +} + +export interface VerificationListInstance { + _version: V2; + _solution: VerificationSolution; + _uri: string; + + (sid: string, ): VerificationContext; + get(sid: string, ): VerificationContext; + + + + + + + /** + * Create a VerificationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationInstance + */ + create(params: VerificationListInstanceCreateOptions, callback?: (error: Error | null, item?: VerificationInstance) => any): Promise<VerificationInstance>; + + /** + * Create a VerificationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationInstance with HTTP metadata + */ + createWithHttpInfo(params: VerificationListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<VerificationInstance>) => any): Promise<ApiResponse<VerificationInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function VerificationListInstance(version: V2, serviceSid: string): VerificationListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as VerificationListInstance; + + instance.get = function get(sid, ): VerificationContext { + return new VerificationContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Verifications`; + + instance.create = function create(params: VerificationListInstanceCreateOptions, callback?: (error: Error | null, items: VerificationInstance) => any): Promise<VerificationInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + if (params["channel"] === null || params["channel"] === undefined) { + throw new Error('Required parameter "params[\'channel\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + + data["Channel"] = params["channel"]; + if (params["customFriendlyName"] !== undefined) + data["CustomFriendlyName"] = params["customFriendlyName"]; + if (params["customMessage"] !== undefined) + data["CustomMessage"] = params["customMessage"]; + if (params["sendDigits"] !== undefined) + data["SendDigits"] = params["sendDigits"]; + if (params["locale"] !== undefined) + data["Locale"] = params["locale"]; + if (params["customCode"] !== undefined) + data["CustomCode"] = params["customCode"]; + if (params["amount"] !== undefined) + data["Amount"] = params["amount"]; + if (params["payee"] !== undefined) + data["Payee"] = params["payee"]; + if (params["rateLimits"] !== undefined) + data["RateLimits"] = serialize.object(params["rateLimits"]); + if (params["channelConfiguration"] !== undefined) + data["ChannelConfiguration"] = serialize.object(params["channelConfiguration"]); + if (params["appHash"] !== undefined) + data["AppHash"] = params["appHash"]; + if (params["templateSid"] !== undefined) + data["TemplateSid"] = params["templateSid"]; + if (params["templateCustomSubstitutions"] !== undefined) + data["TemplateCustomSubstitutions"] = params["templateCustomSubstitutions"]; + if (params["deviceIp"] !== undefined) + data["DeviceIp"] = params["deviceIp"]; + if (params["enableSnaClientToken"] !== undefined) + data["EnableSnaClientToken"] = serialize.bool(params["enableSnaClientToken"]); + if (params["riskCheck"] !== undefined) + data["RiskCheck"] = params["riskCheck"]; + if (params["tags"] !== undefined) + data["Tags"] = params["tags"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new VerificationInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: VerificationListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<VerificationInstance>) => any): Promise<ApiResponse<VerificationInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["to"] === null || params["to"] === undefined) { + throw new Error('Required parameter "params[\'to\']" missing.'); + } + + if (params["channel"] === null || params["channel"] === undefined) { + throw new Error('Required parameter "params[\'channel\']" missing.'); + } + + let data: any = {}; + + + + data["To"] = params["to"]; + + data["Channel"] = params["channel"]; + if (params["customFriendlyName"] !== undefined) + data["CustomFriendlyName"] = params["customFriendlyName"]; + if (params["customMessage"] !== undefined) + data["CustomMessage"] = params["customMessage"]; + if (params["sendDigits"] !== undefined) + data["SendDigits"] = params["sendDigits"]; + if (params["locale"] !== undefined) + data["Locale"] = params["locale"]; + if (params["customCode"] !== undefined) + data["CustomCode"] = params["customCode"]; + if (params["amount"] !== undefined) + data["Amount"] = params["amount"]; + if (params["payee"] !== undefined) + data["Payee"] = params["payee"]; + if (params["rateLimits"] !== undefined) + data["RateLimits"] = serialize.object(params["rateLimits"]); + if (params["channelConfiguration"] !== undefined) + data["ChannelConfiguration"] = serialize.object(params["channelConfiguration"]); + if (params["appHash"] !== undefined) + data["AppHash"] = params["appHash"]; + if (params["templateSid"] !== undefined) + data["TemplateSid"] = params["templateSid"]; + if (params["templateCustomSubstitutions"] !== undefined) + data["TemplateCustomSubstitutions"] = params["templateCustomSubstitutions"]; + if (params["deviceIp"] !== undefined) + data["DeviceIp"] = params["deviceIp"]; + if (params["enableSnaClientToken"] !== undefined) + data["EnableSnaClientToken"] = serialize.bool(params["enableSnaClientToken"]); + if (params["riskCheck"] !== undefined) + data["RiskCheck"] = params["riskCheck"]; + if (params["tags"] !== undefined) + data["Tags"] = params["tags"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<VerificationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<VerificationInstance> => ({ + ...response, + body: new VerificationInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/verify/v2/service/verificationCheck.ts b/rest/verify/v2/service/verificationCheck.ts new file mode 100644 index 000000000..cb1354c67 --- /dev/null +++ b/rest/verify/v2/service/verificationCheck.ts @@ -0,0 +1,323 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, or `sna`. + */ +export type VerificationCheckChannel = 'sms'|'call'|'email'|'whatsapp'|'sna'; + + +/** + * Options to pass to create a VerificationCheckInstance + */ +export interface VerificationCheckListInstanceCreateOptions { + /** The 4-10 character string being verified. */ + "code"?: string; + /** The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). */ + "to"?: string; + /** A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. */ + "verificationSid"?: string; + /** The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. */ + "amount"?: string; + /** The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. */ + "payee"?: string; + /** A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. */ + "snaClientToken"?: string; +} + + +export interface VerificationCheckSolution { + serviceSid: string; +} + +export interface VerificationCheckListInstance { + _version: V2; + _solution: VerificationCheckSolution; + _uri: string; + + + + /** + * Create a VerificationCheckInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationCheckInstance + */ + create(callback?: (error: Error | null, item?: VerificationCheckInstance) => any): Promise<VerificationCheckInstance>; + /** + * Create a VerificationCheckInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationCheckInstance + */ + create(params: VerificationCheckListInstanceCreateOptions, callback?: (error: Error | null, item?: VerificationCheckInstance) => any): Promise<VerificationCheckInstance>; + + /** + * Create a VerificationCheckInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationCheckInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VerificationCheckInstance>) => any): Promise<ApiResponse<VerificationCheckInstance>>; + /** + * Create a VerificationCheckInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationCheckInstance with HTTP metadata + */ + createWithHttpInfo(params: VerificationCheckListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<VerificationCheckInstance>) => any): Promise<ApiResponse<VerificationCheckInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function VerificationCheckListInstance(version: V2, serviceSid: string): VerificationCheckListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = {} as VerificationCheckListInstance; + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/VerificationCheck`; + + instance.create = function create(params?: VerificationCheckListInstanceCreateOptions | ((error: Error | null, items: VerificationCheckInstance) => any), callback?: (error: Error | null, items: VerificationCheckInstance) => any): Promise<VerificationCheckInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["code"] !== undefined) + data["Code"] = params["code"]; + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["verificationSid"] !== undefined) + data["VerificationSid"] = params["verificationSid"]; + if (params["amount"] !== undefined) + data["Amount"] = params["amount"]; + if (params["payee"] !== undefined) + data["Payee"] = params["payee"]; + if (params["snaClientToken"] !== undefined) + data["SnaClientToken"] = params["snaClientToken"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new VerificationCheckInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: VerificationCheckListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<VerificationCheckInstance>) => any), callback?: (error: Error | null, items: ApiResponse<VerificationCheckInstance>) => any): Promise<ApiResponse<VerificationCheckInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["code"] !== undefined) + data["Code"] = params["code"]; + if (params["to"] !== undefined) + data["To"] = params["to"]; + if (params["verificationSid"] !== undefined) + data["VerificationSid"] = params["verificationSid"]; + if (params["amount"] !== undefined) + data["Amount"] = params["amount"]; + if (params["payee"] !== undefined) + data["Payee"] = params["payee"]; + if (params["snaClientToken"] !== undefined) + data["SnaClientToken"] = params["snaClientToken"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<VerificationCheckResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<VerificationCheckInstance> => ({ + ...response, + body: new VerificationCheckInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface VerificationCheckPayload extends VerificationCheckResource {} + +interface VerificationCheckResource { + sid: string; + service_sid: string; + account_sid: string; + to: string; + channel: VerificationCheckChannel; + status: string; + valid: boolean; + amount: string; + payee: string; + date_created: Date; + date_updated: Date; + sna_attempts_error_codes: Array<any>; +} + +export class VerificationCheckInstance { + + constructor(protected _version: V2, payload: VerificationCheckResource, serviceSid: string) { + + this.sid = (payload.sid); + this.serviceSid = (payload.service_sid); + this.accountSid = (payload.account_sid); + this.to = (payload.to); + this.channel = payload.channel; + this.status = (payload.status); + this.valid = (payload.valid); + this.amount = (payload.amount); + this.payee = (payload.payee); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.snaAttemptsErrorCodes = (payload.sna_attempts_error_codes); + + } + + /** + * The unique string that we created to identify the VerificationCheck resource. + */ + sid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + */ + serviceSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the VerificationCheck resource. + */ + accountSid: string; + /** + * The phone number or [email](https://www.twilio.com/docs/verify/email) being verified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + */ + to: string; + channel: VerificationCheckChannel; + /** + * The status of the verification. Can be: `pending`, `approved`, `canceled`, `max_attempts_reached`, `deleted`, `failed` or `expired`. + */ + status: string; + /** + * Use \"status\" instead. Legacy property indicating whether the verification was successful. + */ + valid: boolean; + /** + * The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + */ + amount: string; + /** + * The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + */ + payee: string; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the Verification Check resource was created. + */ + dateCreated: Date; + /** + * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the Verification Check resource was last updated. + */ + dateUpdated: Date; + /** + * List of error codes as a result of attempting a verification using the `sna` channel. The error codes are chronologically ordered, from the first attempt to the latest attempt. This will be an empty list if no errors occured or `null` if the last channel used wasn\'t `sna`. + */ + snaAttemptsErrorCodes: Array<any>; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + serviceSid: this.serviceSid, + accountSid: this.accountSid, + to: this.to, + channel: this.channel, + status: this.status, + valid: this.valid, + amount: this.amount, + payee: this.payee, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + snaAttemptsErrorCodes: this.snaAttemptsErrorCodes, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/verify/v2/service/webhook.ts b/rest/verify/v2/service/webhook.ts new file mode 100644 index 000000000..11956080a --- /dev/null +++ b/rest/verify/v2/service/webhook.ts @@ -0,0 +1,1012 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V2 from "../../V2"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The method to be used when calling the webhook\'s URL. + */ +export type WebhookMethods = 'GET'|'POST'; + +/** + * The webhook status. Default value is `enabled`. One of: `enabled` or `disabled` + */ +export type WebhookStatus = 'enabled'|'disabled'; + +/** + * The webhook version. Default value is `v2` which includes all the latest fields. Version `v1` is legacy and may be removed in the future. + */ +export type WebhookVersion = 'v1'|'v2'; + + + + +/** + * Options to pass to update a WebhookInstance + */ +export interface WebhookContextUpdateOptions { + /** The string that you assigned to describe the webhook. **This value should not contain PII.** */ + "friendlyName"?: string; + /** The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` */ + "eventTypes"?: Array<string>; + /** The URL associated with this Webhook. */ + "webhookUrl"?: string; + /** */ + "status"?: WebhookStatus; + /** */ + "versionParam"?: WebhookVersion; +} + +/** + * Options to pass to create a WebhookInstance + */ +export interface WebhookListInstanceCreateOptions { + /** The string that you assigned to describe the webhook. **This value should not contain PII.** */ + "friendlyName": string; + /** The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` */ + "eventTypes": Array<string>; + /** The URL associated with this Webhook. */ + "webhookUrl": string; + /** */ + "status"?: WebhookStatus; + /** */ + "versionParam"?: WebhookVersion; +} + +/** + * Options to pass to each + */ +export interface WebhookListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: WebhookInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface WebhookListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface WebhookListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface WebhookContext { + + /** + * Remove a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance> + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>> + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance>; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance>; + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface WebhookContextSolution { + "serviceSid": string; + "sid": string; +} + +export class WebhookContextImpl implements WebhookContext { + protected _solution: WebhookContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, serviceSid: string, sid: string) { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { serviceSid, sid, }; + this._uri = `/Services/${serviceSid}/Webhooks/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<WebhookResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<WebhookInstance> => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: WebhookInstance) => any),callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["eventTypes"] !== undefined) + data["EventTypes"] = serialize.map(params["eventTypes"], (e: string) => (e)); + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["versionParam"] !== undefined) + data["Version"] = params["versionParam"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.serviceSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: WebhookContextUpdateOptions | ((error: Error | null, item?: ApiResponse<WebhookInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["eventTypes"] !== undefined) + data["EventTypes"] = serialize.map(params["eventTypes"], (e: string) => (e)); + if (params["webhookUrl"] !== undefined) + data["WebhookUrl"] = params["webhookUrl"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["versionParam"] !== undefined) + data["Version"] = params["versionParam"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<WebhookResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<WebhookInstance> => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.serviceSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface WebhookPayload extends TwilioResponsePayload { + webhooks: WebhookResource[]; +} + +interface WebhookResource { + sid: string; + service_sid: string; + account_sid: string; + friendly_name: string; + event_types: Array<string>; + status: WebhookStatus; + version: WebhookVersion; + webhook_url: string; + webhook_method: WebhookMethods; + date_created: Date; + date_updated: Date; + url: string; +} + +export class WebhookInstance { + protected _solution: WebhookContextSolution; + protected _context?: WebhookContext; + + constructor(protected _version: V2, payload: WebhookResource, serviceSid: string, sid?: string) { + + this.sid = (payload.sid); + this.serviceSid = (payload.service_sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.eventTypes = (payload.event_types); + this.status = payload.status; + this.version = payload.version; + this.webhookUrl = (payload.webhook_url); + this.webhookMethod = payload.webhook_method; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { serviceSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the Webhook resource. + */ + sid: string; + /** + * The unique SID identifier of the Service. + */ + serviceSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the webhook. **This value should not contain PII.** + */ + friendlyName: string; + /** + * The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + */ + eventTypes: Array<string>; + status: WebhookStatus; + version: WebhookVersion; + /** + * The URL associated with this Webhook. + */ + webhookUrl: string; + webhookMethod: WebhookMethods; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the Webhook resource. + */ + url: string; + + private get _proxy(): WebhookContext { + this._context = this._context || new WebhookContextImpl(this._version, this._solution.serviceSid, this._solution.sid); + return this._context; + } + + /** + * Remove a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + fetch(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a WebhookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance>; + /** + * Update a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + update(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance>; + + update(params?: any, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a WebhookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>>; + /** + * Update a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + updateWithHttpInfo(params: WebhookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + serviceSid: this.serviceSid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + eventTypes: this.eventTypes, + status: this.status, + version: this.version, + webhookUrl: this.webhookUrl, + webhookMethod: this.webhookMethod, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface WebhookSolution { + serviceSid: string; +} + +export interface WebhookListInstance { + _version: V2; + _solution: WebhookSolution; + _uri: string; + + (sid: string, ): WebhookContext; + get(sid: string, ): WebhookContext; + + + + + + + + + /** + * Create a WebhookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance + */ + create(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, item?: WebhookInstance) => any): Promise<WebhookInstance>; + + /** + * Create a WebhookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed WebhookInstance with HTTP metadata + */ + createWithHttpInfo(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>>; + + + + + /** + * Streams WebhookInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + each(params: WebhookListInstanceEachOptions, callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + /** + * Streams WebhookInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: WebhookListInstanceEachOptions, callback?: (item: WebhookInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of WebhookInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: WebhookPage) => any): Promise<WebhookPage>; + /** + * Retrieve a single target page of WebhookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<WebhookPage>) => any): Promise<ApiResponse<WebhookPage>>; + /** + * Lists WebhookInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: WebhookInstance[]) => any): Promise<WebhookInstance[]>; + list(params: WebhookListInstanceOptions, callback?: (error: Error | null, items: WebhookInstance[]) => any): Promise<WebhookInstance[]>; + /** + * Lists WebhookInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<WebhookInstance[]>) => any): Promise<ApiResponse<WebhookInstance[]>>; + listWithHttpInfo(params: WebhookListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<WebhookInstance[]>) => any): Promise<ApiResponse<WebhookInstance[]>>; + /** + * Retrieve a single page of WebhookInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: WebhookPage) => any): Promise<WebhookPage>; + page(params: WebhookListInstancePageOptions, callback?: (error: Error | null, items: WebhookPage) => any): Promise<WebhookPage>; + /** + * Retrieve a single page of WebhookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { WebhookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<WebhookPage>) => any): Promise<ApiResponse<WebhookPage>>; + pageWithHttpInfo(params: WebhookListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<WebhookPage>) => any): Promise<ApiResponse<WebhookPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function WebhookListInstance(version: V2, serviceSid: string): WebhookListInstance { + if (!isValidPathParam(serviceSid)) { + throw new Error('Parameter \'serviceSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as WebhookListInstance; + + instance.get = function get(sid, ): WebhookContext { + return new WebhookContextImpl(version, serviceSid, sid); + } + + instance._version = version; + instance._solution = { serviceSid, }; + instance._uri = `/Services/${serviceSid}/Webhooks`; + + instance.create = function create(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, items: WebhookInstance) => any): Promise<WebhookInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["eventTypes"] === null || params["eventTypes"] === undefined) { + throw new Error('Required parameter "params[\'eventTypes\']" missing.'); + } + + if (params["webhookUrl"] === null || params["webhookUrl"] === undefined) { + throw new Error('Required parameter "params[\'webhookUrl\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["EventTypes"] = serialize.map(params["eventTypes"], (e: string) => (e)); + + data["WebhookUrl"] = params["webhookUrl"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["versionParam"] !== undefined) + data["Version"] = params["versionParam"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new WebhookInstance(operationVersion, payload, instance._solution.serviceSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: WebhookListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<WebhookInstance>) => any): Promise<ApiResponse<WebhookInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + if (params["eventTypes"] === null || params["eventTypes"] === undefined) { + throw new Error('Required parameter "params[\'eventTypes\']" missing.'); + } + + if (params["webhookUrl"] === null || params["webhookUrl"] === undefined) { + throw new Error('Required parameter "params[\'webhookUrl\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + + data["EventTypes"] = serialize.map(params["eventTypes"], (e: string) => (e)); + + data["WebhookUrl"] = params["webhookUrl"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["versionParam"] !== undefined) + data["Version"] = params["versionParam"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<WebhookResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<WebhookInstance> => ({ + ...response, + body: new WebhookInstance(operationVersion, response.body, instance._solution.serviceSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: WebhookListInstancePageOptions | ((error: Error | null, items: WebhookPage) => any), callback?: (error: Error | null, items: WebhookPage) => any): Promise<WebhookPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new WebhookPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: WebhookPage) => any): Promise<WebhookPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new WebhookPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: WebhookListInstancePageOptions | ((error: Error | null, items: ApiResponse<WebhookPage>) => any), callback?: (error: Error | null, items: ApiResponse<WebhookPage>) => any): Promise<ApiResponse<WebhookPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<WebhookPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebhookPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<WebhookPage>) => any): Promise<ApiResponse<WebhookPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<WebhookPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new WebhookPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class WebhookPage extends Page<V2, WebhookPayload, WebhookResource, WebhookInstance> { +/** +* Initialize the WebhookPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: WebhookSolution) { + super(version, response, solution); + } + + /** + * Build an instance of WebhookInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: WebhookResource): WebhookInstance { + + return new WebhookInstance( + this._version, + payload, + this._solution.serviceSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/verify/v2/template.ts b/rest/verify/v2/template.ts new file mode 100644 index 000000000..bb6c63cd2 --- /dev/null +++ b/rest/verify/v2/template.ts @@ -0,0 +1,416 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface TemplateListInstanceEachOptions { + /** String filter used to query templates with a given friendly name. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TemplateInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TemplateListInstanceOptions { + /** String filter used to query templates with a given friendly name. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TemplateListInstancePageOptions { + /** String filter used to query templates with a given friendly name. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface TemplateSolution { +} + +export interface TemplateListInstance { + _version: V2; + _solution: TemplateSolution; + _uri: string; + + + + + /** + * Streams TemplateInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TemplateListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TemplateInstance, done: (err?: Error) => void) => void): void; + each(params: TemplateListInstanceEachOptions, callback?: (item: TemplateInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TemplateInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TemplateListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TemplateInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TemplateListInstanceEachOptions, callback?: (item: TemplateInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TemplateInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TemplatePage) => any): Promise<TemplatePage>; + /** + * Retrieve a single target page of TemplateInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TemplatePage>) => any): Promise<ApiResponse<TemplatePage>>; + /** + * Lists TemplateInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TemplateListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TemplateInstance[]) => any): Promise<TemplateInstance[]>; + list(params: TemplateListInstanceOptions, callback?: (error: Error | null, items: TemplateInstance[]) => any): Promise<TemplateInstance[]>; + /** + * Lists TemplateInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TemplateListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TemplateInstance[]>) => any): Promise<ApiResponse<TemplateInstance[]>>; + listWithHttpInfo(params: TemplateListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TemplateInstance[]>) => any): Promise<ApiResponse<TemplateInstance[]>>; + /** + * Retrieve a single page of TemplateInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TemplateListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TemplatePage) => any): Promise<TemplatePage>; + page(params: TemplateListInstancePageOptions, callback?: (error: Error | null, items: TemplatePage) => any): Promise<TemplatePage>; + /** + * Retrieve a single page of TemplateInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TemplateListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TemplatePage>) => any): Promise<ApiResponse<TemplatePage>>; + pageWithHttpInfo(params: TemplateListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TemplatePage>) => any): Promise<ApiResponse<TemplatePage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TemplateListInstance(version: V2): TemplateListInstance { + const instance = {} as TemplateListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/Templates`; + + instance.page = function page(params?: TemplateListInstancePageOptions | ((error: Error | null, items: TemplatePage) => any), callback?: (error: Error | null, items: TemplatePage) => any): Promise<TemplatePage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TemplatePage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TemplatePage) => any): Promise<TemplatePage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TemplatePage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TemplateListInstancePageOptions | ((error: Error | null, items: ApiResponse<TemplatePage>) => any), callback?: (error: Error | null, items: ApiResponse<TemplatePage>) => any): Promise<ApiResponse<TemplatePage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TemplatePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TemplatePage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TemplatePage>) => any): Promise<ApiResponse<TemplatePage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TemplatePage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TemplatePage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface TemplatePayload extends TwilioResponsePayload { + templates: TemplateResource[]; +} + +interface TemplateResource { + sid: string; + account_sid: string; + friendly_name: string; + channels: Array<string>; + translations: any; +} + +export class TemplateInstance { + + constructor(protected _version: V2, payload: TemplateResource) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.channels = (payload.channels); + this.translations = (payload.translations); + + } + + /** + * A 34 character string that uniquely identifies a Verification Template. + */ + sid: string; + /** + * The unique SID identifier of the Account. + */ + accountSid: string; + /** + * A descriptive string that you create to describe a Template. It can be up to 32 characters long. + */ + friendlyName: string; + /** + * A list of channels that support the Template. Can include: sms, voice. + */ + channels: Array<string>; + /** + * An object that contains the different translations of the template. Every translation is identified by the language short name and contains its respective information as the approval status, text and created/modified date. + */ + translations: any; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + channels: this.channels, + translations: this.translations, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class TemplatePage extends Page<V2, TemplatePayload, TemplateResource, TemplateInstance> { +/** +* Initialize the TemplatePage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: TemplateSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TemplateInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TemplateResource): TemplateInstance { + + return new TemplateInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/verify/v2/verificationAttempt.ts b/rest/verify/v2/verificationAttempt.ts new file mode 100644 index 000000000..d4ae7b189 --- /dev/null +++ b/rest/verify/v2/verificationAttempt.ts @@ -0,0 +1,667 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * A string specifying the communication channel used for the verification attempt. + */ +export type VerificationAttemptChannels = 'sms'|'call'|'email'|'whatsapp'|'rbm'; + +/** + * A string specifying the conversion status of the verification. A conversion happens when the user is able to provide the correct code. Possible values are `CONVERTED` and `UNCONVERTED`. + */ +export type VerificationAttemptConversionStatus = 'converted'|'unconverted'; + + + +/** + * Options to pass to each + */ +export interface VerificationAttemptListInstanceEachOptions { + /** Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd\'T\'HH:mm:ss\'Z. */ + "dateCreatedAfter"?: Date; + /** Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd\'T\'HH:mm:ss\'Z. */ + "dateCreatedBefore"?: Date; + /** Destination of a verification. It is phone number in E.164 format. */ + "channelData.to"?: string; + /** Filter used to query Verification Attempts sent to the specified destination country. */ + "country"?: string; + /** Filter used to query Verification Attempts by communication channel. */ + "channel"?: VerificationAttemptChannels; + /** Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. */ + "verifyServiceSid"?: string; + /** Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. */ + "verificationSid"?: string; + /** Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. */ + "status"?: VerificationAttemptConversionStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: VerificationAttemptInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface VerificationAttemptListInstanceOptions { + /** Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd\'T\'HH:mm:ss\'Z. */ + "dateCreatedAfter"?: Date; + /** Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd\'T\'HH:mm:ss\'Z. */ + "dateCreatedBefore"?: Date; + /** Destination of a verification. It is phone number in E.164 format. */ + "channelData.to"?: string; + /** Filter used to query Verification Attempts sent to the specified destination country. */ + "country"?: string; + /** Filter used to query Verification Attempts by communication channel. */ + "channel"?: VerificationAttemptChannels; + /** Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. */ + "verifyServiceSid"?: string; + /** Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. */ + "verificationSid"?: string; + /** Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. */ + "status"?: VerificationAttemptConversionStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface VerificationAttemptListInstancePageOptions { + /** Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd\'T\'HH:mm:ss\'Z. */ + "dateCreatedAfter"?: Date; + /** Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd\'T\'HH:mm:ss\'Z. */ + "dateCreatedBefore"?: Date; + /** Destination of a verification. It is phone number in E.164 format. */ + "channelData.to"?: string; + /** Filter used to query Verification Attempts sent to the specified destination country. */ + "country"?: string; + /** Filter used to query Verification Attempts by communication channel. */ + "channel"?: VerificationAttemptChannels; + /** Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. */ + "verifyServiceSid"?: string; + /** Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. */ + "verificationSid"?: string; + /** Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. */ + "status"?: VerificationAttemptConversionStatus; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface VerificationAttemptContext { + + /** + * Fetch a VerificationAttemptInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptInstance + */ + fetch(callback?: (error: Error | null, item?: VerificationAttemptInstance) => any): Promise<VerificationAttemptInstance> + + /** + * Fetch a VerificationAttemptInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VerificationAttemptInstance>) => any): Promise<ApiResponse<VerificationAttemptInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface VerificationAttemptContextSolution { + "sid": string; +} + +export class VerificationAttemptContextImpl implements VerificationAttemptContext { + protected _solution: VerificationAttemptContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Attempts/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: VerificationAttemptInstance) => any): Promise<VerificationAttemptInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new VerificationAttemptInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VerificationAttemptInstance>) => any): Promise<ApiResponse<VerificationAttemptInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<VerificationAttemptResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<VerificationAttemptInstance> => ({ + ...response, + body: new VerificationAttemptInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface VerificationAttemptPayload extends TwilioResponsePayload { + attempts: VerificationAttemptResource[]; +} + +interface VerificationAttemptResource { + sid: string; + account_sid: string; + service_sid: string; + verification_sid: string; + date_created: Date; + date_updated: Date; + conversion_status: VerificationAttemptConversionStatus; + channel: VerificationAttemptChannels; + price: any; + channel_data: any; + url: string; +} + +export class VerificationAttemptInstance { + protected _solution: VerificationAttemptContextSolution; + protected _context?: VerificationAttemptContext; + + constructor(protected _version: V2, payload: VerificationAttemptResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.serviceSid = (payload.service_sid); + this.verificationSid = (payload.verification_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.conversionStatus = payload.conversion_status; + this.channel = payload.channel; + this.price = (payload.price); + this.channelData = (payload.channel_data); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The SID that uniquely identifies the verification attempt resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Verification resource. + */ + accountSid: string; + /** + * The SID of the [Service](https://www.twilio.com/docs/verify/api/service) used to generate the attempt. + */ + serviceSid: string; + /** + * The SID of the [Verification](https://www.twilio.com/docs/verify/api/verification) that generated the attempt. + */ + verificationSid: string; + /** + * The date that this Attempt was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date that this Attempt was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + conversionStatus: VerificationAttemptConversionStatus; + channel: VerificationAttemptChannels; + /** + * An object containing the charge for this verification attempt related to the channel costs and the currency used. The costs related to the succeeded verifications are not included. May not be immediately available. More information on pricing is available [here](https://www.twilio.com/en-us/verify/pricing). + */ + price: any; + /** + * An object containing the channel specific information for an attempt. + */ + channelData: any; + url: string; + + private get _proxy(): VerificationAttemptContext { + this._context = this._context || new VerificationAttemptContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a VerificationAttemptInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptInstance + */ + fetch(callback?: (error: Error | null, item?: VerificationAttemptInstance) => any): Promise<VerificationAttemptInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a VerificationAttemptInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VerificationAttemptInstance>) => any): Promise<ApiResponse<VerificationAttemptInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + serviceSid: this.serviceSid, + verificationSid: this.verificationSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + conversionStatus: this.conversionStatus, + channel: this.channel, + price: this.price, + channelData: this.channelData, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface VerificationAttemptSolution { +} + +export interface VerificationAttemptListInstance { + _version: V2; + _solution: VerificationAttemptSolution; + _uri: string; + + (sid: string, ): VerificationAttemptContext; + get(sid: string, ): VerificationAttemptContext; + + + + + + /** + * Streams VerificationAttemptInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VerificationAttemptListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: VerificationAttemptInstance, done: (err?: Error) => void) => void): void; + each(params: VerificationAttemptListInstanceEachOptions, callback?: (item: VerificationAttemptInstance, done: (err?: Error) => void) => void): void; + /** + * Streams VerificationAttemptInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VerificationAttemptListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: VerificationAttemptInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: VerificationAttemptListInstanceEachOptions, callback?: (item: VerificationAttemptInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of VerificationAttemptInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: VerificationAttemptPage) => any): Promise<VerificationAttemptPage>; + /** + * Retrieve a single target page of VerificationAttemptInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<VerificationAttemptPage>) => any): Promise<ApiResponse<VerificationAttemptPage>>; + /** + * Lists VerificationAttemptInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VerificationAttemptListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: VerificationAttemptInstance[]) => any): Promise<VerificationAttemptInstance[]>; + list(params: VerificationAttemptListInstanceOptions, callback?: (error: Error | null, items: VerificationAttemptInstance[]) => any): Promise<VerificationAttemptInstance[]>; + /** + * Lists VerificationAttemptInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VerificationAttemptListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<VerificationAttemptInstance[]>) => any): Promise<ApiResponse<VerificationAttemptInstance[]>>; + listWithHttpInfo(params: VerificationAttemptListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<VerificationAttemptInstance[]>) => any): Promise<ApiResponse<VerificationAttemptInstance[]>>; + /** + * Retrieve a single page of VerificationAttemptInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VerificationAttemptListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: VerificationAttemptPage) => any): Promise<VerificationAttemptPage>; + page(params: VerificationAttemptListInstancePageOptions, callback?: (error: Error | null, items: VerificationAttemptPage) => any): Promise<VerificationAttemptPage>; + /** + * Retrieve a single page of VerificationAttemptInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { VerificationAttemptListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<VerificationAttemptPage>) => any): Promise<ApiResponse<VerificationAttemptPage>>; + pageWithHttpInfo(params: VerificationAttemptListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<VerificationAttemptPage>) => any): Promise<ApiResponse<VerificationAttemptPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function VerificationAttemptListInstance(version: V2): VerificationAttemptListInstance { + const instance = ((sid, ) => instance.get(sid, )) as VerificationAttemptListInstance; + + instance.get = function get(sid, ): VerificationAttemptContext { + return new VerificationAttemptContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Attempts`; + + instance.page = function page(params?: VerificationAttemptListInstancePageOptions | ((error: Error | null, items: VerificationAttemptPage) => any), callback?: (error: Error | null, items: VerificationAttemptPage) => any): Promise<VerificationAttemptPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["channelData.to"] !== undefined) + data["ChannelData.To"] = params["channelData.to"]; + if (params["country"] !== undefined) + data["Country"] = params["country"]; + if (params["channel"] !== undefined) + data["Channel"] = params["channel"]; + if (params["verifyServiceSid"] !== undefined) + data["VerifyServiceSid"] = params["verifyServiceSid"]; + if (params["verificationSid"] !== undefined) + data["VerificationSid"] = params["verificationSid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new VerificationAttemptPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: VerificationAttemptPage) => any): Promise<VerificationAttemptPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new VerificationAttemptPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: VerificationAttemptListInstancePageOptions | ((error: Error | null, items: ApiResponse<VerificationAttemptPage>) => any), callback?: (error: Error | null, items: ApiResponse<VerificationAttemptPage>) => any): Promise<ApiResponse<VerificationAttemptPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["channelData.to"] !== undefined) + data["ChannelData.To"] = params["channelData.to"]; + if (params["country"] !== undefined) + data["Country"] = params["country"]; + if (params["channel"] !== undefined) + data["Channel"] = params["channel"]; + if (params["verifyServiceSid"] !== undefined) + data["VerifyServiceSid"] = params["verifyServiceSid"]; + if (params["verificationSid"] !== undefined) + data["VerificationSid"] = params["verificationSid"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<VerificationAttemptPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new VerificationAttemptPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<VerificationAttemptPage>) => any): Promise<ApiResponse<VerificationAttemptPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<VerificationAttemptPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new VerificationAttemptPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class VerificationAttemptPage extends Page<V2, VerificationAttemptPayload, VerificationAttemptResource, VerificationAttemptInstance> { +/** +* Initialize the VerificationAttemptPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: VerificationAttemptSolution) { + super(version, response, solution); + } + + /** + * Build an instance of VerificationAttemptInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: VerificationAttemptResource): VerificationAttemptInstance { + + return new VerificationAttemptInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/verify/v2/verificationAttemptsSummary.ts b/rest/verify/v2/verificationAttemptsSummary.ts new file mode 100644 index 000000000..95791318b --- /dev/null +++ b/rest/verify/v2/verificationAttemptsSummary.ts @@ -0,0 +1,363 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export type VerificationAttemptsSummaryChannels = 'sms'|'call'|'email'|'whatsapp'|'rbm'; + + +/** + * Options to pass to fetch a VerificationAttemptsSummaryInstance + */ +export interface VerificationAttemptsSummaryContextFetchOptions { + /** Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. */ + "verifyServiceSid"?: string; + /** Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd\'T\'HH:mm:ss\'Z. */ + "dateCreatedAfter"?: Date; + /** Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd\'T\'HH:mm:ss\'Z. */ + "dateCreatedBefore"?: Date; + /** Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. */ + "country"?: string; + /** Filter Verification Attempts considered on the summary aggregation by communication channel. */ + "channel"?: VerificationAttemptsSummaryChannels; + /** Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. */ + "destinationPrefix"?: string; +} + +export interface VerificationAttemptsSummaryContext { + + /** + * Fetch a VerificationAttemptsSummaryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptsSummaryInstance + */ + fetch(callback?: (error: Error | null, item?: VerificationAttemptsSummaryInstance) => any): Promise<VerificationAttemptsSummaryInstance>; + /** + * Fetch a VerificationAttemptsSummaryInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptsSummaryInstance + */ + fetch(params: VerificationAttemptsSummaryContextFetchOptions, callback?: (error: Error | null, item?: VerificationAttemptsSummaryInstance) => any): Promise<VerificationAttemptsSummaryInstance>; + + /** + * Fetch a VerificationAttemptsSummaryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptsSummaryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VerificationAttemptsSummaryInstance>) => any): Promise<ApiResponse<VerificationAttemptsSummaryInstance>>; + /** + * Fetch a VerificationAttemptsSummaryInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptsSummaryInstance with HTTP metadata + */ + fetchWithHttpInfo(params: VerificationAttemptsSummaryContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<VerificationAttemptsSummaryInstance>) => any): Promise<ApiResponse<VerificationAttemptsSummaryInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface VerificationAttemptsSummaryContextSolution { +} + +export class VerificationAttemptsSummaryContextImpl implements VerificationAttemptsSummaryContext { + protected _solution: VerificationAttemptsSummaryContextSolution; + protected _uri: string; + + + constructor(protected _version: V2) { + this._solution = { }; + this._uri = `/Attempts/Summary`; + } + + fetch(params?: VerificationAttemptsSummaryContextFetchOptions | ((error: Error | null, item?: VerificationAttemptsSummaryInstance) => any),callback?: (error: Error | null, item?: VerificationAttemptsSummaryInstance) => any): Promise<VerificationAttemptsSummaryInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["verifyServiceSid"] !== undefined) + data["VerifyServiceSid"] = params["verifyServiceSid"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["country"] !== undefined) + data["Country"] = params["country"]; + if (params["channel"] !== undefined) + data["Channel"] = params["channel"]; + if (params["destinationPrefix"] !== undefined) + data["DestinationPrefix"] = params["destinationPrefix"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new VerificationAttemptsSummaryInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(params?: VerificationAttemptsSummaryContextFetchOptions | ((error: Error | null, item?: ApiResponse<VerificationAttemptsSummaryInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<VerificationAttemptsSummaryInstance>) => any): Promise<ApiResponse<VerificationAttemptsSummaryInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["verifyServiceSid"] !== undefined) + data["VerifyServiceSid"] = params["verifyServiceSid"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["country"] !== undefined) + data["Country"] = params["country"]; + if (params["channel"] !== undefined) + data["Channel"] = params["channel"]; + if (params["destinationPrefix"] !== undefined) + data["DestinationPrefix"] = params["destinationPrefix"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<VerificationAttemptsSummaryResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<VerificationAttemptsSummaryInstance> => ({ + ...response, + body: new VerificationAttemptsSummaryInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface VerificationAttemptsSummaryPayload extends VerificationAttemptsSummaryResource {} + +interface VerificationAttemptsSummaryResource { + total_attempts: number; + total_converted: number; + total_unconverted: number; + conversion_rate_percentage: string; + url: string; +} + +export class VerificationAttemptsSummaryInstance { + protected _solution: VerificationAttemptsSummaryContextSolution; + protected _context?: VerificationAttemptsSummaryContext; + + constructor(protected _version: V2, payload: VerificationAttemptsSummaryResource) { + + this.totalAttempts = deserialize.integer(payload.total_attempts); + this.totalConverted = deserialize.integer(payload.total_converted); + this.totalUnconverted = deserialize.integer(payload.total_unconverted); + this.conversionRatePercentage = (payload.conversion_rate_percentage); + this.url = (payload.url); + + this._solution = { }; + } + + /** + * Total of attempts made according to the provided filters + */ + totalAttempts: number; + /** + * Total of attempts made that were confirmed by the end user, according to the provided filters. + */ + totalConverted: number; + /** + * Total of attempts made that were not confirmed by the end user, according to the provided filters. + */ + totalUnconverted: number; + /** + * Percentage of the confirmed messages over the total, defined by (total_converted/total_attempts)*100. + */ + conversionRatePercentage: string; + url: string; + + private get _proxy(): VerificationAttemptsSummaryContext { + this._context = this._context || new VerificationAttemptsSummaryContextImpl(this._version); + return this._context; + } + + /** + * Fetch a VerificationAttemptsSummaryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptsSummaryInstance + */ + fetch(callback?: (error: Error | null, item?: VerificationAttemptsSummaryInstance) => any): Promise<VerificationAttemptsSummaryInstance>; + /** + * Fetch a VerificationAttemptsSummaryInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptsSummaryInstance + */ + fetch(params: VerificationAttemptsSummaryContextFetchOptions, callback?: (error: Error | null, item?: VerificationAttemptsSummaryInstance) => any): Promise<VerificationAttemptsSummaryInstance>; + + fetch(params?: any, callback?: (error: Error | null, item?: VerificationAttemptsSummaryInstance) => any): Promise<VerificationAttemptsSummaryInstance> + { + return this._proxy.fetch(params, callback); + } + + /** + * Fetch a VerificationAttemptsSummaryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptsSummaryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<VerificationAttemptsSummaryInstance>) => any): Promise<ApiResponse<VerificationAttemptsSummaryInstance>>; + /** + * Fetch a VerificationAttemptsSummaryInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed VerificationAttemptsSummaryInstance with HTTP metadata + */ + fetchWithHttpInfo(params: VerificationAttemptsSummaryContextFetchOptions, callback?: (error: Error | null, item?: ApiResponse<VerificationAttemptsSummaryInstance>) => any): Promise<ApiResponse<VerificationAttemptsSummaryInstance>>; + + fetchWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<VerificationAttemptsSummaryInstance>) => any): Promise<ApiResponse<VerificationAttemptsSummaryInstance>> + { + return this._proxy.fetchWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + totalAttempts: this.totalAttempts, + totalConverted: this.totalConverted, + totalUnconverted: this.totalUnconverted, + conversionRatePercentage: this.conversionRatePercentage, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface VerificationAttemptsSummarySolution { +} + +export interface VerificationAttemptsSummaryListInstance { + _version: V2; + _solution: VerificationAttemptsSummarySolution; + _uri: string; + + (): VerificationAttemptsSummaryContext; + get(): VerificationAttemptsSummaryContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function VerificationAttemptsSummaryListInstance(version: V2): VerificationAttemptsSummaryListInstance { + const instance = (() => instance.get()) as VerificationAttemptsSummaryListInstance; + + instance.get = function get(): VerificationAttemptsSummaryContext { + return new VerificationAttemptsSummaryContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/video/V1.ts b/rest/video/V1.ts new file mode 100644 index 000000000..74db53155 --- /dev/null +++ b/rest/video/V1.ts @@ -0,0 +1,83 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import VideoBase from "../VideoBase"; +import Version from "../../base/Version"; +import { CompositionListInstance } from "./v1/composition"; +import { CompositionHookListInstance } from "./v1/compositionHook"; +import { CompositionSettingsListInstance } from "./v1/compositionSettings"; +import { RecordingListInstance } from "./v1/recording"; +import { RecordingSettingsListInstance } from "./v1/recordingSettings"; +import { RoomListInstance } from "./v1/room"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Video + * + * @param domain - The Twilio (Twilio.Video) domain + */ + constructor(domain: VideoBase) { + super(domain, "v1"); + } + + /** compositions - { Twilio.Video.V1.CompositionListInstance } resource */ + protected _compositions?: CompositionListInstance; + /** compositionHooks - { Twilio.Video.V1.CompositionHookListInstance } resource */ + protected _compositionHooks?: CompositionHookListInstance; + /** compositionSettings - { Twilio.Video.V1.CompositionSettingsListInstance } resource */ + protected _compositionSettings?: CompositionSettingsListInstance; + /** recordings - { Twilio.Video.V1.RecordingListInstance } resource */ + protected _recordings?: RecordingListInstance; + /** recordingSettings - { Twilio.Video.V1.RecordingSettingsListInstance } resource */ + protected _recordingSettings?: RecordingSettingsListInstance; + /** rooms - { Twilio.Video.V1.RoomListInstance } resource */ + protected _rooms?: RoomListInstance; + + /** Getter for compositions resource */ + get compositions(): CompositionListInstance { + this._compositions = this._compositions || CompositionListInstance(this); + return this._compositions; + } + + /** Getter for compositionHooks resource */ + get compositionHooks(): CompositionHookListInstance { + this._compositionHooks = this._compositionHooks || CompositionHookListInstance(this); + return this._compositionHooks; + } + + /** Getter for compositionSettings resource */ + get compositionSettings(): CompositionSettingsListInstance { + this._compositionSettings = this._compositionSettings || CompositionSettingsListInstance(this); + return this._compositionSettings; + } + + /** Getter for recordings resource */ + get recordings(): RecordingListInstance { + this._recordings = this._recordings || RecordingListInstance(this); + return this._recordings; + } + + /** Getter for recordingSettings resource */ + get recordingSettings(): RecordingSettingsListInstance { + this._recordingSettings = this._recordingSettings || RecordingSettingsListInstance(this); + return this._recordingSettings; + } + + /** Getter for rooms resource */ + get rooms(): RoomListInstance { + this._rooms = this._rooms || RoomListInstance(this); + return this._rooms; + } + +} diff --git a/rest/video/v1/composition.ts b/rest/video/v1/composition.ts new file mode 100644 index 000000000..6aa1b41ad --- /dev/null +++ b/rest/video/v1/composition.ts @@ -0,0 +1,925 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The container format of the composition\'s media files as specified in the POST request that created the Composition resource. See [POST Parameters](https://www.twilio.com/docs/video/api/compositions-resource#http-post-parameters) for more information. + */ +export type CompositionFormat = 'mp4'|'webm'; + +/** + * The status of the composition. Can be: `enqueued`, `processing`, `completed`, `deleted` or `failed`. `enqueued` is the initial state and indicates that the composition request has been received and is scheduled for processing; `processing` indicates the composition is being processed; `completed` indicates the composition has been completed and is available for download; `deleted` means the composition media has been deleted from the system, but its metadata is still available for 30 days; `failed` indicates the composition failed to execute the media processing task. + */ +export type CompositionStatus = 'enqueued'|'processing'|'completed'|'deleted'|'failed'; + + + + +/** + * Options to pass to create a CompositionInstance + */ +export interface CompositionListInstanceCreateOptions { + /** The SID of the Group Room with the media tracks to be used as composition sources. */ + "roomSid": string; + /** An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request */ + "videoLayout"?: any; + /** An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request */ + "audioSources"?: Array<string>; + /** An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. */ + "audioSourcesExcluded"?: Array<string>; + /** A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string\\\'s format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. */ + "resolution"?: string; + /** */ + "format"?: CompositionFormat; + /** The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. */ + "statusCallbackMethod"?: string; + /** Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. */ + "trim"?: boolean; +} + +/** + * Options to pass to each + */ +export interface CompositionListInstanceEachOptions { + /** Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. */ + "status"?: CompositionStatus; + /** Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only Composition resources created before this ISO 8601 date-time with time zone. */ + "dateCreatedBefore"?: Date; + /** Read only Composition resources with this Room SID. */ + "roomSid"?: string; + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CompositionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CompositionListInstanceOptions { + /** Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. */ + "status"?: CompositionStatus; + /** Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only Composition resources created before this ISO 8601 date-time with time zone. */ + "dateCreatedBefore"?: Date; + /** Read only Composition resources with this Room SID. */ + "roomSid"?: string; + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CompositionListInstancePageOptions { + /** Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. */ + "status"?: CompositionStatus; + /** Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only Composition resources created before this ISO 8601 date-time with time zone. */ + "dateCreatedBefore"?: Date; + /** Read only Composition resources with this Room SID. */ + "roomSid"?: string; + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CompositionContext { + + /** + * Remove a CompositionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a CompositionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a CompositionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionInstance + */ + fetch(callback?: (error: Error | null, item?: CompositionInstance) => any): Promise<CompositionInstance> + + /** + * Fetch a CompositionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CompositionInstance>) => any): Promise<ApiResponse<CompositionInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CompositionContextSolution { + "sid": string; +} + +export class CompositionContextImpl implements CompositionContext { + protected _solution: CompositionContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Compositions/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CompositionInstance) => any): Promise<CompositionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CompositionInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CompositionInstance>) => any): Promise<ApiResponse<CompositionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CompositionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CompositionInstance> => ({ + ...response, + body: new CompositionInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CompositionPayload extends TwilioResponsePayload { + compositions: CompositionResource[]; +} + +interface CompositionResource { + account_sid: string; + status: CompositionStatus; + date_created: Date; + date_completed: Date; + date_deleted: Date; + sid: string; + room_sid: string; + audio_sources: Array<string>; + audio_sources_excluded: Array<string>; + video_layout: any; + resolution: string; + trim: boolean; + format: CompositionFormat; + bitrate: number; + size: number; + duration: number; + media_external_location: string; + status_callback: string; + status_callback_method: string; + url: string; + links: Record<string, string>; +} + +export class CompositionInstance { + protected _solution: CompositionContextSolution; + protected _context?: CompositionContext; + + constructor(protected _version: V1, payload: CompositionResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.status = payload.status; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateCompleted = deserialize.iso8601DateTime(payload.date_completed); + this.dateDeleted = deserialize.iso8601DateTime(payload.date_deleted); + this.sid = (payload.sid); + this.roomSid = (payload.room_sid); + this.audioSources = (payload.audio_sources); + this.audioSourcesExcluded = (payload.audio_sources_excluded); + this.videoLayout = (payload.video_layout); + this.resolution = (payload.resolution); + this.trim = (payload.trim); + this.format = payload.format; + this.bitrate = deserialize.integer(payload.bitrate); + this.size = (payload.size); + this.duration = deserialize.integer(payload.duration); + this.mediaExternalLocation = (payload.media_external_location); + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Composition resource. + */ + accountSid: string; + status: CompositionStatus; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the composition\'s media processing task finished, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCompleted: Date; + /** + * The date and time in GMT when the composition generated media was deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateDeleted: Date; + /** + * The unique string that we created to identify the Composition resource. + */ + sid: string; + /** + * The SID of the Group Room that generated the audio and video tracks used in the composition. All media sources included in a composition must belong to the same Group Room. + */ + roomSid: string; + /** + * The array of track names to include in the composition. The composition includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + */ + audioSources: Array<string>; + /** + * The array of track names to exclude from the composition. The composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + */ + audioSourcesExcluded: Array<string>; + /** + * An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + */ + videoLayout: any; + /** + * The dimensions of the video image in pixels expressed as columns (width) and rows (height). The string\'s format is `{width}x{height}`, such as `640x480`. + */ + resolution: string; + /** + * Whether to remove intervals with no media, as specified in the POST request that created the composition. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + */ + trim: boolean; + format: CompositionFormat; + /** + * The average bit rate of the composition\'s media. + */ + bitrate: number; + /** + * The size of the composed media file in bytes. + */ + size: number; + /** + * The duration of the composition\'s media file in seconds. + */ + duration: number; + /** + * The URL of the media file associated with the composition when stored externally. See [External S3 Compositions](/docs/video/api/external-s3-compositions) for more details. + */ + mediaExternalLocation: string; + /** + * The URL called using the `status_callback_method` to send status information on every composition event. + */ + statusCallback: string; + /** + * The HTTP method used to call `status_callback`. Can be: `POST` or `GET`, defaults to `POST`. + */ + statusCallbackMethod: string; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URL of the media file associated with the composition. + */ + links: Record<string, string>; + + private get _proxy(): CompositionContext { + this._context = this._context || new CompositionContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CompositionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CompositionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CompositionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionInstance + */ + fetch(callback?: (error: Error | null, item?: CompositionInstance) => any): Promise<CompositionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CompositionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CompositionInstance>) => any): Promise<ApiResponse<CompositionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + status: this.status, + dateCreated: this.dateCreated, + dateCompleted: this.dateCompleted, + dateDeleted: this.dateDeleted, + sid: this.sid, + roomSid: this.roomSid, + audioSources: this.audioSources, + audioSourcesExcluded: this.audioSourcesExcluded, + videoLayout: this.videoLayout, + resolution: this.resolution, + trim: this.trim, + format: this.format, + bitrate: this.bitrate, + size: this.size, + duration: this.duration, + mediaExternalLocation: this.mediaExternalLocation, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CompositionSolution { +} + +export interface CompositionListInstance { + _version: V1; + _solution: CompositionSolution; + _uri: string; + + (sid: string, ): CompositionContext; + get(sid: string, ): CompositionContext; + + + + + + + /** + * Create a CompositionInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionInstance + */ + create(params: CompositionListInstanceCreateOptions, callback?: (error: Error | null, item?: CompositionInstance) => any): Promise<CompositionInstance>; + + /** + * Create a CompositionInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionInstance with HTTP metadata + */ + createWithHttpInfo(params: CompositionListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CompositionInstance>) => any): Promise<ApiResponse<CompositionInstance>>; + + + + + /** + * Streams CompositionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CompositionInstance, done: (err?: Error) => void) => void): void; + each(params: CompositionListInstanceEachOptions, callback?: (item: CompositionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CompositionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CompositionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CompositionListInstanceEachOptions, callback?: (item: CompositionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CompositionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CompositionPage) => any): Promise<CompositionPage>; + /** + * Retrieve a single target page of CompositionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CompositionPage>) => any): Promise<ApiResponse<CompositionPage>>; + /** + * Lists CompositionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CompositionInstance[]) => any): Promise<CompositionInstance[]>; + list(params: CompositionListInstanceOptions, callback?: (error: Error | null, items: CompositionInstance[]) => any): Promise<CompositionInstance[]>; + /** + * Lists CompositionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CompositionInstance[]>) => any): Promise<ApiResponse<CompositionInstance[]>>; + listWithHttpInfo(params: CompositionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CompositionInstance[]>) => any): Promise<ApiResponse<CompositionInstance[]>>; + /** + * Retrieve a single page of CompositionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CompositionPage) => any): Promise<CompositionPage>; + page(params: CompositionListInstancePageOptions, callback?: (error: Error | null, items: CompositionPage) => any): Promise<CompositionPage>; + /** + * Retrieve a single page of CompositionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CompositionPage>) => any): Promise<ApiResponse<CompositionPage>>; + pageWithHttpInfo(params: CompositionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CompositionPage>) => any): Promise<ApiResponse<CompositionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CompositionListInstance(version: V1): CompositionListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CompositionListInstance; + + instance.get = function get(sid, ): CompositionContext { + return new CompositionContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Compositions`; + + instance.create = function create(params: CompositionListInstanceCreateOptions, callback?: (error: Error | null, items: CompositionInstance) => any): Promise<CompositionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["roomSid"] === null || params["roomSid"] === undefined) { + throw new Error('Required parameter "params[\'roomSid\']" missing.'); + } + + let data: any = {}; + + + + data["RoomSid"] = params["roomSid"]; + if (params["videoLayout"] !== undefined) + data["VideoLayout"] = serialize.object(params["videoLayout"]); + if (params["audioSources"] !== undefined) + data["AudioSources"] = serialize.map(params["audioSources"], (e: string) => (e)); + if (params["audioSourcesExcluded"] !== undefined) + data["AudioSourcesExcluded"] = serialize.map(params["audioSourcesExcluded"], (e: string) => (e)); + if (params["resolution"] !== undefined) + data["Resolution"] = params["resolution"]; + if (params["format"] !== undefined) + data["Format"] = params["format"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["trim"] !== undefined) + data["Trim"] = serialize.bool(params["trim"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CompositionInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CompositionListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<CompositionInstance>) => any): Promise<ApiResponse<CompositionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["roomSid"] === null || params["roomSid"] === undefined) { + throw new Error('Required parameter "params[\'roomSid\']" missing.'); + } + + let data: any = {}; + + + + data["RoomSid"] = params["roomSid"]; + if (params["videoLayout"] !== undefined) + data["VideoLayout"] = serialize.object(params["videoLayout"]); + if (params["audioSources"] !== undefined) + data["AudioSources"] = serialize.map(params["audioSources"], (e: string) => (e)); + if (params["audioSourcesExcluded"] !== undefined) + data["AudioSourcesExcluded"] = serialize.map(params["audioSourcesExcluded"], (e: string) => (e)); + if (params["resolution"] !== undefined) + data["Resolution"] = params["resolution"]; + if (params["format"] !== undefined) + data["Format"] = params["format"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["trim"] !== undefined) + data["Trim"] = serialize.bool(params["trim"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CompositionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CompositionInstance> => ({ + ...response, + body: new CompositionInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CompositionListInstancePageOptions | ((error: Error | null, items: CompositionPage) => any), callback?: (error: Error | null, items: CompositionPage) => any): Promise<CompositionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["roomSid"] !== undefined) + data["RoomSid"] = params["roomSid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CompositionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CompositionPage) => any): Promise<CompositionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CompositionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CompositionListInstancePageOptions | ((error: Error | null, items: ApiResponse<CompositionPage>) => any), callback?: (error: Error | null, items: ApiResponse<CompositionPage>) => any): Promise<ApiResponse<CompositionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["roomSid"] !== undefined) + data["RoomSid"] = params["roomSid"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CompositionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CompositionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CompositionPage>) => any): Promise<ApiResponse<CompositionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CompositionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CompositionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CompositionPage extends Page<V1, CompositionPayload, CompositionResource, CompositionInstance> { +/** +* Initialize the CompositionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CompositionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CompositionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CompositionResource): CompositionInstance { + + return new CompositionInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/video/v1/compositionHook.ts b/rest/video/v1/compositionHook.ts new file mode 100644 index 000000000..aa0bdd58a --- /dev/null +++ b/rest/video/v1/compositionHook.ts @@ -0,0 +1,1072 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The container format of the media files used by the compositions created by the composition hook. If `mp4` or `webm`, `audio_sources` must have one or more tracks and/or a `video_layout` element must contain a valid `video_sources` list, otherwise an error occurs. + */ +export type CompositionHookFormat = 'mp4'|'webm'; + + + + +/** + * Options to pass to update a CompositionHookInstance + */ +export interface CompositionHookContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. */ + "friendlyName": string; + /** Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. */ + "enabled"?: boolean; + /** A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. */ + "videoLayout"?: any; + /** An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. */ + "audioSources"?: Array<string>; + /** An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. */ + "audioSourcesExcluded"?: Array<string>; + /** Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. */ + "trim"?: boolean; + /** */ + "format"?: CompositionHookFormat; + /** A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string\\\'s format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. */ + "resolution"?: string; + /** The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. */ + "statusCallbackMethod"?: string; +} + +/** + * Options to pass to create a CompositionHookInstance + */ +export interface CompositionHookListInstanceCreateOptions { + /** A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. */ + "friendlyName": string; + /** Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. */ + "enabled"?: boolean; + /** An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. */ + "videoLayout"?: any; + /** An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. */ + "audioSources"?: Array<string>; + /** An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. */ + "audioSourcesExcluded"?: Array<string>; + /** A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string\\\'s format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. */ + "resolution"?: string; + /** */ + "format"?: CompositionHookFormat; + /** The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. */ + "statusCallback"?: string; + /** The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. */ + "statusCallbackMethod"?: string; + /** Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. */ + "trim"?: boolean; +} + +/** + * Options to pass to each + */ +export interface CompositionHookListInstanceEachOptions { + /** Read only CompositionHook resources with an `enabled` value that matches this parameter. */ + "enabled"?: boolean; + /** Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedBefore"?: Date; + /** Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CompositionHookInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CompositionHookListInstanceOptions { + /** Read only CompositionHook resources with an `enabled` value that matches this parameter. */ + "enabled"?: boolean; + /** Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedBefore"?: Date; + /** Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CompositionHookListInstancePageOptions { + /** Read only CompositionHook resources with an `enabled` value that matches this parameter. */ + "enabled"?: boolean; + /** Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedBefore"?: Date; + /** Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. */ + "friendlyName"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CompositionHookContext { + + /** + * Remove a CompositionHookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a CompositionHookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a CompositionHookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionHookInstance + */ + fetch(callback?: (error: Error | null, item?: CompositionHookInstance) => any): Promise<CompositionHookInstance> + + /** + * Fetch a CompositionHookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionHookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CompositionHookInstance>) => any): Promise<ApiResponse<CompositionHookInstance>> + + /** + * Update a CompositionHookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionHookInstance + */ + update(params: CompositionHookContextUpdateOptions, callback?: (error: Error | null, item?: CompositionHookInstance) => any): Promise<CompositionHookInstance>; + + /** + * Update a CompositionHookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionHookInstance with HTTP metadata + */ + updateWithHttpInfo(params: CompositionHookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<CompositionHookInstance>) => any): Promise<ApiResponse<CompositionHookInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CompositionHookContextSolution { + "sid": string; +} + +export class CompositionHookContextImpl implements CompositionHookContext { + protected _solution: CompositionHookContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/CompositionHooks/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CompositionHookInstance) => any): Promise<CompositionHookInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CompositionHookInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CompositionHookInstance>) => any): Promise<ApiResponse<CompositionHookInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CompositionHookResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CompositionHookInstance> => ({ + ...response, + body: new CompositionHookInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: CompositionHookContextUpdateOptions,callback?: (error: Error | null, item?: CompositionHookInstance) => any): Promise<CompositionHookInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["videoLayout"] !== undefined) + data["VideoLayout"] = serialize.object(params["videoLayout"]); + if (params["audioSources"] !== undefined) + data["AudioSources"] = serialize.map(params["audioSources"], (e: string) => (e)); + if (params["audioSourcesExcluded"] !== undefined) + data["AudioSourcesExcluded"] = serialize.map(params["audioSourcesExcluded"], (e: string) => (e)); + if (params["trim"] !== undefined) + data["Trim"] = serialize.bool(params["trim"]); + if (params["format"] !== undefined) + data["Format"] = params["format"]; + if (params["resolution"] !== undefined) + data["Resolution"] = params["resolution"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CompositionHookInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: CompositionHookContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<CompositionHookInstance>) => any): Promise<ApiResponse<CompositionHookInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["videoLayout"] !== undefined) + data["VideoLayout"] = serialize.object(params["videoLayout"]); + if (params["audioSources"] !== undefined) + data["AudioSources"] = serialize.map(params["audioSources"], (e: string) => (e)); + if (params["audioSourcesExcluded"] !== undefined) + data["AudioSourcesExcluded"] = serialize.map(params["audioSourcesExcluded"], (e: string) => (e)); + if (params["trim"] !== undefined) + data["Trim"] = serialize.bool(params["trim"]); + if (params["format"] !== undefined) + data["Format"] = params["format"]; + if (params["resolution"] !== undefined) + data["Resolution"] = params["resolution"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<CompositionHookResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CompositionHookInstance> => ({ + ...response, + body: new CompositionHookInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CompositionHookPayload extends TwilioResponsePayload { + composition_hooks: CompositionHookResource[]; +} + +interface CompositionHookResource { + account_sid: string; + friendly_name: string; + enabled: boolean; + date_created: Date; + date_updated: Date; + sid: string; + audio_sources: Array<string>; + audio_sources_excluded: Array<string>; + video_layout: any; + resolution: string; + trim: boolean; + format: CompositionHookFormat; + status_callback: string; + status_callback_method: string; + url: string; +} + +export class CompositionHookInstance { + protected _solution: CompositionHookContextSolution; + protected _context?: CompositionHookContext; + + constructor(protected _version: V1, payload: CompositionHookResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.enabled = (payload.enabled); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.sid = (payload.sid); + this.audioSources = (payload.audio_sources); + this.audioSourcesExcluded = (payload.audio_sources_excluded); + this.videoLayout = (payload.video_layout); + this.resolution = (payload.resolution); + this.trim = (payload.trim); + this.format = payload.format; + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CompositionHook resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. Can be up to 100 characters long and must be unique within the account. + */ + friendlyName: string; + /** + * Whether the CompositionHook is active. When `true`, the CompositionHook is triggered for every completed Group Room on the account. When `false`, the CompositionHook is never triggered. + */ + enabled: boolean; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The unique string that we created to identify the CompositionHook resource. + */ + sid: string; + /** + * The array of track names to include in the compositions created by the composition hook. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + */ + audioSources: Array<string>; + /** + * The array of track names to exclude from the compositions created by the composition hook. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + */ + audioSourcesExcluded: Array<string>; + /** + * A JSON object that describes the video layout of the composition in terms of regions as specified in the HTTP POST request that created the CompositionHook resource. See [POST Parameters](https://www.twilio.com/docs/video/api/compositions-resource#http-post-parameters) for more information. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + */ + videoLayout: any; + /** + * The dimensions of the video image in pixels expressed as columns (width) and rows (height). The string\'s format is `{width}x{height}`, such as `640x480`. + */ + resolution: string; + /** + * Whether intervals with no media are clipped, as specified in the POST request that created the CompositionHook resource. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + */ + trim: boolean; + format: CompositionHookFormat; + /** + * The URL we call using the `status_callback_method` to send status information to your application. + */ + statusCallback: string; + /** + * The HTTP method we should use to call `status_callback`. Can be `POST` or `GET` and defaults to `POST`. + */ + statusCallbackMethod: string; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): CompositionHookContext { + this._context = this._context || new CompositionHookContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CompositionHookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CompositionHookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CompositionHookInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionHookInstance + */ + fetch(callback?: (error: Error | null, item?: CompositionHookInstance) => any): Promise<CompositionHookInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CompositionHookInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionHookInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CompositionHookInstance>) => any): Promise<ApiResponse<CompositionHookInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a CompositionHookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionHookInstance + */ + update(params: CompositionHookContextUpdateOptions, callback?: (error: Error | null, item?: CompositionHookInstance) => any): Promise<CompositionHookInstance>; + + update(params?: any, callback?: (error: Error | null, item?: CompositionHookInstance) => any): Promise<CompositionHookInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a CompositionHookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionHookInstance with HTTP metadata + */ + updateWithHttpInfo(params: CompositionHookContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<CompositionHookInstance>) => any): Promise<ApiResponse<CompositionHookInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<CompositionHookInstance>) => any): Promise<ApiResponse<CompositionHookInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + friendlyName: this.friendlyName, + enabled: this.enabled, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + sid: this.sid, + audioSources: this.audioSources, + audioSourcesExcluded: this.audioSourcesExcluded, + videoLayout: this.videoLayout, + resolution: this.resolution, + trim: this.trim, + format: this.format, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CompositionHookSolution { +} + +export interface CompositionHookListInstance { + _version: V1; + _solution: CompositionHookSolution; + _uri: string; + + (sid: string, ): CompositionHookContext; + get(sid: string, ): CompositionHookContext; + + + + + + + + + /** + * Create a CompositionHookInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionHookInstance + */ + create(params: CompositionHookListInstanceCreateOptions, callback?: (error: Error | null, item?: CompositionHookInstance) => any): Promise<CompositionHookInstance>; + + /** + * Create a CompositionHookInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionHookInstance with HTTP metadata + */ + createWithHttpInfo(params: CompositionHookListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CompositionHookInstance>) => any): Promise<ApiResponse<CompositionHookInstance>>; + + + + + /** + * Streams CompositionHookInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionHookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CompositionHookInstance, done: (err?: Error) => void) => void): void; + each(params: CompositionHookListInstanceEachOptions, callback?: (item: CompositionHookInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CompositionHookInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionHookListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CompositionHookInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CompositionHookListInstanceEachOptions, callback?: (item: CompositionHookInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CompositionHookInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CompositionHookPage) => any): Promise<CompositionHookPage>; + /** + * Retrieve a single target page of CompositionHookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CompositionHookPage>) => any): Promise<ApiResponse<CompositionHookPage>>; + /** + * Lists CompositionHookInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionHookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CompositionHookInstance[]) => any): Promise<CompositionHookInstance[]>; + list(params: CompositionHookListInstanceOptions, callback?: (error: Error | null, items: CompositionHookInstance[]) => any): Promise<CompositionHookInstance[]>; + /** + * Lists CompositionHookInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionHookListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CompositionHookInstance[]>) => any): Promise<ApiResponse<CompositionHookInstance[]>>; + listWithHttpInfo(params: CompositionHookListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CompositionHookInstance[]>) => any): Promise<ApiResponse<CompositionHookInstance[]>>; + /** + * Retrieve a single page of CompositionHookInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionHookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CompositionHookPage) => any): Promise<CompositionHookPage>; + page(params: CompositionHookListInstancePageOptions, callback?: (error: Error | null, items: CompositionHookPage) => any): Promise<CompositionHookPage>; + /** + * Retrieve a single page of CompositionHookInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CompositionHookListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CompositionHookPage>) => any): Promise<ApiResponse<CompositionHookPage>>; + pageWithHttpInfo(params: CompositionHookListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CompositionHookPage>) => any): Promise<ApiResponse<CompositionHookPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CompositionHookListInstance(version: V1): CompositionHookListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CompositionHookListInstance; + + instance.get = function get(sid, ): CompositionHookContext { + return new CompositionHookContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/CompositionHooks`; + + instance.create = function create(params: CompositionHookListInstanceCreateOptions, callback?: (error: Error | null, items: CompositionHookInstance) => any): Promise<CompositionHookInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["videoLayout"] !== undefined) + data["VideoLayout"] = serialize.object(params["videoLayout"]); + if (params["audioSources"] !== undefined) + data["AudioSources"] = serialize.map(params["audioSources"], (e: string) => (e)); + if (params["audioSourcesExcluded"] !== undefined) + data["AudioSourcesExcluded"] = serialize.map(params["audioSourcesExcluded"], (e: string) => (e)); + if (params["resolution"] !== undefined) + data["Resolution"] = params["resolution"]; + if (params["format"] !== undefined) + data["Format"] = params["format"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["trim"] !== undefined) + data["Trim"] = serialize.bool(params["trim"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CompositionHookInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CompositionHookListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<CompositionHookInstance>) => any): Promise<ApiResponse<CompositionHookInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["videoLayout"] !== undefined) + data["VideoLayout"] = serialize.object(params["videoLayout"]); + if (params["audioSources"] !== undefined) + data["AudioSources"] = serialize.map(params["audioSources"], (e: string) => (e)); + if (params["audioSourcesExcluded"] !== undefined) + data["AudioSourcesExcluded"] = serialize.map(params["audioSourcesExcluded"], (e: string) => (e)); + if (params["resolution"] !== undefined) + data["Resolution"] = params["resolution"]; + if (params["format"] !== undefined) + data["Format"] = params["format"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["trim"] !== undefined) + data["Trim"] = serialize.bool(params["trim"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CompositionHookResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CompositionHookInstance> => ({ + ...response, + body: new CompositionHookInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CompositionHookListInstancePageOptions | ((error: Error | null, items: CompositionHookPage) => any), callback?: (error: Error | null, items: CompositionHookPage) => any): Promise<CompositionHookPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CompositionHookPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CompositionHookPage) => any): Promise<CompositionHookPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CompositionHookPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CompositionHookListInstancePageOptions | ((error: Error | null, items: ApiResponse<CompositionHookPage>) => any), callback?: (error: Error | null, items: ApiResponse<CompositionHookPage>) => any): Promise<ApiResponse<CompositionHookPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CompositionHookPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CompositionHookPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CompositionHookPage>) => any): Promise<ApiResponse<CompositionHookPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CompositionHookPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CompositionHookPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CompositionHookPage extends Page<V1, CompositionHookPayload, CompositionHookResource, CompositionHookInstance> { +/** +* Initialize the CompositionHookPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CompositionHookSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CompositionHookInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CompositionHookResource): CompositionHookInstance { + + return new CompositionHookInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/video/v1/compositionSettings.ts b/rest/video/v1/compositionSettings.ts new file mode 100644 index 000000000..8b2ee3b8d --- /dev/null +++ b/rest/video/v1/compositionSettings.ts @@ -0,0 +1,439 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a CompositionSettingsInstance + */ +export interface CompositionSettingsContextCreateOptions { + /** A descriptive string that you create to describe the resource and show to the user in the console */ + "friendlyName": string; + /** The SID of the stored Credential resource. */ + "awsCredentialsSid"?: string; + /** The SID of the Public Key resource to use for encryption. */ + "encryptionKeySid"?: string; + /** The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). */ + "awsS3Url"?: string; + /** Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. */ + "awsStorageEnabled"?: boolean; + /** Whether all compositions should be stored in an encrypted form. The default is `false`. */ + "encryptionEnabled"?: boolean; +} + + +export interface CompositionSettingsContext { + + /** + * Create a CompositionSettingsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionSettingsInstance + */ + create(params: CompositionSettingsContextCreateOptions, callback?: (error: Error | null, item?: CompositionSettingsInstance) => any): Promise<CompositionSettingsInstance>; + + /** + * Create a CompositionSettingsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionSettingsInstance with HTTP metadata + */ + createWithHttpInfo(params: CompositionSettingsContextCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CompositionSettingsInstance>) => any): Promise<ApiResponse<CompositionSettingsInstance>>; + + /** + * Fetch a CompositionSettingsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionSettingsInstance + */ + fetch(callback?: (error: Error | null, item?: CompositionSettingsInstance) => any): Promise<CompositionSettingsInstance> + + /** + * Fetch a CompositionSettingsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionSettingsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CompositionSettingsInstance>) => any): Promise<ApiResponse<CompositionSettingsInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CompositionSettingsContextSolution { +} + +export class CompositionSettingsContextImpl implements CompositionSettingsContext { + protected _solution: CompositionSettingsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/CompositionSettings/Default`; + } + + create(params: CompositionSettingsContextCreateOptions,callback?: (error: Error | null, item?: CompositionSettingsInstance) => any): Promise<CompositionSettingsInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["awsCredentialsSid"] !== undefined) + data["AwsCredentialsSid"] = params["awsCredentialsSid"]; + if (params["encryptionKeySid"] !== undefined) + data["EncryptionKeySid"] = params["encryptionKeySid"]; + if (params["awsS3Url"] !== undefined) + data["AwsS3Url"] = params["awsS3Url"]; + if (params["awsStorageEnabled"] !== undefined) + data["AwsStorageEnabled"] = serialize.bool(params["awsStorageEnabled"]); + if (params["encryptionEnabled"] !== undefined) + data["EncryptionEnabled"] = serialize.bool(params["encryptionEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CompositionSettingsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params: CompositionSettingsContextCreateOptions,callback?: (error: Error | null, item?: ApiResponse<CompositionSettingsInstance>) => any): Promise<ApiResponse<CompositionSettingsInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["awsCredentialsSid"] !== undefined) + data["AwsCredentialsSid"] = params["awsCredentialsSid"]; + if (params["encryptionKeySid"] !== undefined) + data["EncryptionKeySid"] = params["encryptionKeySid"]; + if (params["awsS3Url"] !== undefined) + data["AwsS3Url"] = params["awsS3Url"]; + if (params["awsStorageEnabled"] !== undefined) + data["AwsStorageEnabled"] = serialize.bool(params["awsStorageEnabled"]); + if (params["encryptionEnabled"] !== undefined) + data["EncryptionEnabled"] = serialize.bool(params["encryptionEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CompositionSettingsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CompositionSettingsInstance> => ({ + ...response, + body: new CompositionSettingsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CompositionSettingsInstance) => any): Promise<CompositionSettingsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CompositionSettingsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CompositionSettingsInstance>) => any): Promise<ApiResponse<CompositionSettingsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CompositionSettingsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CompositionSettingsInstance> => ({ + ...response, + body: new CompositionSettingsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CompositionSettingsPayload extends CompositionSettingsResource {} + +interface CompositionSettingsResource { + account_sid: string; + friendly_name: string; + aws_credentials_sid: string; + aws_s3_url: string; + aws_storage_enabled: boolean; + encryption_key_sid: string; + encryption_enabled: boolean; + url: string; +} + +export class CompositionSettingsInstance { + protected _solution: CompositionSettingsContextSolution; + protected _context?: CompositionSettingsContext; + + constructor(protected _version: V1, payload: CompositionSettingsResource) { + + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.awsCredentialsSid = (payload.aws_credentials_sid); + this.awsS3Url = (payload.aws_s3_url); + this.awsStorageEnabled = (payload.aws_storage_enabled); + this.encryptionKeySid = (payload.encryption_key_sid); + this.encryptionEnabled = (payload.encryption_enabled); + this.url = (payload.url); + + this._solution = { }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CompositionSettings resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource and that will be shown in the console + */ + friendlyName: string; + /** + * The SID of the stored Credential resource. + */ + awsCredentialsSid: string; + /** + * The URL of the AWS S3 bucket where the compositions are stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + */ + awsS3Url: string; + /** + * Whether all compositions are written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + */ + awsStorageEnabled: boolean; + /** + * The SID of the Public Key resource used for encryption. + */ + encryptionKeySid: string; + /** + * Whether all compositions are stored in an encrypted form. The default is `false`. + */ + encryptionEnabled: boolean; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): CompositionSettingsContext { + this._context = this._context || new CompositionSettingsContextImpl(this._version); + return this._context; + } + + /** + * Create a CompositionSettingsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionSettingsInstance + */ + create(params: CompositionSettingsContextCreateOptions, callback?: (error: Error | null, item?: CompositionSettingsInstance) => any): Promise<CompositionSettingsInstance>; + + create(params?: any, callback?: (error: Error | null, item?: CompositionSettingsInstance) => any): Promise<CompositionSettingsInstance> + { + return this._proxy.create(params, callback); + } + + /** + * Create a CompositionSettingsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionSettingsInstance with HTTP metadata + */ + createWithHttpInfo(params: CompositionSettingsContextCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CompositionSettingsInstance>) => any): Promise<ApiResponse<CompositionSettingsInstance>>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<CompositionSettingsInstance>) => any): Promise<ApiResponse<CompositionSettingsInstance>> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Fetch a CompositionSettingsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionSettingsInstance + */ + fetch(callback?: (error: Error | null, item?: CompositionSettingsInstance) => any): Promise<CompositionSettingsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CompositionSettingsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CompositionSettingsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CompositionSettingsInstance>) => any): Promise<ApiResponse<CompositionSettingsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + friendlyName: this.friendlyName, + awsCredentialsSid: this.awsCredentialsSid, + awsS3Url: this.awsS3Url, + awsStorageEnabled: this.awsStorageEnabled, + encryptionKeySid: this.encryptionKeySid, + encryptionEnabled: this.encryptionEnabled, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CompositionSettingsSolution { +} + +export interface CompositionSettingsListInstance { + _version: V1; + _solution: CompositionSettingsSolution; + _uri: string; + + (): CompositionSettingsContext; + get(): CompositionSettingsContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CompositionSettingsListInstance(version: V1): CompositionSettingsListInstance { + const instance = (() => instance.get()) as CompositionSettingsListInstance; + + instance.get = function get(): CompositionSettingsContext { + return new CompositionSettingsContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/video/v1/recording.ts b/rest/video/v1/recording.ts new file mode 100644 index 000000000..2058cb76e --- /dev/null +++ b/rest/video/v1/recording.ts @@ -0,0 +1,778 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The codec used to encode the track. Can be: `VP8`, `H264`, `OPUS`, and `PCMU`. + */ +export type RecordingCodec = 'VP8'|'H264'|'OPUS'|'PCMU'; + +export type RecordingFormat = 'mka'|'mkv'; + +/** + * The status of the recording. Can be: `processing`, `completed`, or `deleted`. `processing` indicates the recording is still being captured; `completed` indicates the recording has been captured and is now available for download. `deleted` means the recording media has been deleted from the system, but its metadata is still available. + */ +export type RecordingStatus = 'processing'|'completed'|'deleted'|'failed'; + +/** + * The recording\'s media type. Can be: `audio` or `video`. + */ +export type RecordingType = 'audio'|'video'|'data'; + + + + +/** + * Options to pass to each + */ +export interface RecordingListInstanceEachOptions { + /** Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. */ + "status"?: RecordingStatus; + /** Read only the recordings that have this `source_sid`. */ + "sourceSid"?: string; + /** Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. */ + "groupingSid"?: Array<string>; + /** Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. */ + "dateCreatedBefore"?: Date; + /** Read only recordings that have this media type. Can be either `audio` or `video`. */ + "mediaType"?: RecordingType; + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RecordingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RecordingListInstanceOptions { + /** Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. */ + "status"?: RecordingStatus; + /** Read only the recordings that have this `source_sid`. */ + "sourceSid"?: string; + /** Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. */ + "groupingSid"?: Array<string>; + /** Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. */ + "dateCreatedBefore"?: Date; + /** Read only recordings that have this media type. Can be either `audio` or `video`. */ + "mediaType"?: RecordingType; + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RecordingListInstancePageOptions { + /** Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. */ + "status"?: RecordingStatus; + /** Read only the recordings that have this `source_sid`. */ + "sourceSid"?: string; + /** Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. */ + "groupingSid"?: Array<string>; + /** Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. */ + "dateCreatedBefore"?: Date; + /** Read only recordings that have this media type. Can be either `audio` or `video`. */ + "mediaType"?: RecordingType; + /** How many resources to return in each list page. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RecordingContext { + + /** + * Remove a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RecordingContextSolution { + "sid": string; +} + +export class RecordingContextImpl implements RecordingContext { + protected _solution: RecordingContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Recordings/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RecordingResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<RecordingInstance> => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RecordingPayload extends TwilioResponsePayload { + recordings: RecordingResource[]; +} + +interface RecordingResource { + account_sid: string; + status: RecordingStatus; + date_created: Date; + sid: string; + source_sid: string; + size: number; + url: string; + type: RecordingType; + duration: number; + container_format: RecordingFormat; + codec: RecordingCodec; + grouping_sids: any; + track_name: string; + offset: number; + media_external_location: string; + status_callback: string; + status_callback_method: string; + links: Record<string, string>; +} + +export class RecordingInstance { + protected _solution: RecordingContextSolution; + protected _context?: RecordingContext; + + constructor(protected _version: V1, payload: RecordingResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.status = payload.status; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.sid = (payload.sid); + this.sourceSid = (payload.source_sid); + this.size = (payload.size); + this.url = (payload.url); + this.type = payload.type; + this.duration = deserialize.integer(payload.duration); + this.containerFormat = payload.container_format; + this.codec = payload.codec; + this.groupingSids = (payload.grouping_sids); + this.trackName = (payload.track_name); + this.offset = (payload.offset); + this.mediaExternalLocation = (payload.media_external_location); + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource. + */ + accountSid: string; + status: RecordingStatus; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The unique string that we created to identify the Recording resource. + */ + sid: string; + /** + * The SID of the recording source. For a Room Recording, this value is a `track_sid`. + */ + sourceSid: string; + /** + * The size of the recorded track, in bytes. + */ + size: number; + /** + * The absolute URL of the resource. + */ + url: string; + type: RecordingType; + /** + * The duration of the recording in seconds rounded to the nearest second. Sub-second tracks have a `Duration` property of 1 second + */ + duration: number; + containerFormat: RecordingFormat; + codec: RecordingCodec; + /** + * A list of SIDs related to the recording. Includes the `room_sid` and `participant_sid`. + */ + groupingSids: any; + /** + * The name that was given to the source track of the recording. If no name is given, the `source_sid` is used. + */ + trackName: string; + /** + * The time in milliseconds elapsed between an arbitrary point in time, common to all group rooms, and the moment when the source room of this track started. This information provides a synchronization mechanism for recordings belonging to the same room. + */ + offset: number; + /** + * The URL of the media file associated with the recording when stored externally. See [External S3 Recordings](/docs/video/api/external-s3-recordings) for more details. + */ + mediaExternalLocation: string; + /** + * The URL called using the `status_callback_method` to send status information on every recording event. + */ + statusCallback: string; + /** + * The HTTP method used to call `status_callback`. Can be: `POST` or `GET`, defaults to `POST`. + */ + statusCallbackMethod: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): RecordingContext { + this._context = this._context || new RecordingContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + status: this.status, + dateCreated: this.dateCreated, + sid: this.sid, + sourceSid: this.sourceSid, + size: this.size, + url: this.url, + type: this.type, + duration: this.duration, + containerFormat: this.containerFormat, + codec: this.codec, + groupingSids: this.groupingSids, + trackName: this.trackName, + offset: this.offset, + mediaExternalLocation: this.mediaExternalLocation, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RecordingSolution { +} + +export interface RecordingListInstance { + _version: V1; + _solution: RecordingSolution; + _uri: string; + + (sid: string, ): RecordingContext; + get(sid: string, ): RecordingContext; + + + + + + + + /** + * Streams RecordingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + each(params: RecordingListInstanceEachOptions, callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RecordingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RecordingListInstanceEachOptions, callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RecordingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RecordingPage) => any): Promise<RecordingPage>; + /** + * Retrieve a single target page of RecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RecordingPage>) => any): Promise<ApiResponse<RecordingPage>>; + /** + * Lists RecordingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RecordingInstance[]) => any): Promise<RecordingInstance[]>; + list(params: RecordingListInstanceOptions, callback?: (error: Error | null, items: RecordingInstance[]) => any): Promise<RecordingInstance[]>; + /** + * Lists RecordingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RecordingInstance[]>) => any): Promise<ApiResponse<RecordingInstance[]>>; + listWithHttpInfo(params: RecordingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RecordingInstance[]>) => any): Promise<ApiResponse<RecordingInstance[]>>; + /** + * Retrieve a single page of RecordingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RecordingPage) => any): Promise<RecordingPage>; + page(params: RecordingListInstancePageOptions, callback?: (error: Error | null, items: RecordingPage) => any): Promise<RecordingPage>; + /** + * Retrieve a single page of RecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RecordingPage>) => any): Promise<ApiResponse<RecordingPage>>; + pageWithHttpInfo(params: RecordingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RecordingPage>) => any): Promise<ApiResponse<RecordingPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RecordingListInstance(version: V1): RecordingListInstance { + const instance = ((sid, ) => instance.get(sid, )) as RecordingListInstance; + + instance.get = function get(sid, ): RecordingContext { + return new RecordingContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Recordings`; + + instance.page = function page(params?: RecordingListInstancePageOptions | ((error: Error | null, items: RecordingPage) => any), callback?: (error: Error | null, items: RecordingPage) => any): Promise<RecordingPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["sourceSid"] !== undefined) + data["SourceSid"] = params["sourceSid"]; + if (params["groupingSid"] !== undefined) + data["GroupingSid"] = serialize.map(params["groupingSid"], (e: string) => (e)); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["mediaType"] !== undefined) + data["MediaType"] = params["mediaType"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RecordingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RecordingPage) => any): Promise<RecordingPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RecordingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RecordingListInstancePageOptions | ((error: Error | null, items: ApiResponse<RecordingPage>) => any), callback?: (error: Error | null, items: ApiResponse<RecordingPage>) => any): Promise<ApiResponse<RecordingPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["sourceSid"] !== undefined) + data["SourceSid"] = params["sourceSid"]; + if (params["groupingSid"] !== undefined) + data["GroupingSid"] = serialize.map(params["groupingSid"], (e: string) => (e)); + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["mediaType"] !== undefined) + data["MediaType"] = params["mediaType"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RecordingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RecordingPage>) => any): Promise<ApiResponse<RecordingPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RecordingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RecordingPage extends Page<V1, RecordingPayload, RecordingResource, RecordingInstance> { +/** +* Initialize the RecordingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: RecordingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RecordingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RecordingResource): RecordingInstance { + + return new RecordingInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/video/v1/recordingSettings.ts b/rest/video/v1/recordingSettings.ts new file mode 100644 index 000000000..f18c953ae --- /dev/null +++ b/rest/video/v1/recordingSettings.ts @@ -0,0 +1,439 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a RecordingSettingsInstance + */ +export interface RecordingSettingsContextCreateOptions { + /** A descriptive string that you create to describe the resource and be shown to users in the console */ + "friendlyName": string; + /** The SID of the stored Credential resource. */ + "awsCredentialsSid"?: string; + /** The SID of the Public Key resource to use for encryption. */ + "encryptionKeySid"?: string; + /** The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). */ + "awsS3Url"?: string; + /** Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. */ + "awsStorageEnabled"?: boolean; + /** Whether all recordings should be stored in an encrypted form. The default is `false`. */ + "encryptionEnabled"?: boolean; +} + + +export interface RecordingSettingsContext { + + /** + * Create a RecordingSettingsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingSettingsInstance + */ + create(params: RecordingSettingsContextCreateOptions, callback?: (error: Error | null, item?: RecordingSettingsInstance) => any): Promise<RecordingSettingsInstance>; + + /** + * Create a RecordingSettingsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingSettingsInstance with HTTP metadata + */ + createWithHttpInfo(params: RecordingSettingsContextCreateOptions, callback?: (error: Error | null, item?: ApiResponse<RecordingSettingsInstance>) => any): Promise<ApiResponse<RecordingSettingsInstance>>; + + /** + * Fetch a RecordingSettingsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingSettingsInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingSettingsInstance) => any): Promise<RecordingSettingsInstance> + + /** + * Fetch a RecordingSettingsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingSettingsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingSettingsInstance>) => any): Promise<ApiResponse<RecordingSettingsInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RecordingSettingsContextSolution { +} + +export class RecordingSettingsContextImpl implements RecordingSettingsContext { + protected _solution: RecordingSettingsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/RecordingSettings/Default`; + } + + create(params: RecordingSettingsContextCreateOptions,callback?: (error: Error | null, item?: RecordingSettingsInstance) => any): Promise<RecordingSettingsInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["awsCredentialsSid"] !== undefined) + data["AwsCredentialsSid"] = params["awsCredentialsSid"]; + if (params["encryptionKeySid"] !== undefined) + data["EncryptionKeySid"] = params["encryptionKeySid"]; + if (params["awsS3Url"] !== undefined) + data["AwsS3Url"] = params["awsS3Url"]; + if (params["awsStorageEnabled"] !== undefined) + data["AwsStorageEnabled"] = serialize.bool(params["awsStorageEnabled"]); + if (params["encryptionEnabled"] !== undefined) + data["EncryptionEnabled"] = serialize.bool(params["encryptionEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RecordingSettingsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params: RecordingSettingsContextCreateOptions,callback?: (error: Error | null, item?: ApiResponse<RecordingSettingsInstance>) => any): Promise<ApiResponse<RecordingSettingsInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["friendlyName"] === null || params["friendlyName"] === undefined) { + throw new Error('Required parameter "params[\'friendlyName\']" missing.'); + } + + let data: any = {}; + + + + data["FriendlyName"] = params["friendlyName"]; + if (params["awsCredentialsSid"] !== undefined) + data["AwsCredentialsSid"] = params["awsCredentialsSid"]; + if (params["encryptionKeySid"] !== undefined) + data["EncryptionKeySid"] = params["encryptionKeySid"]; + if (params["awsS3Url"] !== undefined) + data["AwsS3Url"] = params["awsS3Url"]; + if (params["awsStorageEnabled"] !== undefined) + data["AwsStorageEnabled"] = serialize.bool(params["awsStorageEnabled"]); + if (params["encryptionEnabled"] !== undefined) + data["EncryptionEnabled"] = serialize.bool(params["encryptionEnabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<RecordingSettingsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RecordingSettingsInstance> => ({ + ...response, + body: new RecordingSettingsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RecordingSettingsInstance) => any): Promise<RecordingSettingsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RecordingSettingsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingSettingsInstance>) => any): Promise<ApiResponse<RecordingSettingsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RecordingSettingsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<RecordingSettingsInstance> => ({ + ...response, + body: new RecordingSettingsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RecordingSettingsPayload extends RecordingSettingsResource {} + +interface RecordingSettingsResource { + account_sid: string; + friendly_name: string; + aws_credentials_sid: string; + aws_s3_url: string; + aws_storage_enabled: boolean; + encryption_key_sid: string; + encryption_enabled: boolean; + url: string; +} + +export class RecordingSettingsInstance { + protected _solution: RecordingSettingsContextSolution; + protected _context?: RecordingSettingsContext; + + constructor(protected _version: V1, payload: RecordingSettingsResource) { + + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.awsCredentialsSid = (payload.aws_credentials_sid); + this.awsS3Url = (payload.aws_s3_url); + this.awsStorageEnabled = (payload.aws_storage_enabled); + this.encryptionKeySid = (payload.encryption_key_sid); + this.encryptionEnabled = (payload.encryption_enabled); + this.url = (payload.url); + + this._solution = { }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RecordingSettings resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource and show the user in the console + */ + friendlyName: string; + /** + * The SID of the stored Credential resource. + */ + awsCredentialsSid: string; + /** + * The URL of the AWS S3 bucket where the recordings are stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + */ + awsS3Url: string; + /** + * Whether all recordings are written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + */ + awsStorageEnabled: boolean; + /** + * The SID of the Public Key resource used for encryption. + */ + encryptionKeySid: string; + /** + * Whether all recordings are stored in an encrypted form. The default is `false`. + */ + encryptionEnabled: boolean; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): RecordingSettingsContext { + this._context = this._context || new RecordingSettingsContextImpl(this._version); + return this._context; + } + + /** + * Create a RecordingSettingsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingSettingsInstance + */ + create(params: RecordingSettingsContextCreateOptions, callback?: (error: Error | null, item?: RecordingSettingsInstance) => any): Promise<RecordingSettingsInstance>; + + create(params?: any, callback?: (error: Error | null, item?: RecordingSettingsInstance) => any): Promise<RecordingSettingsInstance> + { + return this._proxy.create(params, callback); + } + + /** + * Create a RecordingSettingsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingSettingsInstance with HTTP metadata + */ + createWithHttpInfo(params: RecordingSettingsContextCreateOptions, callback?: (error: Error | null, item?: ApiResponse<RecordingSettingsInstance>) => any): Promise<ApiResponse<RecordingSettingsInstance>>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<RecordingSettingsInstance>) => any): Promise<ApiResponse<RecordingSettingsInstance>> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Fetch a RecordingSettingsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingSettingsInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingSettingsInstance) => any): Promise<RecordingSettingsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RecordingSettingsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingSettingsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingSettingsInstance>) => any): Promise<ApiResponse<RecordingSettingsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + friendlyName: this.friendlyName, + awsCredentialsSid: this.awsCredentialsSid, + awsS3Url: this.awsS3Url, + awsStorageEnabled: this.awsStorageEnabled, + encryptionKeySid: this.encryptionKeySid, + encryptionEnabled: this.encryptionEnabled, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RecordingSettingsSolution { +} + +export interface RecordingSettingsListInstance { + _version: V1; + _solution: RecordingSettingsSolution; + _uri: string; + + (): RecordingSettingsContext; + get(): RecordingSettingsContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RecordingSettingsListInstance(version: V1): RecordingSettingsListInstance { + const instance = (() => instance.get()) as RecordingSettingsListInstance; + + instance.get = function get(): RecordingSettingsContext { + return new RecordingSettingsContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/video/v1/room.ts b/rest/video/v1/room.ts new file mode 100644 index 000000000..e22d951c0 --- /dev/null +++ b/rest/video/v1/room.ts @@ -0,0 +1,1120 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ParticipantListInstance } from "./room/participant"; +import { RecordingRulesListInstance } from "./room/recordingRules"; +import { RoomRecordingListInstance } from "./room/roomRecording"; +import { TranscriptionsListInstance } from "./room/transcriptions"; + + +export type RoomRoomStatus = 'in-progress'|'completed'|'failed'; + +/** + * Type of room. Use `group` for new implementations. `go`, `peer-to-peer`, and `group-small` are deprecated. + */ +export type RoomRoomType = 'group'|'go'|'peer-to-peer'|'group-small'; + +export type RoomVideoCodec = 'VP8'|'H264'; + + + +/** + * Options to pass to update a RoomInstance + */ +export interface RoomContextUpdateOptions { + /** */ + "status": RoomRoomStatus; +} + +/** + * Options to pass to create a RoomInstance + */ +export interface RoomListInstanceCreateOptions { + /** Deprecated, now always considered to be true. */ + "enableTurn"?: boolean; + /** */ + "type"?: RoomRoomType; + /** An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource\\\'s `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. */ + "uniqueName"?: string; + /** The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. */ + "statusCallback"?: string; + /** The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. */ + "statusCallbackMethod"?: string; + /** The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. */ + "maxParticipants"?: number; + /** Whether to start recording when Participants connect. */ + "recordParticipantsOnConnect"?: boolean; + /** Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. */ + "transcribeParticipantsOnConnect"?: boolean; + /** An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. */ + "videoCodecs"?: Array<RoomVideoCodec>; + /** The region for the Room\\\'s media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). */ + "mediaRegion"?: string; + /** A collection of Recording Rules that describe how to include or exclude matching tracks for recording */ + "recordingRules"?: any; + /** A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. */ + "transcriptionsConfiguration"?: object; + /** When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. */ + "audioOnly"?: boolean; + /** The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). */ + "maxParticipantDuration"?: number; + /** Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). */ + "emptyRoomTimeout"?: number; + /** Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). */ + "unusedRoomTimeout"?: number; + /** When set to true, indicated that this is the large room. */ + "largeRoom"?: boolean; +} + +/** + * Options to pass to each + */ +export interface RoomListInstanceEachOptions { + /** Read only the rooms with this status. Can be: `in-progress` (default) or `completed` */ + "status"?: RoomRoomStatus; + /** Read only rooms with the this `unique_name`. */ + "uniqueName"?: string; + /** Read only rooms that started on or after this date, given as `YYYY-MM-DD`. */ + "dateCreatedAfter"?: Date; + /** Read only rooms that started before this date, given as `YYYY-MM-DD`. */ + "dateCreatedBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoomInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoomListInstanceOptions { + /** Read only the rooms with this status. Can be: `in-progress` (default) or `completed` */ + "status"?: RoomRoomStatus; + /** Read only rooms with the this `unique_name`. */ + "uniqueName"?: string; + /** Read only rooms that started on or after this date, given as `YYYY-MM-DD`. */ + "dateCreatedAfter"?: Date; + /** Read only rooms that started before this date, given as `YYYY-MM-DD`. */ + "dateCreatedBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoomListInstancePageOptions { + /** Read only the rooms with this status. Can be: `in-progress` (default) or `completed` */ + "status"?: RoomRoomStatus; + /** Read only rooms with the this `unique_name`. */ + "uniqueName"?: string; + /** Read only rooms that started on or after this date, given as `YYYY-MM-DD`. */ + "dateCreatedAfter"?: Date; + /** Read only rooms that started before this date, given as `YYYY-MM-DD`. */ + "dateCreatedBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoomContext { + participants: ParticipantListInstance; + recordingRules: RecordingRulesListInstance; + recordings: RoomRecordingListInstance; + transcriptions: TranscriptionsListInstance; + + /** + * Fetch a RoomInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance + */ + fetch(callback?: (error: Error | null, item?: RoomInstance) => any): Promise<RoomInstance> + + /** + * Fetch a RoomInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RoomInstance>) => any): Promise<ApiResponse<RoomInstance>> + + /** + * Update a RoomInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance + */ + update(params: RoomContextUpdateOptions, callback?: (error: Error | null, item?: RoomInstance) => any): Promise<RoomInstance>; + + /** + * Update a RoomInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoomContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RoomInstance>) => any): Promise<ApiResponse<RoomInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoomContextSolution { + "sid": string; +} + +export class RoomContextImpl implements RoomContext { + protected _solution: RoomContextSolution; + protected _uri: string; + + protected _participants?: ParticipantListInstance; + protected _recordingRules?: RecordingRulesListInstance; + protected _recordings?: RoomRecordingListInstance; + protected _transcriptions?: TranscriptionsListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Rooms/${sid}`; + } + + get participants(): ParticipantListInstance { + this._participants = this._participants || ParticipantListInstance(this._version, this._solution.sid); + return this._participants; + } + + get recordingRules(): RecordingRulesListInstance { + this._recordingRules = this._recordingRules || RecordingRulesListInstance(this._version, this._solution.sid); + return this._recordingRules; + } + + get recordings(): RoomRecordingListInstance { + this._recordings = this._recordings || RoomRecordingListInstance(this._version, this._solution.sid); + return this._recordings; + } + + get transcriptions(): TranscriptionsListInstance { + this._transcriptions = this._transcriptions || TranscriptionsListInstance(this._version, this._solution.sid); + return this._transcriptions; + } + + fetch(callback?: (error: Error | null, item?: RoomInstance) => any): Promise<RoomInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RoomInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RoomInstance>) => any): Promise<ApiResponse<RoomInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RoomResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<RoomInstance> => ({ + ...response, + body: new RoomInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: RoomContextUpdateOptions,callback?: (error: Error | null, item?: RoomInstance) => any): Promise<RoomInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoomInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: RoomContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<RoomInstance>) => any): Promise<ApiResponse<RoomInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["status"] === null || params["status"] === undefined) { + throw new Error('Required parameter "params[\'status\']" missing.'); + } + + let data: any = {}; + + + + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<RoomResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RoomInstance> => ({ + ...response, + body: new RoomInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RoomPayload extends TwilioResponsePayload { + rooms: RoomResource[]; +} + +interface RoomResource { + sid: string; + status: RoomRoomStatus; + date_created: Date; + date_updated: Date; + account_sid: string; + enable_turn: boolean; + unique_name: string; + status_callback: string; + status_callback_method: string; + end_time: Date; + duration: number; + type: RoomRoomType; + max_participants: number; + max_participant_duration: number; + max_concurrent_published_tracks: number; + record_participants_on_connect: boolean; + video_codecs: Array<RoomVideoCodec>; + media_region: string; + audio_only: boolean; + empty_room_timeout: number; + unused_room_timeout: number; + large_room: boolean; + url: string; + links: Record<string, string>; +} + +export class RoomInstance { + protected _solution: RoomContextSolution; + protected _context?: RoomContext; + + constructor(protected _version: V1, payload: RoomResource, sid?: string) { + + this.sid = (payload.sid); + this.status = payload.status; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.accountSid = (payload.account_sid); + this.enableTurn = (payload.enable_turn); + this.uniqueName = (payload.unique_name); + this.statusCallback = (payload.status_callback); + this.statusCallbackMethod = (payload.status_callback_method); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.duration = deserialize.integer(payload.duration); + this.type = payload.type; + this.maxParticipants = deserialize.integer(payload.max_participants); + this.maxParticipantDuration = deserialize.integer(payload.max_participant_duration); + this.maxConcurrentPublishedTracks = deserialize.integer(payload.max_concurrent_published_tracks); + this.recordParticipantsOnConnect = (payload.record_participants_on_connect); + this.videoCodecs = (payload.video_codecs); + this.mediaRegion = (payload.media_region); + this.audioOnly = (payload.audio_only); + this.emptyRoomTimeout = deserialize.integer(payload.empty_room_timeout); + this.unusedRoomTimeout = deserialize.integer(payload.unused_room_timeout); + this.largeRoom = (payload.large_room); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that Twilio created to identify the Room resource. + */ + sid: string; + status: RoomRoomStatus; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Room resource. + */ + accountSid: string; + /** + * Deprecated, now always considered to be true. + */ + enableTurn: boolean; + /** + * An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource\'s `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + */ + uniqueName: string; + /** + * The URL Twilio calls using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + */ + statusCallback: string; + /** + * The HTTP method Twilio uses to call `status_callback`. Can be `POST` or `GET` and defaults to `POST`. + */ + statusCallbackMethod: string; + /** + * The UTC end time of the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + */ + endTime: Date; + /** + * The duration of the room in seconds. + */ + duration: number; + type: RoomRoomType; + /** + * The maximum number of concurrent Participants allowed in the room. + */ + maxParticipants: number; + /** + * The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + */ + maxParticipantDuration: number; + /** + * The maximum number of published audio, video, and data tracks all participants combined are allowed to publish in the room at the same time. Check [Programmable Video Limits](https://www.twilio.com/docs/video/programmable-video-limits) for more details. If it is set to 0 it means unconstrained. + */ + maxConcurrentPublishedTracks: number; + /** + * Whether to start recording when Participants connect. + */ + recordParticipantsOnConnect: boolean; + /** + * An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + */ + videoCodecs: Array<RoomVideoCodec>; + /** + * The region for the Room\'s media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#media-servers). + */ + mediaRegion: string; + /** + * When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + */ + audioOnly: boolean; + /** + * Specifies how long (in minutes) a room will remain active after last participant leaves. Can be configured when creating a room via REST API. For Ad-Hoc rooms this value cannot be changed. + */ + emptyRoomTimeout: number; + /** + * Specifies how long (in minutes) a room will remain active if no one joins. Can be configured when creating a room via REST API. For Ad-Hoc rooms this value cannot be changed. + */ + unusedRoomTimeout: number; + /** + * Indicates if this is a large room. + */ + largeRoom: boolean; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): RoomContext { + this._context = this._context || new RoomContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Fetch a RoomInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance + */ + fetch(callback?: (error: Error | null, item?: RoomInstance) => any): Promise<RoomInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RoomInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RoomInstance>) => any): Promise<ApiResponse<RoomInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RoomInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance + */ + update(params: RoomContextUpdateOptions, callback?: (error: Error | null, item?: RoomInstance) => any): Promise<RoomInstance>; + + update(params?: any, callback?: (error: Error | null, item?: RoomInstance) => any): Promise<RoomInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a RoomInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance with HTTP metadata + */ + updateWithHttpInfo(params: RoomContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RoomInstance>) => any): Promise<ApiResponse<RoomInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<RoomInstance>) => any): Promise<ApiResponse<RoomInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the participants. + */ + participants(): ParticipantListInstance { + return this._proxy.participants; + } + + /** + * Access the recordingRules. + */ + recordingRules(): RecordingRulesListInstance { + return this._proxy.recordingRules; + } + + /** + * Access the recordings. + */ + recordings(): RoomRecordingListInstance { + return this._proxy.recordings; + } + + /** + * Access the transcriptions. + */ + transcriptions(): TranscriptionsListInstance { + return this._proxy.transcriptions; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + status: this.status, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + accountSid: this.accountSid, + enableTurn: this.enableTurn, + uniqueName: this.uniqueName, + statusCallback: this.statusCallback, + statusCallbackMethod: this.statusCallbackMethod, + endTime: this.endTime, + duration: this.duration, + type: this.type, + maxParticipants: this.maxParticipants, + maxParticipantDuration: this.maxParticipantDuration, + maxConcurrentPublishedTracks: this.maxConcurrentPublishedTracks, + recordParticipantsOnConnect: this.recordParticipantsOnConnect, + videoCodecs: this.videoCodecs, + mediaRegion: this.mediaRegion, + audioOnly: this.audioOnly, + emptyRoomTimeout: this.emptyRoomTimeout, + unusedRoomTimeout: this.unusedRoomTimeout, + largeRoom: this.largeRoom, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoomSolution { +} + +export interface RoomListInstance { + _version: V1; + _solution: RoomSolution; + _uri: string; + + (sid: string, ): RoomContext; + get(sid: string, ): RoomContext; + + + + + + + /** + * Create a RoomInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance + */ + create(callback?: (error: Error | null, item?: RoomInstance) => any): Promise<RoomInstance>; + /** + * Create a RoomInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance + */ + create(params: RoomListInstanceCreateOptions, callback?: (error: Error | null, item?: RoomInstance) => any): Promise<RoomInstance>; + + /** + * Create a RoomInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RoomInstance>) => any): Promise<ApiResponse<RoomInstance>>; + /** + * Create a RoomInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomInstance with HTTP metadata + */ + createWithHttpInfo(params: RoomListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<RoomInstance>) => any): Promise<ApiResponse<RoomInstance>>; + + + + + /** + * Streams RoomInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoomInstance, done: (err?: Error) => void) => void): void; + each(params: RoomListInstanceEachOptions, callback?: (item: RoomInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoomInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoomInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoomListInstanceEachOptions, callback?: (item: RoomInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoomInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RoomPage) => any): Promise<RoomPage>; + /** + * Retrieve a single target page of RoomInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RoomPage>) => any): Promise<ApiResponse<RoomPage>>; + /** + * Lists RoomInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoomInstance[]) => any): Promise<RoomInstance[]>; + list(params: RoomListInstanceOptions, callback?: (error: Error | null, items: RoomInstance[]) => any): Promise<RoomInstance[]>; + /** + * Lists RoomInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RoomInstance[]>) => any): Promise<ApiResponse<RoomInstance[]>>; + listWithHttpInfo(params: RoomListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RoomInstance[]>) => any): Promise<ApiResponse<RoomInstance[]>>; + /** + * Retrieve a single page of RoomInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RoomPage) => any): Promise<RoomPage>; + page(params: RoomListInstancePageOptions, callback?: (error: Error | null, items: RoomPage) => any): Promise<RoomPage>; + /** + * Retrieve a single page of RoomInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RoomPage>) => any): Promise<ApiResponse<RoomPage>>; + pageWithHttpInfo(params: RoomListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RoomPage>) => any): Promise<ApiResponse<RoomPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoomListInstance(version: V1): RoomListInstance { + const instance = ((sid, ) => instance.get(sid, )) as RoomListInstance; + + instance.get = function get(sid, ): RoomContext { + return new RoomContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Rooms`; + + instance.create = function create(params?: RoomListInstanceCreateOptions | ((error: Error | null, items: RoomInstance) => any), callback?: (error: Error | null, items: RoomInstance) => any): Promise<RoomInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["enableTurn"] !== undefined) + data["EnableTurn"] = serialize.bool(params["enableTurn"]); + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["maxParticipants"] !== undefined) + data["MaxParticipants"] = params["maxParticipants"]; + if (params["recordParticipantsOnConnect"] !== undefined) + data["RecordParticipantsOnConnect"] = serialize.bool(params["recordParticipantsOnConnect"]); + if (params["transcribeParticipantsOnConnect"] !== undefined) + data["TranscribeParticipantsOnConnect"] = serialize.bool(params["transcribeParticipantsOnConnect"]); + if (params["videoCodecs"] !== undefined) + data["VideoCodecs"] = serialize.map(params["videoCodecs"], (e: RoomVideoCodec) => (e)); + if (params["mediaRegion"] !== undefined) + data["MediaRegion"] = params["mediaRegion"]; + if (params["recordingRules"] !== undefined) + data["RecordingRules"] = serialize.object(params["recordingRules"]); + if (params["transcriptionsConfiguration"] !== undefined) + data["TranscriptionsConfiguration"] = serialize.object(params["transcriptionsConfiguration"]); + if (params["audioOnly"] !== undefined) + data["AudioOnly"] = serialize.bool(params["audioOnly"]); + if (params["maxParticipantDuration"] !== undefined) + data["MaxParticipantDuration"] = params["maxParticipantDuration"]; + if (params["emptyRoomTimeout"] !== undefined) + data["EmptyRoomTimeout"] = params["emptyRoomTimeout"]; + if (params["unusedRoomTimeout"] !== undefined) + data["UnusedRoomTimeout"] = params["unusedRoomTimeout"]; + if (params["largeRoom"] !== undefined) + data["LargeRoom"] = serialize.bool(params["largeRoom"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RoomInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: RoomListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<RoomInstance>) => any), callback?: (error: Error | null, items: ApiResponse<RoomInstance>) => any): Promise<ApiResponse<RoomInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["enableTurn"] !== undefined) + data["EnableTurn"] = serialize.bool(params["enableTurn"]); + if (params["type"] !== undefined) + data["Type"] = params["type"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["statusCallback"] !== undefined) + data["StatusCallback"] = params["statusCallback"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["maxParticipants"] !== undefined) + data["MaxParticipants"] = params["maxParticipants"]; + if (params["recordParticipantsOnConnect"] !== undefined) + data["RecordParticipantsOnConnect"] = serialize.bool(params["recordParticipantsOnConnect"]); + if (params["transcribeParticipantsOnConnect"] !== undefined) + data["TranscribeParticipantsOnConnect"] = serialize.bool(params["transcribeParticipantsOnConnect"]); + if (params["videoCodecs"] !== undefined) + data["VideoCodecs"] = serialize.map(params["videoCodecs"], (e: RoomVideoCodec) => (e)); + if (params["mediaRegion"] !== undefined) + data["MediaRegion"] = params["mediaRegion"]; + if (params["recordingRules"] !== undefined) + data["RecordingRules"] = serialize.object(params["recordingRules"]); + if (params["transcriptionsConfiguration"] !== undefined) + data["TranscriptionsConfiguration"] = serialize.object(params["transcriptionsConfiguration"]); + if (params["audioOnly"] !== undefined) + data["AudioOnly"] = serialize.bool(params["audioOnly"]); + if (params["maxParticipantDuration"] !== undefined) + data["MaxParticipantDuration"] = params["maxParticipantDuration"]; + if (params["emptyRoomTimeout"] !== undefined) + data["EmptyRoomTimeout"] = params["emptyRoomTimeout"]; + if (params["unusedRoomTimeout"] !== undefined) + data["UnusedRoomTimeout"] = params["unusedRoomTimeout"]; + if (params["largeRoom"] !== undefined) + data["LargeRoom"] = serialize.bool(params["largeRoom"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<RoomResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RoomInstance> => ({ + ...response, + body: new RoomInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RoomListInstancePageOptions | ((error: Error | null, items: RoomPage) => any), callback?: (error: Error | null, items: RoomPage) => any): Promise<RoomPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RoomPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RoomPage) => any): Promise<RoomPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RoomPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoomListInstancePageOptions | ((error: Error | null, items: ApiResponse<RoomPage>) => any), callback?: (error: Error | null, items: ApiResponse<RoomPage>) => any): Promise<ApiResponse<RoomPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RoomPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RoomPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RoomPage>) => any): Promise<ApiResponse<RoomPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RoomPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RoomPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RoomPage extends Page<V1, RoomPayload, RoomResource, RoomInstance> { +/** +* Initialize the RoomPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: RoomSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoomInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoomResource): RoomInstance { + + return new RoomInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/video/v1/room/participant.ts b/rest/video/v1/room/participant.ts new file mode 100644 index 000000000..5ee762f34 --- /dev/null +++ b/rest/video/v1/room/participant.ts @@ -0,0 +1,867 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; +import { AnonymizeListInstance } from "./participant/anonymize"; +import { PublishedTrackListInstance } from "./participant/publishedTrack"; +import { SubscribeRulesListInstance } from "./participant/subscribeRules"; +import { SubscribedTrackListInstance } from "./participant/subscribedTrack"; + + +/** + * The status of the Participant. Can be: `connected` or `disconnected`. + */ +export type ParticipantStatus = 'connected'|'disconnected'|'reconnecting'; + + + +/** + * Options to pass to update a ParticipantInstance + */ +export interface ParticipantContextUpdateOptions { + /** */ + "status"?: ParticipantStatus; +} + +/** + * Options to pass to each + */ +export interface ParticipantListInstanceEachOptions { + /** Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. */ + "status"?: ParticipantStatus; + /** Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. */ + "identity"?: string; + /** Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. */ + "dateCreatedAfter"?: Date; + /** Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. */ + "dateCreatedBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ParticipantListInstanceOptions { + /** Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. */ + "status"?: ParticipantStatus; + /** Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. */ + "identity"?: string; + /** Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. */ + "dateCreatedAfter"?: Date; + /** Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. */ + "dateCreatedBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ParticipantListInstancePageOptions { + /** Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. */ + "status"?: ParticipantStatus; + /** Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. */ + "identity"?: string; + /** Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. */ + "dateCreatedAfter"?: Date; + /** Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. */ + "dateCreatedBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ParticipantContext { + anonymize: AnonymizeListInstance; + publishedTracks: PublishedTrackListInstance; + subscribeRules: SubscribeRulesListInstance; + subscribedTracks: SubscribedTrackListInstance; + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance> + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>> + + /** + * Update a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance>; + /** + * Update a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance>; + + /** + * Update a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>>; + /** + * Update a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ParticipantContextSolution { + "roomSid": string; + "sid": string; +} + +export class ParticipantContextImpl implements ParticipantContext { + protected _solution: ParticipantContextSolution; + protected _uri: string; + + protected _anonymize?: AnonymizeListInstance; + protected _publishedTracks?: PublishedTrackListInstance; + protected _subscribeRules?: SubscribeRulesListInstance; + protected _subscribedTracks?: SubscribedTrackListInstance; + + constructor(protected _version: V1, roomSid: string, sid: string) { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { roomSid, sid, }; + this._uri = `/Rooms/${roomSid}/Participants/${sid}`; + } + + get anonymize(): AnonymizeListInstance { + this._anonymize = this._anonymize || AnonymizeListInstance(this._version, this._solution.roomSid, this._solution.sid); + return this._anonymize; + } + + get publishedTracks(): PublishedTrackListInstance { + this._publishedTracks = this._publishedTracks || PublishedTrackListInstance(this._version, this._solution.roomSid, this._solution.sid); + return this._publishedTracks; + } + + get subscribeRules(): SubscribeRulesListInstance { + this._subscribeRules = this._subscribeRules || SubscribeRulesListInstance(this._version, this._solution.roomSid, this._solution.sid); + return this._subscribeRules; + } + + get subscribedTracks(): SubscribedTrackListInstance { + this._subscribedTracks = this._subscribedTracks || SubscribedTrackListInstance(this._version, this._solution.roomSid, this._solution.sid); + return this._subscribedTracks; + } + + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ParticipantResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ParticipantInstance> => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ParticipantContextUpdateOptions | ((error: Error | null, item?: ParticipantInstance) => any),callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ParticipantInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ParticipantContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ParticipantInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ParticipantResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ParticipantInstance> => ({ + ...response, + body: new ParticipantInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ParticipantPayload extends TwilioResponsePayload { + participants: ParticipantResource[]; +} + +interface ParticipantResource { + sid: string; + room_sid: string; + account_sid: string; + status: ParticipantStatus; + identity: string; + date_created: Date; + date_updated: Date; + start_time: Date; + end_time: Date; + duration: number; + url: string; + links: Record<string, string>; +} + +export class ParticipantInstance { + protected _solution: ParticipantContextSolution; + protected _context?: ParticipantContext; + + constructor(protected _version: V1, payload: ParticipantResource, roomSid: string, sid?: string) { + + this.sid = (payload.sid); + this.roomSid = (payload.room_sid); + this.accountSid = (payload.account_sid); + this.status = payload.status; + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.duration = deserialize.integer(payload.duration); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { roomSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the RoomParticipant resource. + */ + sid: string; + /** + * The SID of the participant\'s room. + */ + roomSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RoomParticipant resource. + */ + accountSid: string; + status: ParticipantStatus; + /** + * The application-defined string that uniquely identifies the resource\'s User within a Room. If a client joins with an existing Identity, the existing client is disconnected. See [access tokens](https://www.twilio.com/docs/video/tutorials/user-identity-access-tokens) and [limits](https://www.twilio.com/docs/video/programmable-video-limits) for more info. + */ + identity: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The time of participant connected to the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + */ + startTime: Date; + /** + * The time when the participant disconnected from the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + */ + endTime: Date; + /** + * The duration in seconds that the participant was `connected`. Populated only after the participant is `disconnected`. + */ + duration: number; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): ParticipantContext { + this._context = this._context || new ParticipantContextImpl(this._version, this._solution.roomSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + fetch(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ParticipantInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance>; + /** + * Update a ParticipantInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance + */ + update(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ParticipantInstance) => any): Promise<ParticipantInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ParticipantInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>>; + /** + * Update a ParticipantInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ParticipantInstance with HTTP metadata + */ + updateWithHttpInfo(params: ParticipantContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ParticipantInstance>) => any): Promise<ApiResponse<ParticipantInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the anonymize. + */ + anonymize(): AnonymizeListInstance { + return this._proxy.anonymize; + } + + /** + * Access the publishedTracks. + */ + publishedTracks(): PublishedTrackListInstance { + return this._proxy.publishedTracks; + } + + /** + * Access the subscribeRules. + */ + subscribeRules(): SubscribeRulesListInstance { + return this._proxy.subscribeRules; + } + + /** + * Access the subscribedTracks. + */ + subscribedTracks(): SubscribedTrackListInstance { + return this._proxy.subscribedTracks; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + roomSid: this.roomSid, + accountSid: this.accountSid, + status: this.status, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + startTime: this.startTime, + endTime: this.endTime, + duration: this.duration, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ParticipantSolution { + roomSid: string; +} + +export interface ParticipantListInstance { + _version: V1; + _solution: ParticipantSolution; + _uri: string; + + (sid: string, ): ParticipantContext; + get(sid: string, ): ParticipantContext; + + + + + + + + /** + * Streams ParticipantInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + each(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ParticipantInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ParticipantListInstanceEachOptions, callback?: (item: ParticipantInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise<ParticipantPage>; + /** + * Retrieve a single target page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ParticipantPage>) => any): Promise<ApiResponse<ParticipantPage>>; + /** + * Lists ParticipantInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise<ParticipantInstance[]>; + list(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ParticipantInstance[]) => any): Promise<ParticipantInstance[]>; + /** + * Lists ParticipantInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ParticipantInstance[]>) => any): Promise<ApiResponse<ParticipantInstance[]>>; + listWithHttpInfo(params: ParticipantListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ParticipantInstance[]>) => any): Promise<ApiResponse<ParticipantInstance[]>>; + /** + * Retrieve a single page of ParticipantInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ParticipantPage) => any): Promise<ParticipantPage>; + page(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ParticipantPage) => any): Promise<ParticipantPage>; + /** + * Retrieve a single page of ParticipantInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ParticipantListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ParticipantPage>) => any): Promise<ApiResponse<ParticipantPage>>; + pageWithHttpInfo(params: ParticipantListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ParticipantPage>) => any): Promise<ApiResponse<ParticipantPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ParticipantListInstance(version: V1, roomSid: string): ParticipantListInstance { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ParticipantListInstance; + + instance.get = function get(sid, ): ParticipantContext { + return new ParticipantContextImpl(version, roomSid, sid); + } + + instance._version = version; + instance._solution = { roomSid, }; + instance._uri = `/Rooms/${roomSid}/Participants`; + + instance.page = function page(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ParticipantPage) => any), callback?: (error: Error | null, items: ParticipantPage) => any): Promise<ParticipantPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ParticipantPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ParticipantPage) => any): Promise<ParticipantPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ParticipantPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ParticipantListInstancePageOptions | ((error: Error | null, items: ApiResponse<ParticipantPage>) => any), callback?: (error: Error | null, items: ApiResponse<ParticipantPage>) => any): Promise<ApiResponse<ParticipantPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["identity"] !== undefined) + data["Identity"] = params["identity"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ParticipantPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ParticipantPage>) => any): Promise<ApiResponse<ParticipantPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ParticipantPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ParticipantPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ParticipantPage extends Page<V1, ParticipantPayload, ParticipantResource, ParticipantInstance> { +/** +* Initialize the ParticipantPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ParticipantSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ParticipantInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ParticipantResource): ParticipantInstance { + + return new ParticipantInstance( + this._version, + payload, + this._solution.roomSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/video/v1/room/participant/anonymize.ts b/rest/video/v1/room/participant/anonymize.ts new file mode 100644 index 000000000..0aa8743ff --- /dev/null +++ b/rest/video/v1/room/participant/anonymize.ts @@ -0,0 +1,321 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The status of the Participant. Can be: `connected` or `disconnected`. + */ +export type AnonymizeStatus = 'connected'|'disconnected'; + + + +export interface AnonymizeContext { + + /** + * Update a AnonymizeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnonymizeInstance + */ + update(callback?: (error: Error | null, item?: AnonymizeInstance) => any): Promise<AnonymizeInstance> + + /** + * Update a AnonymizeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnonymizeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AnonymizeInstance>) => any): Promise<ApiResponse<AnonymizeInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AnonymizeContextSolution { + "roomSid": string; + "sid": string; +} + +export class AnonymizeContextImpl implements AnonymizeContext { + protected _solution: AnonymizeContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, roomSid: string, sid: string) { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { roomSid, sid, }; + this._uri = `/Rooms/${roomSid}/Participants/${sid}/Anonymize`; + } + + update(callback?: (error: Error | null, item?: AnonymizeInstance) => any): Promise<AnonymizeInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", headers}); + + operationPromise = operationPromise.then(payload => new AnonymizeInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AnonymizeInstance>) => any): Promise<ApiResponse<AnonymizeInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<AnonymizeResource>({ uri: instance._uri, method: "post", headers}).then((response) : ApiResponse<AnonymizeInstance> => ({ + ...response, + body: new AnonymizeInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AnonymizePayload extends AnonymizeResource {} + +interface AnonymizeResource { + sid: string; + room_sid: string; + account_sid: string; + status: AnonymizeStatus; + identity: string; + date_created: Date; + date_updated: Date; + start_time: Date; + end_time: Date; + duration: number; + url: string; +} + +export class AnonymizeInstance { + protected _solution: AnonymizeContextSolution; + protected _context?: AnonymizeContext; + + constructor(protected _version: V1, payload: AnonymizeResource, roomSid: string, sid: string) { + + this.sid = (payload.sid); + this.roomSid = (payload.room_sid); + this.accountSid = (payload.account_sid); + this.status = payload.status; + this.identity = (payload.identity); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.duration = deserialize.integer(payload.duration); + this.url = (payload.url); + + this._solution = { roomSid, sid, }; + } + + /** + * The unique string that we created to identify the RoomParticipant resource. + */ + sid: string; + /** + * The SID of the participant\'s room. + */ + roomSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RoomParticipant resource. + */ + accountSid: string; + status: AnonymizeStatus; + /** + * The SID of the participant. + */ + identity: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The time of participant connected to the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + */ + startTime: Date; + /** + * The time when the participant disconnected from the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + */ + endTime: Date; + /** + * The duration in seconds that the participant was `connected`. Populated only after the participant is `disconnected`. + */ + duration: number; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): AnonymizeContext { + this._context = this._context || new AnonymizeContextImpl(this._version, this._solution.roomSid, this._solution.sid); + return this._context; + } + + /** + * Update a AnonymizeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnonymizeInstance + */ + update(callback?: (error: Error | null, item?: AnonymizeInstance) => any): Promise<AnonymizeInstance> + + { + return this._proxy.update(callback); + } + + /** + * Update a AnonymizeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AnonymizeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AnonymizeInstance>) => any): Promise<ApiResponse<AnonymizeInstance>> + + { + return this._proxy.updateWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + roomSid: this.roomSid, + accountSid: this.accountSid, + status: this.status, + identity: this.identity, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + startTime: this.startTime, + endTime: this.endTime, + duration: this.duration, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AnonymizeSolution { + roomSid: string; + sid: string; +} + +export interface AnonymizeListInstance { + _version: V1; + _solution: AnonymizeSolution; + _uri: string; + + (): AnonymizeContext; + get(): AnonymizeContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AnonymizeListInstance(version: V1, roomSid: string, sid: string): AnonymizeListInstance { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + const instance = (() => instance.get()) as AnonymizeListInstance; + + instance.get = function get(): AnonymizeContext { + return new AnonymizeContextImpl(version, roomSid, sid); + } + + instance._version = version; + instance._solution = { roomSid, sid, }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/video/v1/room/participant/publishedTrack.ts b/rest/video/v1/room/participant/publishedTrack.ts new file mode 100644 index 000000000..996dc54dd --- /dev/null +++ b/rest/video/v1/room/participant/publishedTrack.ts @@ -0,0 +1,596 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The track type. Can be: `audio`, `video` or `data`. + */ +export type PublishedTrackKind = 'audio'|'video'|'data'; + + + +/** + * Options to pass to each + */ +export interface PublishedTrackListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: PublishedTrackInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface PublishedTrackListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface PublishedTrackListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface PublishedTrackContext { + + /** + * Fetch a PublishedTrackInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublishedTrackInstance + */ + fetch(callback?: (error: Error | null, item?: PublishedTrackInstance) => any): Promise<PublishedTrackInstance> + + /** + * Fetch a PublishedTrackInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublishedTrackInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PublishedTrackInstance>) => any): Promise<ApiResponse<PublishedTrackInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface PublishedTrackContextSolution { + "roomSid": string; + "participantSid": string; + "sid": string; +} + +export class PublishedTrackContextImpl implements PublishedTrackContext { + protected _solution: PublishedTrackContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, roomSid: string, participantSid: string, sid: string) { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(participantSid)) { + throw new Error('Parameter \'participantSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { roomSid, participantSid, sid, }; + this._uri = `/Rooms/${roomSid}/Participants/${participantSid}/PublishedTracks/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: PublishedTrackInstance) => any): Promise<PublishedTrackInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new PublishedTrackInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.participantSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PublishedTrackInstance>) => any): Promise<ApiResponse<PublishedTrackInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<PublishedTrackResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<PublishedTrackInstance> => ({ + ...response, + body: new PublishedTrackInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.participantSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface PublishedTrackPayload extends TwilioResponsePayload { + published_tracks: PublishedTrackResource[]; +} + +interface PublishedTrackResource { + sid: string; + participant_sid: string; + room_sid: string; + name: string; + date_created: Date; + date_updated: Date; + enabled: boolean; + kind: PublishedTrackKind; + url: string; +} + +export class PublishedTrackInstance { + protected _solution: PublishedTrackContextSolution; + protected _context?: PublishedTrackContext; + + constructor(protected _version: V1, payload: PublishedTrackResource, roomSid: string, participantSid: string, sid?: string) { + + this.sid = (payload.sid); + this.participantSid = (payload.participant_sid); + this.roomSid = (payload.room_sid); + this.name = (payload.name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.enabled = (payload.enabled); + this.kind = payload.kind; + this.url = (payload.url); + + this._solution = { roomSid, participantSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the RoomParticipantPublishedTrack resource. + */ + sid: string; + /** + * The SID of the Participant resource with the published track. + */ + participantSid: string; + /** + * The SID of the Room resource where the track is published. + */ + roomSid: string; + /** + * The track name. Must be no more than 128 characters, and be unique among the participant\'s published tracks. + */ + name: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * Whether the track is enabled. + */ + enabled: boolean; + kind: PublishedTrackKind; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): PublishedTrackContext { + this._context = this._context || new PublishedTrackContextImpl(this._version, this._solution.roomSid, this._solution.participantSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a PublishedTrackInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublishedTrackInstance + */ + fetch(callback?: (error: Error | null, item?: PublishedTrackInstance) => any): Promise<PublishedTrackInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a PublishedTrackInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed PublishedTrackInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<PublishedTrackInstance>) => any): Promise<ApiResponse<PublishedTrackInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + participantSid: this.participantSid, + roomSid: this.roomSid, + name: this.name, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + enabled: this.enabled, + kind: this.kind, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface PublishedTrackSolution { + roomSid: string; + participantSid: string; +} + +export interface PublishedTrackListInstance { + _version: V1; + _solution: PublishedTrackSolution; + _uri: string; + + (sid: string, ): PublishedTrackContext; + get(sid: string, ): PublishedTrackContext; + + + + + + /** + * Streams PublishedTrackInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublishedTrackListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: PublishedTrackInstance, done: (err?: Error) => void) => void): void; + each(params: PublishedTrackListInstanceEachOptions, callback?: (item: PublishedTrackInstance, done: (err?: Error) => void) => void): void; + /** + * Streams PublishedTrackInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublishedTrackListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: PublishedTrackInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: PublishedTrackListInstanceEachOptions, callback?: (item: PublishedTrackInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of PublishedTrackInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: PublishedTrackPage) => any): Promise<PublishedTrackPage>; + /** + * Retrieve a single target page of PublishedTrackInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<PublishedTrackPage>) => any): Promise<ApiResponse<PublishedTrackPage>>; + /** + * Lists PublishedTrackInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublishedTrackListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: PublishedTrackInstance[]) => any): Promise<PublishedTrackInstance[]>; + list(params: PublishedTrackListInstanceOptions, callback?: (error: Error | null, items: PublishedTrackInstance[]) => any): Promise<PublishedTrackInstance[]>; + /** + * Lists PublishedTrackInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublishedTrackListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PublishedTrackInstance[]>) => any): Promise<ApiResponse<PublishedTrackInstance[]>>; + listWithHttpInfo(params: PublishedTrackListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<PublishedTrackInstance[]>) => any): Promise<ApiResponse<PublishedTrackInstance[]>>; + /** + * Retrieve a single page of PublishedTrackInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublishedTrackListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: PublishedTrackPage) => any): Promise<PublishedTrackPage>; + page(params: PublishedTrackListInstancePageOptions, callback?: (error: Error | null, items: PublishedTrackPage) => any): Promise<PublishedTrackPage>; + /** + * Retrieve a single page of PublishedTrackInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { PublishedTrackListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<PublishedTrackPage>) => any): Promise<ApiResponse<PublishedTrackPage>>; + pageWithHttpInfo(params: PublishedTrackListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<PublishedTrackPage>) => any): Promise<ApiResponse<PublishedTrackPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function PublishedTrackListInstance(version: V1, roomSid: string, participantSid: string): PublishedTrackListInstance { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(participantSid)) { + throw new Error('Parameter \'participantSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as PublishedTrackListInstance; + + instance.get = function get(sid, ): PublishedTrackContext { + return new PublishedTrackContextImpl(version, roomSid, participantSid, sid); + } + + instance._version = version; + instance._solution = { roomSid, participantSid, }; + instance._uri = `/Rooms/${roomSid}/Participants/${participantSid}/PublishedTracks`; + + instance.page = function page(params?: PublishedTrackListInstancePageOptions | ((error: Error | null, items: PublishedTrackPage) => any), callback?: (error: Error | null, items: PublishedTrackPage) => any): Promise<PublishedTrackPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new PublishedTrackPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: PublishedTrackPage) => any): Promise<PublishedTrackPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new PublishedTrackPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: PublishedTrackListInstancePageOptions | ((error: Error | null, items: ApiResponse<PublishedTrackPage>) => any), callback?: (error: Error | null, items: ApiResponse<PublishedTrackPage>) => any): Promise<ApiResponse<PublishedTrackPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<PublishedTrackPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PublishedTrackPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<PublishedTrackPage>) => any): Promise<ApiResponse<PublishedTrackPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<PublishedTrackPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new PublishedTrackPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class PublishedTrackPage extends Page<V1, PublishedTrackPayload, PublishedTrackResource, PublishedTrackInstance> { +/** +* Initialize the PublishedTrackPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: PublishedTrackSolution) { + super(version, response, solution); + } + + /** + * Build an instance of PublishedTrackInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: PublishedTrackResource): PublishedTrackInstance { + + return new PublishedTrackInstance( + this._version, + payload, + this._solution.roomSid, + this._solution.participantSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/video/v1/room/participant/subscribeRules.ts b/rest/video/v1/room/participant/subscribeRules.ts new file mode 100644 index 000000000..dae7c53d2 --- /dev/null +++ b/rest/video/v1/room/participant/subscribeRules.ts @@ -0,0 +1,322 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +export class VideoV1RoomRoomParticipantRoomParticipantSubscribeRuleRules { + "type"?: string; + "all"?: boolean; + "publisher"?: string; + "track"?: string; + "kind"?: string; + "priority"?: string; + + constructor(payload) { + this.type = payload["type"]; + this.all = payload["all"]; + this.publisher = payload["publisher"]; + this.track = payload["track"]; + this.kind = payload["kind"]; + this.priority = payload["priority"]; + } +} + + + + +/** + * Options to pass to update a SubscribeRulesInstance + */ +export interface SubscribeRulesListInstanceUpdateOptions { + /** A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. */ + "rules"?: any; +} + + +export interface SubscribeRulesSolution { + roomSid: string; + participantSid: string; +} + +export interface SubscribeRulesListInstance { + _version: V1; + _solution: SubscribeRulesSolution; + _uri: string; + + + + /** + * Fetch a SubscribeRulesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribeRulesInstance + */ + fetch(callback?: (error: Error | null, item?: SubscribeRulesInstance) => any): Promise<SubscribeRulesInstance> + + /** + * Fetch a SubscribeRulesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribeRulesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SubscribeRulesInstance>) => any): Promise<ApiResponse<SubscribeRulesInstance>> + + + + /** + * Update a SubscribeRulesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribeRulesInstance + */ + update(callback?: (error: Error | null, item?: SubscribeRulesInstance) => any): Promise<SubscribeRulesInstance>; + /** + * Update a SubscribeRulesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribeRulesInstance + */ + update(params: SubscribeRulesListInstanceUpdateOptions, callback?: (error: Error | null, item?: SubscribeRulesInstance) => any): Promise<SubscribeRulesInstance>; + + /** + * Update a SubscribeRulesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribeRulesInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SubscribeRulesInstance>) => any): Promise<ApiResponse<SubscribeRulesInstance>>; + /** + * Update a SubscribeRulesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribeRulesInstance with HTTP metadata + */ + updateWithHttpInfo(params: SubscribeRulesListInstanceUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SubscribeRulesInstance>) => any): Promise<ApiResponse<SubscribeRulesInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SubscribeRulesListInstance(version: V1, roomSid: string, participantSid: string): SubscribeRulesListInstance { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(participantSid)) { + throw new Error('Parameter \'participantSid\' is not valid.'); + } + + const instance = {} as SubscribeRulesListInstance; + + instance._version = version; + instance._solution = { roomSid, participantSid, }; + instance._uri = `/Rooms/${roomSid}/Participants/${participantSid}/SubscribeRules`; + + instance.fetch = function fetch( callback?: (error: Error | null, items: SubscribeRulesInstance) => any): Promise<SubscribeRulesInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SubscribeRulesInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.participantSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<SubscribeRulesInstance>) => any): Promise<ApiResponse<SubscribeRulesInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SubscribeRulesResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SubscribeRulesInstance> => ({ + ...response, + body: new SubscribeRulesInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.participantSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.update = function update(params?: SubscribeRulesListInstanceUpdateOptions | ((error: Error | null, items: SubscribeRulesInstance) => any), callback?: (error: Error | null, items: SubscribeRulesInstance) => any): Promise<SubscribeRulesInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["rules"] !== undefined) + data["Rules"] = serialize.object(params["rules"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SubscribeRulesInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.participantSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.updateWithHttpInfo = function updateWithHttpInfo(params?: SubscribeRulesListInstanceUpdateOptions | ((error: Error | null, items: ApiResponse<SubscribeRulesInstance>) => any), callback?: (error: Error | null, items: ApiResponse<SubscribeRulesInstance>) => any): Promise<ApiResponse<SubscribeRulesInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["rules"] !== undefined) + data["Rules"] = serialize.object(params["rules"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SubscribeRulesResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SubscribeRulesInstance> => ({ + ...response, + body: new SubscribeRulesInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.participantSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface SubscribeRulesPayload extends SubscribeRulesResource {} + +interface SubscribeRulesResource { + participant_sid: string; + room_sid: string; + rules: Array<VideoV1RoomRoomParticipantRoomParticipantSubscribeRuleRules>; + date_created: Date; + date_updated: Date; +} + +export class SubscribeRulesInstance { + + constructor(protected _version: V1, payload: SubscribeRulesResource, roomSid: string, participantSid: string) { + + this.participantSid = (payload.participant_sid); + this.roomSid = (payload.room_sid); + this.rules = payload.rules !== null && payload.rules !== undefined ? payload.rules.map( + (payload: any) => new VideoV1RoomRoomParticipantRoomParticipantSubscribeRuleRules(payload) + ) : null; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The SID of the Participant resource for the Subscribe Rules. + */ + participantSid: string; + /** + * The SID of the Room resource for the Subscribe Rules + */ + roomSid: string; + /** + * A collection of Subscribe Rules that describe how to include or exclude matching tracks. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. + */ + rules: Array<VideoV1RoomRoomParticipantRoomParticipantSubscribeRuleRules>; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + participantSid: this.participantSid, + roomSid: this.roomSid, + rules: this.rules, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/video/v1/room/participant/subscribedTrack.ts b/rest/video/v1/room/participant/subscribedTrack.ts new file mode 100644 index 000000000..162fbcb33 --- /dev/null +++ b/rest/video/v1/room/participant/subscribedTrack.ts @@ -0,0 +1,603 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../../base/Page"; +import Response from "../../../../../http/response"; +import V1 from "../../../V1"; +const deserialize = require("../../../../../base/deserialize"); +const serialize = require("../../../../../base/serialize"); +import { isValidPathParam } from "../../../../../base/utility"; +import { ApiResponse } from "../../../../../base/ApiResponse"; + + +/** + * The track type. Can be: `audio`, `video` or `data`. + */ +export type SubscribedTrackKind = 'audio'|'video'|'data'; + + + +/** + * Options to pass to each + */ +export interface SubscribedTrackListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SubscribedTrackInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SubscribedTrackListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SubscribedTrackListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SubscribedTrackContext { + + /** + * Fetch a SubscribedTrackInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedTrackInstance + */ + fetch(callback?: (error: Error | null, item?: SubscribedTrackInstance) => any): Promise<SubscribedTrackInstance> + + /** + * Fetch a SubscribedTrackInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedTrackInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SubscribedTrackInstance>) => any): Promise<ApiResponse<SubscribedTrackInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SubscribedTrackContextSolution { + "roomSid": string; + "participantSid": string; + "sid": string; +} + +export class SubscribedTrackContextImpl implements SubscribedTrackContext { + protected _solution: SubscribedTrackContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, roomSid: string, participantSid: string, sid: string) { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(participantSid)) { + throw new Error('Parameter \'participantSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { roomSid, participantSid, sid, }; + this._uri = `/Rooms/${roomSid}/Participants/${participantSid}/SubscribedTracks/${sid}`; + } + + fetch(callback?: (error: Error | null, item?: SubscribedTrackInstance) => any): Promise<SubscribedTrackInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SubscribedTrackInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.participantSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SubscribedTrackInstance>) => any): Promise<ApiResponse<SubscribedTrackInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SubscribedTrackResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SubscribedTrackInstance> => ({ + ...response, + body: new SubscribedTrackInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.participantSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SubscribedTrackPayload extends TwilioResponsePayload { + subscribed_tracks: SubscribedTrackResource[]; +} + +interface SubscribedTrackResource { + sid: string; + participant_sid: string; + publisher_sid: string; + room_sid: string; + name: string; + date_created: Date; + date_updated: Date; + enabled: boolean; + kind: SubscribedTrackKind; + url: string; +} + +export class SubscribedTrackInstance { + protected _solution: SubscribedTrackContextSolution; + protected _context?: SubscribedTrackContext; + + constructor(protected _version: V1, payload: SubscribedTrackResource, roomSid: string, participantSid: string, sid?: string) { + + this.sid = (payload.sid); + this.participantSid = (payload.participant_sid); + this.publisherSid = (payload.publisher_sid); + this.roomSid = (payload.room_sid); + this.name = (payload.name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.enabled = (payload.enabled); + this.kind = payload.kind; + this.url = (payload.url); + + this._solution = { roomSid, participantSid, sid: sid, }; + } + + /** + * The unique string that we created to identify the RoomParticipantSubscribedTrack resource. + */ + sid: string; + /** + * The SID of the participant that subscribes to the track. + */ + participantSid: string; + /** + * The SID of the participant that publishes the track. + */ + publisherSid: string; + /** + * The SID of the room where the track is published. + */ + roomSid: string; + /** + * The track name. Must have no more than 128 characters and be unique among the participant\'s published tracks. + */ + name: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * Whether the track is enabled. + */ + enabled: boolean; + kind: SubscribedTrackKind; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): SubscribedTrackContext { + this._context = this._context || new SubscribedTrackContextImpl(this._version, this._solution.roomSid, this._solution.participantSid, this._solution.sid); + return this._context; + } + + /** + * Fetch a SubscribedTrackInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedTrackInstance + */ + fetch(callback?: (error: Error | null, item?: SubscribedTrackInstance) => any): Promise<SubscribedTrackInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SubscribedTrackInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SubscribedTrackInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SubscribedTrackInstance>) => any): Promise<ApiResponse<SubscribedTrackInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + participantSid: this.participantSid, + publisherSid: this.publisherSid, + roomSid: this.roomSid, + name: this.name, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + enabled: this.enabled, + kind: this.kind, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SubscribedTrackSolution { + roomSid: string; + participantSid: string; +} + +export interface SubscribedTrackListInstance { + _version: V1; + _solution: SubscribedTrackSolution; + _uri: string; + + (sid: string, ): SubscribedTrackContext; + get(sid: string, ): SubscribedTrackContext; + + + + + + /** + * Streams SubscribedTrackInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedTrackListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SubscribedTrackInstance, done: (err?: Error) => void) => void): void; + each(params: SubscribedTrackListInstanceEachOptions, callback?: (item: SubscribedTrackInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SubscribedTrackInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedTrackListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SubscribedTrackInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SubscribedTrackListInstanceEachOptions, callback?: (item: SubscribedTrackInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SubscribedTrackInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SubscribedTrackPage) => any): Promise<SubscribedTrackPage>; + /** + * Retrieve a single target page of SubscribedTrackInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SubscribedTrackPage>) => any): Promise<ApiResponse<SubscribedTrackPage>>; + /** + * Lists SubscribedTrackInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedTrackListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SubscribedTrackInstance[]) => any): Promise<SubscribedTrackInstance[]>; + list(params: SubscribedTrackListInstanceOptions, callback?: (error: Error | null, items: SubscribedTrackInstance[]) => any): Promise<SubscribedTrackInstance[]>; + /** + * Lists SubscribedTrackInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedTrackListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SubscribedTrackInstance[]>) => any): Promise<ApiResponse<SubscribedTrackInstance[]>>; + listWithHttpInfo(params: SubscribedTrackListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SubscribedTrackInstance[]>) => any): Promise<ApiResponse<SubscribedTrackInstance[]>>; + /** + * Retrieve a single page of SubscribedTrackInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedTrackListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SubscribedTrackPage) => any): Promise<SubscribedTrackPage>; + page(params: SubscribedTrackListInstancePageOptions, callback?: (error: Error | null, items: SubscribedTrackPage) => any): Promise<SubscribedTrackPage>; + /** + * Retrieve a single page of SubscribedTrackInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SubscribedTrackListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SubscribedTrackPage>) => any): Promise<ApiResponse<SubscribedTrackPage>>; + pageWithHttpInfo(params: SubscribedTrackListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SubscribedTrackPage>) => any): Promise<ApiResponse<SubscribedTrackPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SubscribedTrackListInstance(version: V1, roomSid: string, participantSid: string): SubscribedTrackListInstance { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(participantSid)) { + throw new Error('Parameter \'participantSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as SubscribedTrackListInstance; + + instance.get = function get(sid, ): SubscribedTrackContext { + return new SubscribedTrackContextImpl(version, roomSid, participantSid, sid); + } + + instance._version = version; + instance._solution = { roomSid, participantSid, }; + instance._uri = `/Rooms/${roomSid}/Participants/${participantSid}/SubscribedTracks`; + + instance.page = function page(params?: SubscribedTrackListInstancePageOptions | ((error: Error | null, items: SubscribedTrackPage) => any), callback?: (error: Error | null, items: SubscribedTrackPage) => any): Promise<SubscribedTrackPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SubscribedTrackPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SubscribedTrackPage) => any): Promise<SubscribedTrackPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SubscribedTrackPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SubscribedTrackListInstancePageOptions | ((error: Error | null, items: ApiResponse<SubscribedTrackPage>) => any), callback?: (error: Error | null, items: ApiResponse<SubscribedTrackPage>) => any): Promise<ApiResponse<SubscribedTrackPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SubscribedTrackPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SubscribedTrackPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SubscribedTrackPage>) => any): Promise<ApiResponse<SubscribedTrackPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SubscribedTrackPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SubscribedTrackPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SubscribedTrackPage extends Page<V1, SubscribedTrackPayload, SubscribedTrackResource, SubscribedTrackInstance> { +/** +* Initialize the SubscribedTrackPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SubscribedTrackSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SubscribedTrackInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SubscribedTrackResource): SubscribedTrackInstance { + + return new SubscribedTrackInstance( + this._version, + payload, + this._solution.roomSid, + this._solution.participantSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/video/v1/room/recordingRules.ts b/rest/video/v1/room/recordingRules.ts new file mode 100644 index 000000000..ec3be2b3c --- /dev/null +++ b/rest/video/v1/room/recordingRules.ts @@ -0,0 +1,308 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +export class VideoV1RoomRoomRecordingRuleRules { + "type"?: string; + "all"?: boolean; + "publisher"?: string; + "track"?: string; + "kind"?: string; + + constructor(payload) { + this.type = payload["type"]; + this.all = payload["all"]; + this.publisher = payload["publisher"]; + this.track = payload["track"]; + this.kind = payload["kind"]; + } +} + + + + +/** + * Options to pass to update a RecordingRulesInstance + */ +export interface RecordingRulesListInstanceUpdateOptions { + /** A JSON-encoded array of recording rules. */ + "rules"?: any; +} + + +export interface RecordingRulesSolution { + roomSid: string; +} + +export interface RecordingRulesListInstance { + _version: V1; + _solution: RecordingRulesSolution; + _uri: string; + + + + /** + * Fetch a RecordingRulesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingRulesInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingRulesInstance) => any): Promise<RecordingRulesInstance> + + /** + * Fetch a RecordingRulesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingRulesInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingRulesInstance>) => any): Promise<ApiResponse<RecordingRulesInstance>> + + + + /** + * Update a RecordingRulesInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingRulesInstance + */ + update(callback?: (error: Error | null, item?: RecordingRulesInstance) => any): Promise<RecordingRulesInstance>; + /** + * Update a RecordingRulesInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingRulesInstance + */ + update(params: RecordingRulesListInstanceUpdateOptions, callback?: (error: Error | null, item?: RecordingRulesInstance) => any): Promise<RecordingRulesInstance>; + + /** + * Update a RecordingRulesInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingRulesInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingRulesInstance>) => any): Promise<ApiResponse<RecordingRulesInstance>>; + /** + * Update a RecordingRulesInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingRulesInstance with HTTP metadata + */ + updateWithHttpInfo(params: RecordingRulesListInstanceUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RecordingRulesInstance>) => any): Promise<ApiResponse<RecordingRulesInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RecordingRulesListInstance(version: V1, roomSid: string): RecordingRulesListInstance { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + const instance = {} as RecordingRulesListInstance; + + instance._version = version; + instance._solution = { roomSid, }; + instance._uri = `/Rooms/${roomSid}/RecordingRules`; + + instance.fetch = function fetch( callback?: (error: Error | null, items: RecordingRulesInstance) => any): Promise<RecordingRulesInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RecordingRulesInstance(operationVersion, payload, instance._solution.roomSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<RecordingRulesInstance>) => any): Promise<ApiResponse<RecordingRulesInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RecordingRulesResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<RecordingRulesInstance> => ({ + ...response, + body: new RecordingRulesInstance(operationVersion, response.body, instance._solution.roomSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.update = function update(params?: RecordingRulesListInstanceUpdateOptions | ((error: Error | null, items: RecordingRulesInstance) => any), callback?: (error: Error | null, items: RecordingRulesInstance) => any): Promise<RecordingRulesInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["rules"] !== undefined) + data["Rules"] = serialize.object(params["rules"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RecordingRulesInstance(operationVersion, payload, instance._solution.roomSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.updateWithHttpInfo = function updateWithHttpInfo(params?: RecordingRulesListInstanceUpdateOptions | ((error: Error | null, items: ApiResponse<RecordingRulesInstance>) => any), callback?: (error: Error | null, items: ApiResponse<RecordingRulesInstance>) => any): Promise<ApiResponse<RecordingRulesInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["rules"] !== undefined) + data["Rules"] = serialize.object(params["rules"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<RecordingRulesResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RecordingRulesInstance> => ({ + ...response, + body: new RecordingRulesInstance(operationVersion, response.body, instance._solution.roomSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface RecordingRulesPayload extends RecordingRulesResource {} + +interface RecordingRulesResource { + room_sid: string; + rules: Array<VideoV1RoomRoomRecordingRuleRules>; + date_created: Date; + date_updated: Date; +} + +export class RecordingRulesInstance { + + constructor(protected _version: V1, payload: RecordingRulesResource, roomSid: string) { + + this.roomSid = (payload.room_sid); + this.rules = payload.rules !== null && payload.rules !== undefined ? payload.rules.map( + (payload: any) => new VideoV1RoomRoomRecordingRuleRules(payload) + ) : null; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + + } + + /** + * The SID of the Room resource for the Recording Rules + */ + roomSid: string; + /** + * A collection of Recording Rules that describe how to include or exclude matching tracks for recording + */ + rules: Array<VideoV1RoomRoomRecordingRuleRules>; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + roomSid: this.roomSid, + rules: this.rules, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/video/v1/room/roomRecording.ts b/rest/video/v1/room/roomRecording.ts new file mode 100644 index 000000000..7cf1e36b1 --- /dev/null +++ b/rest/video/v1/room/roomRecording.ts @@ -0,0 +1,762 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The codec used for the recording. Can be: `VP8` or `H264`. + */ +export type RoomRecordingCodec = 'VP8'|'H264'|'OPUS'|'PCMU'; + +export type RoomRecordingFormat = 'mka'|'mkv'; + +/** + * The status of the recording. Can be: `processing`, `completed`, or `deleted`. `processing` indicates the Recording is still being captured. `completed` indicates the Recording has been captured and is now available for download. `deleted` means the recording media has been deleted from the system, but its metadata is still available for historical purposes. + */ +export type RoomRecordingStatus = 'processing'|'completed'|'deleted'|'failed'; + +/** + * The recording\'s media type. Can be: `audio` or `video`. + */ +export type RoomRecordingType = 'audio'|'video'|'data'; + + + + +/** + * Options to pass to each + */ +export interface RoomRecordingListInstanceEachOptions { + /** Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. */ + "status"?: RoomRecordingStatus; + /** Read only the recordings that have this `source_sid`. */ + "sourceSid"?: string; + /** Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RoomRecordingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RoomRecordingListInstanceOptions { + /** Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. */ + "status"?: RoomRecordingStatus; + /** Read only the recordings that have this `source_sid`. */ + "sourceSid"?: string; + /** Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RoomRecordingListInstancePageOptions { + /** Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. */ + "status"?: RoomRecordingStatus; + /** Read only the recordings that have this `source_sid`. */ + "sourceSid"?: string; + /** Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedAfter"?: Date; + /** Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. */ + "dateCreatedBefore"?: Date; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RoomRecordingContext { + + /** + * Remove a RoomRecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a RoomRecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a RoomRecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomRecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RoomRecordingInstance) => any): Promise<RoomRecordingInstance> + + /** + * Fetch a RoomRecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomRecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RoomRecordingInstance>) => any): Promise<ApiResponse<RoomRecordingInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RoomRecordingContextSolution { + "roomSid": string; + "sid": string; +} + +export class RoomRecordingContextImpl implements RoomRecordingContext { + protected _solution: RoomRecordingContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, roomSid: string, sid: string) { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { roomSid, sid, }; + this._uri = `/Rooms/${roomSid}/Recordings/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RoomRecordingInstance) => any): Promise<RoomRecordingInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RoomRecordingInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RoomRecordingInstance>) => any): Promise<ApiResponse<RoomRecordingInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RoomRecordingResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<RoomRecordingInstance> => ({ + ...response, + body: new RoomRecordingInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RoomRecordingPayload extends TwilioResponsePayload { + recordings: RoomRecordingResource[]; +} + +interface RoomRecordingResource { + account_sid: string; + status: RoomRecordingStatus; + date_created: Date; + sid: string; + source_sid: string; + size: number; + url: string; + type: RoomRecordingType; + duration: number; + container_format: RoomRecordingFormat; + codec: RoomRecordingCodec; + grouping_sids: any; + track_name: string; + offset: number; + media_external_location: string; + room_sid: string; + links: Record<string, string>; +} + +export class RoomRecordingInstance { + protected _solution: RoomRecordingContextSolution; + protected _context?: RoomRecordingContext; + + constructor(protected _version: V1, payload: RoomRecordingResource, roomSid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.status = payload.status; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.sid = (payload.sid); + this.sourceSid = (payload.source_sid); + this.size = (payload.size); + this.url = (payload.url); + this.type = payload.type; + this.duration = deserialize.integer(payload.duration); + this.containerFormat = payload.container_format; + this.codec = payload.codec; + this.groupingSids = (payload.grouping_sids); + this.trackName = (payload.track_name); + this.offset = (payload.offset); + this.mediaExternalLocation = (payload.media_external_location); + this.roomSid = (payload.room_sid); + this.links = (payload.links); + + this._solution = { roomSid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RoomRecording resource. + */ + accountSid: string; + status: RoomRecordingStatus; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The unique string that we created to identify the RoomRecording resource. + */ + sid: string; + /** + * The SID of the recording source. For a Room Recording, this value is a `track_sid`. + */ + sourceSid: string; + /** + * The size of the recorded track in bytes. + */ + size: number; + /** + * The absolute URL of the resource. + */ + url: string; + type: RoomRecordingType; + /** + * The duration of the recording rounded to the nearest second. Sub-second duration tracks have a `duration` of 1 second + */ + duration: number; + containerFormat: RoomRecordingFormat; + codec: RoomRecordingCodec; + /** + * A list of SIDs related to the Recording. Includes the `room_sid` and `participant_sid`. + */ + groupingSids: any; + /** + * The name that was given to the source track of the recording. If no name is given, the `source_sid` is used. + */ + trackName: string; + /** + * The time in milliseconds elapsed between an arbitrary point in time, common to all group rooms, and the moment when the source room of this track started. This information provides a synchronization mechanism for recordings belonging to the same room. + */ + offset: number; + /** + * The URL of the media file associated with the recording when stored externally. See [External S3 Recordings](/docs/video/api/external-s3-recordings) for more details. + */ + mediaExternalLocation: string; + /** + * The SID of the Room resource the recording is associated with. + */ + roomSid: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): RoomRecordingContext { + this._context = this._context || new RoomRecordingContextImpl(this._version, this._solution.roomSid, this._solution.sid); + return this._context; + } + + /** + * Remove a RoomRecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RoomRecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RoomRecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomRecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RoomRecordingInstance) => any): Promise<RoomRecordingInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RoomRecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RoomRecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RoomRecordingInstance>) => any): Promise<ApiResponse<RoomRecordingInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + status: this.status, + dateCreated: this.dateCreated, + sid: this.sid, + sourceSid: this.sourceSid, + size: this.size, + url: this.url, + type: this.type, + duration: this.duration, + containerFormat: this.containerFormat, + codec: this.codec, + groupingSids: this.groupingSids, + trackName: this.trackName, + offset: this.offset, + mediaExternalLocation: this.mediaExternalLocation, + roomSid: this.roomSid, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RoomRecordingSolution { + roomSid: string; +} + +export interface RoomRecordingListInstance { + _version: V1; + _solution: RoomRecordingSolution; + _uri: string; + + (sid: string, ): RoomRecordingContext; + get(sid: string, ): RoomRecordingContext; + + + + + + + + /** + * Streams RoomRecordingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomRecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RoomRecordingInstance, done: (err?: Error) => void) => void): void; + each(params: RoomRecordingListInstanceEachOptions, callback?: (item: RoomRecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RoomRecordingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomRecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RoomRecordingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RoomRecordingListInstanceEachOptions, callback?: (item: RoomRecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RoomRecordingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RoomRecordingPage) => any): Promise<RoomRecordingPage>; + /** + * Retrieve a single target page of RoomRecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RoomRecordingPage>) => any): Promise<ApiResponse<RoomRecordingPage>>; + /** + * Lists RoomRecordingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomRecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RoomRecordingInstance[]) => any): Promise<RoomRecordingInstance[]>; + list(params: RoomRecordingListInstanceOptions, callback?: (error: Error | null, items: RoomRecordingInstance[]) => any): Promise<RoomRecordingInstance[]>; + /** + * Lists RoomRecordingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomRecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RoomRecordingInstance[]>) => any): Promise<ApiResponse<RoomRecordingInstance[]>>; + listWithHttpInfo(params: RoomRecordingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RoomRecordingInstance[]>) => any): Promise<ApiResponse<RoomRecordingInstance[]>>; + /** + * Retrieve a single page of RoomRecordingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomRecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RoomRecordingPage) => any): Promise<RoomRecordingPage>; + page(params: RoomRecordingListInstancePageOptions, callback?: (error: Error | null, items: RoomRecordingPage) => any): Promise<RoomRecordingPage>; + /** + * Retrieve a single page of RoomRecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RoomRecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RoomRecordingPage>) => any): Promise<ApiResponse<RoomRecordingPage>>; + pageWithHttpInfo(params: RoomRecordingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RoomRecordingPage>) => any): Promise<ApiResponse<RoomRecordingPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RoomRecordingListInstance(version: V1, roomSid: string): RoomRecordingListInstance { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as RoomRecordingListInstance; + + instance.get = function get(sid, ): RoomRecordingContext { + return new RoomRecordingContextImpl(version, roomSid, sid); + } + + instance._version = version; + instance._solution = { roomSid, }; + instance._uri = `/Rooms/${roomSid}/Recordings`; + + instance.page = function page(params?: RoomRecordingListInstancePageOptions | ((error: Error | null, items: RoomRecordingPage) => any), callback?: (error: Error | null, items: RoomRecordingPage) => any): Promise<RoomRecordingPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["sourceSid"] !== undefined) + data["SourceSid"] = params["sourceSid"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RoomRecordingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RoomRecordingPage) => any): Promise<RoomRecordingPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RoomRecordingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RoomRecordingListInstancePageOptions | ((error: Error | null, items: ApiResponse<RoomRecordingPage>) => any), callback?: (error: Error | null, items: ApiResponse<RoomRecordingPage>) => any): Promise<ApiResponse<RoomRecordingPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["sourceSid"] !== undefined) + data["SourceSid"] = params["sourceSid"]; + if (params["dateCreatedAfter"] !== undefined) + data["DateCreatedAfter"] = serialize.iso8601DateTime(params["dateCreatedAfter"]); + if (params["dateCreatedBefore"] !== undefined) + data["DateCreatedBefore"] = serialize.iso8601DateTime(params["dateCreatedBefore"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RoomRecordingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RoomRecordingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RoomRecordingPage>) => any): Promise<ApiResponse<RoomRecordingPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RoomRecordingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RoomRecordingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RoomRecordingPage extends Page<V1, RoomRecordingPayload, RoomRecordingResource, RoomRecordingInstance> { +/** +* Initialize the RoomRecordingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: RoomRecordingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RoomRecordingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RoomRecordingResource): RoomRecordingInstance { + + return new RoomRecordingInstance( + this._version, + payload, + this._solution.roomSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/video/v1/room/transcriptions.ts b/rest/video/v1/room/transcriptions.ts new file mode 100644 index 000000000..de6c108de --- /dev/null +++ b/rest/video/v1/room/transcriptions.ts @@ -0,0 +1,886 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * The status of the transcriptions resource. + */ +export type TranscriptionsStatus = 'started'|'stopped'|'failed'; + + + +/** + * Options to pass to update a TranscriptionsInstance + */ +export interface TranscriptionsContextUpdateOptions { + /** */ + "status"?: TranscriptionsStatus; + /** A collection of properties that describe transcription behaviour. */ + "configuration"?: object; +} + +/** + * Options to pass to create a TranscriptionsInstance + */ +export interface TranscriptionsListInstanceCreateOptions { + /** A collection of properties that describe transcription behaviour. */ + "configuration"?: object; +} + +/** + * Options to pass to each + */ +export interface TranscriptionsListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TranscriptionsInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TranscriptionsListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TranscriptionsListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TranscriptionsContext { + + /** + * Fetch a TranscriptionsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance> + + /** + * Fetch a TranscriptionsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>> + + /** + * Update a TranscriptionsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance + */ + update(callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance>; + /** + * Update a TranscriptionsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance + */ + update(params: TranscriptionsContextUpdateOptions, callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance>; + + /** + * Update a TranscriptionsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>>; + /** + * Update a TranscriptionsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance with HTTP metadata + */ + updateWithHttpInfo(params: TranscriptionsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TranscriptionsContextSolution { + "roomSid": string; + "ttid": string; +} + +export class TranscriptionsContextImpl implements TranscriptionsContext { + protected _solution: TranscriptionsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, roomSid: string, ttid: string) { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + if (!isValidPathParam(ttid)) { + throw new Error('Parameter \'ttid\' is not valid.'); + } + + this._solution = { roomSid, ttid, }; + this._uri = `/Rooms/${roomSid}/Transcriptions/${ttid}`; + } + + fetch(callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionsInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.ttid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TranscriptionsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TranscriptionsInstance> => ({ + ...response, + body: new TranscriptionsInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.ttid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: TranscriptionsContextUpdateOptions | ((error: Error | null, item?: TranscriptionsInstance) => any),callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionsInstance(operationVersion, payload, instance._solution.roomSid, instance._solution.ttid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: TranscriptionsContextUpdateOptions | ((error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<TranscriptionsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TranscriptionsInstance> => ({ + ...response, + body: new TranscriptionsInstance(operationVersion, response.body, instance._solution.roomSid, instance._solution.ttid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TranscriptionsPayload extends TwilioResponsePayload { + transcriptions: TranscriptionsResource[]; +} + +interface TranscriptionsResource { + ttid: string; + account_sid: string; + room_sid: string; + source_sid: string; + status: TranscriptionsStatus; + date_created: Date; + date_updated: Date; + start_time: Date; + end_time: Date; + duration: number; + url: string; + configuration: Record<string, object>; +} + +export class TranscriptionsInstance { + protected _solution: TranscriptionsContextSolution; + protected _context?: TranscriptionsContext; + + constructor(protected _version: V1, payload: TranscriptionsResource, roomSid: string, ttid?: string) { + + this.ttid = (payload.ttid); + this.accountSid = (payload.account_sid); + this.roomSid = (payload.room_sid); + this.sourceSid = (payload.source_sid); + this.status = payload.status; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.startTime = deserialize.iso8601DateTime(payload.start_time); + this.endTime = deserialize.iso8601DateTime(payload.end_time); + this.duration = deserialize.integer(payload.duration); + this.url = (payload.url); + this.configuration = (payload.configuration); + + this._solution = { roomSid, ttid: ttid, }; + } + + /** + * The unique string that we created to identify the transcriptions resource. + */ + ttid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Room resource. + */ + accountSid: string; + /** + * The SID of the transcriptions\'s room. + */ + roomSid: string; + /** + * The SID of the transcriptions\'s associated call. + */ + sourceSid: string; + status: TranscriptionsStatus; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + */ + dateUpdated: Date; + /** + * The time of transcriptions connected to the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + */ + startTime: Date; + /** + * The time when the transcriptions disconnected from the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + */ + endTime: Date; + /** + * The duration in seconds that the transcriptions were `connected`. Populated only after the transcriptions is `stopped`. + */ + duration: number; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * An JSON object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + */ + configuration: Record<string, object>; + + private get _proxy(): TranscriptionsContext { + this._context = this._context || new TranscriptionsContextImpl(this._version, this._solution.roomSid, this._solution.ttid); + return this._context; + } + + /** + * Fetch a TranscriptionsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TranscriptionsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TranscriptionsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance + */ + update(callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance>; + /** + * Update a TranscriptionsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance + */ + update(params: TranscriptionsContextUpdateOptions, callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance>; + + update(params?: any, callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a TranscriptionsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>>; + /** + * Update a TranscriptionsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance with HTTP metadata + */ + updateWithHttpInfo(params: TranscriptionsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + ttid: this.ttid, + accountSid: this.accountSid, + roomSid: this.roomSid, + sourceSid: this.sourceSid, + status: this.status, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + startTime: this.startTime, + endTime: this.endTime, + duration: this.duration, + url: this.url, + configuration: this.configuration, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TranscriptionsSolution { + roomSid: string; +} + +export interface TranscriptionsListInstance { + _version: V1; + _solution: TranscriptionsSolution; + _uri: string; + + (ttid: string, ): TranscriptionsContext; + get(ttid: string, ): TranscriptionsContext; + + + + + + + /** + * Create a TranscriptionsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance + */ + create(callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance>; + /** + * Create a TranscriptionsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance + */ + create(params: TranscriptionsListInstanceCreateOptions, callback?: (error: Error | null, item?: TranscriptionsInstance) => any): Promise<TranscriptionsInstance>; + + /** + * Create a TranscriptionsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>>; + /** + * Create a TranscriptionsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionsInstance with HTTP metadata + */ + createWithHttpInfo(params: TranscriptionsListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>>; + + + + + /** + * Streams TranscriptionsInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TranscriptionsInstance, done: (err?: Error) => void) => void): void; + each(params: TranscriptionsListInstanceEachOptions, callback?: (item: TranscriptionsInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TranscriptionsInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionsListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TranscriptionsInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TranscriptionsListInstanceEachOptions, callback?: (item: TranscriptionsInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TranscriptionsInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TranscriptionsPage) => any): Promise<TranscriptionsPage>; + /** + * Retrieve a single target page of TranscriptionsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TranscriptionsPage>) => any): Promise<ApiResponse<TranscriptionsPage>>; + /** + * Lists TranscriptionsInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TranscriptionsInstance[]) => any): Promise<TranscriptionsInstance[]>; + list(params: TranscriptionsListInstanceOptions, callback?: (error: Error | null, items: TranscriptionsInstance[]) => any): Promise<TranscriptionsInstance[]>; + /** + * Lists TranscriptionsInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionsListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TranscriptionsInstance[]>) => any): Promise<ApiResponse<TranscriptionsInstance[]>>; + listWithHttpInfo(params: TranscriptionsListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TranscriptionsInstance[]>) => any): Promise<ApiResponse<TranscriptionsInstance[]>>; + /** + * Retrieve a single page of TranscriptionsInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TranscriptionsPage) => any): Promise<TranscriptionsPage>; + page(params: TranscriptionsListInstancePageOptions, callback?: (error: Error | null, items: TranscriptionsPage) => any): Promise<TranscriptionsPage>; + /** + * Retrieve a single page of TranscriptionsInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionsListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TranscriptionsPage>) => any): Promise<ApiResponse<TranscriptionsPage>>; + pageWithHttpInfo(params: TranscriptionsListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TranscriptionsPage>) => any): Promise<ApiResponse<TranscriptionsPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TranscriptionsListInstance(version: V1, roomSid: string): TranscriptionsListInstance { + if (!isValidPathParam(roomSid)) { + throw new Error('Parameter \'roomSid\' is not valid.'); + } + + const instance = ((ttid, ) => instance.get(ttid, )) as TranscriptionsListInstance; + + instance.get = function get(ttid, ): TranscriptionsContext { + return new TranscriptionsContextImpl(version, roomSid, ttid); + } + + instance._version = version; + instance._solution = { roomSid, }; + instance._uri = `/Rooms/${roomSid}/Transcriptions`; + + instance.create = function create(params?: TranscriptionsListInstanceCreateOptions | ((error: Error | null, items: TranscriptionsInstance) => any), callback?: (error: Error | null, items: TranscriptionsInstance) => any): Promise<TranscriptionsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionsInstance(operationVersion, payload, instance._solution.roomSid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: TranscriptionsListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<TranscriptionsInstance>) => any), callback?: (error: Error | null, items: ApiResponse<TranscriptionsInstance>) => any): Promise<ApiResponse<TranscriptionsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["configuration"] !== undefined) + data["Configuration"] = serialize.object(params["configuration"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TranscriptionsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TranscriptionsInstance> => ({ + ...response, + body: new TranscriptionsInstance(operationVersion, response.body, instance._solution.roomSid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TranscriptionsListInstancePageOptions | ((error: Error | null, items: TranscriptionsPage) => any), callback?: (error: Error | null, items: TranscriptionsPage) => any): Promise<TranscriptionsPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TranscriptionsPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TranscriptionsPage) => any): Promise<TranscriptionsPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TranscriptionsPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TranscriptionsListInstancePageOptions | ((error: Error | null, items: ApiResponse<TranscriptionsPage>) => any), callback?: (error: Error | null, items: ApiResponse<TranscriptionsPage>) => any): Promise<ApiResponse<TranscriptionsPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TranscriptionsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TranscriptionsPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TranscriptionsPage>) => any): Promise<ApiResponse<TranscriptionsPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TranscriptionsPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TranscriptionsPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TranscriptionsPage extends Page<V1, TranscriptionsPayload, TranscriptionsResource, TranscriptionsInstance> { +/** +* Initialize the TranscriptionsPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: TranscriptionsSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TranscriptionsInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TranscriptionsResource): TranscriptionsInstance { + + return new TranscriptionsInstance( + this._version, + payload, + this._solution.roomSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/V1.ts b/rest/voice/V1.ts new file mode 100644 index 000000000..c999de3ef --- /dev/null +++ b/rest/voice/V1.ts @@ -0,0 +1,101 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import VoiceBase from "../VoiceBase"; +import Version from "../../base/Version"; +import { ArchivedCallListInstance } from "./v1/archivedCall"; +import { BulkCountryUpdateListInstance } from "./v1/bulkCountryUpdate"; +import { ByocTrunkListInstance } from "./v1/byocTrunk"; +import { ConnectionPolicyListInstance } from "./v1/connectionPolicy"; +import { CountryListInstance } from "./v1/country"; +import { IpRecordListInstance } from "./v1/ipRecord"; +import { SettingsListInstance } from "./v1/settings"; +import { SourceIpMappingListInstance } from "./v1/sourceIpMapping"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Voice + * + * @param domain - The Twilio (Twilio.Voice) domain + */ + constructor(domain: VoiceBase) { + super(domain, "v1"); + } + + /** archivedCalls - { Twilio.Voice.V1.ArchivedCallListInstance } resource */ + protected _archivedCalls?: ArchivedCallListInstance; + /** bulkCountryUpdates - { Twilio.Voice.V1.BulkCountryUpdateListInstance } resource */ + protected _bulkCountryUpdates?: BulkCountryUpdateListInstance; + /** byocTrunks - { Twilio.Voice.V1.ByocTrunkListInstance } resource */ + protected _byocTrunks?: ByocTrunkListInstance; + /** connectionPolicies - { Twilio.Voice.V1.ConnectionPolicyListInstance } resource */ + protected _connectionPolicies?: ConnectionPolicyListInstance; + /** countries - { Twilio.Voice.V1.CountryListInstance } resource */ + protected _countries?: CountryListInstance; + /** ipRecords - { Twilio.Voice.V1.IpRecordListInstance } resource */ + protected _ipRecords?: IpRecordListInstance; + /** settings - { Twilio.Voice.V1.SettingsListInstance } resource */ + protected _settings?: SettingsListInstance; + /** sourceIpMappings - { Twilio.Voice.V1.SourceIpMappingListInstance } resource */ + protected _sourceIpMappings?: SourceIpMappingListInstance; + + /** Getter for archivedCalls resource */ + get archivedCalls(): ArchivedCallListInstance { + this._archivedCalls = this._archivedCalls || ArchivedCallListInstance(this); + return this._archivedCalls; + } + + /** Getter for bulkCountryUpdates resource */ + get bulkCountryUpdates(): BulkCountryUpdateListInstance { + this._bulkCountryUpdates = this._bulkCountryUpdates || BulkCountryUpdateListInstance(this); + return this._bulkCountryUpdates; + } + + /** Getter for byocTrunks resource */ + get byocTrunks(): ByocTrunkListInstance { + this._byocTrunks = this._byocTrunks || ByocTrunkListInstance(this); + return this._byocTrunks; + } + + /** Getter for connectionPolicies resource */ + get connectionPolicies(): ConnectionPolicyListInstance { + this._connectionPolicies = this._connectionPolicies || ConnectionPolicyListInstance(this); + return this._connectionPolicies; + } + + /** Getter for countries resource */ + get countries(): CountryListInstance { + this._countries = this._countries || CountryListInstance(this); + return this._countries; + } + + /** Getter for ipRecords resource */ + get ipRecords(): IpRecordListInstance { + this._ipRecords = this._ipRecords || IpRecordListInstance(this); + return this._ipRecords; + } + + /** Getter for settings resource */ + get settings(): SettingsListInstance { + this._settings = this._settings || SettingsListInstance(this); + return this._settings; + } + + /** Getter for sourceIpMappings resource */ + get sourceIpMappings(): SourceIpMappingListInstance { + this._sourceIpMappings = this._sourceIpMappings || SourceIpMappingListInstance(this); + return this._sourceIpMappings; + } + +} diff --git a/rest/voice/V2.ts b/rest/voice/V2.ts new file mode 100644 index 000000000..a09b1b10c --- /dev/null +++ b/rest/voice/V2.ts @@ -0,0 +1,83 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio API definition for public-api voice + * Powers Twilio public-api voice + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import VoiceBase from "../VoiceBase"; +import Version from "../../base/Version"; +import { AccountDefaultConfigurationListInstance } from "./v2/accountDefaultConfiguration"; +import { ConfigurationListInstance } from "./v2/configuration"; +import { DefaultListInstance } from "./v2/default"; +import { RecordingListInstance } from "./v2/recording"; +import { TranscriptionListInstance } from "./v2/transcription"; +import { TypeListInstance } from "./v2/type"; + +export default class V2 extends Version { + /** + * Initialize the V2 version of Voice + * + * @param domain - The Twilio (Twilio.Voice) domain + */ + constructor(domain: VoiceBase) { + super(domain, "v2"); + } + + /** accountDefaultConfiguration - { Twilio.Voice.V2.AccountDefaultConfigurationListInstance } resource */ + protected _accountDefaultConfiguration?: AccountDefaultConfigurationListInstance; + /** configurations - { Twilio.Voice.V2.ConfigurationListInstance } resource */ + protected _configurations?: ConfigurationListInstance; + /** default - { Twilio.Voice.V2.DefaultListInstance } resource */ + protected _default?: DefaultListInstance; + /** recording - { Twilio.Voice.V2.RecordingListInstance } resource */ + protected _recording?: RecordingListInstance; + /** transcription - { Twilio.Voice.V2.TranscriptionListInstance } resource */ + protected _transcription?: TranscriptionListInstance; + /** type - { Twilio.Voice.V2.TypeListInstance } resource */ + protected _type?: TypeListInstance; + + /** Getter for accountDefaultConfiguration resource */ + get accountDefaultConfiguration(): AccountDefaultConfigurationListInstance { + this._accountDefaultConfiguration = this._accountDefaultConfiguration || AccountDefaultConfigurationListInstance(this); + return this._accountDefaultConfiguration; + } + + /** Getter for configurations resource */ + get configurations(): ConfigurationListInstance { + this._configurations = this._configurations || ConfigurationListInstance(this); + return this._configurations; + } + + /** Getter for default resource */ + get default(): DefaultListInstance { + this._default = this._default || DefaultListInstance(this); + return this._default; + } + + /** Getter for recording resource */ + get recording(): RecordingListInstance { + this._recording = this._recording || RecordingListInstance(this); + return this._recording; + } + + /** Getter for transcription resource */ + get transcription(): TranscriptionListInstance { + this._transcription = this._transcription || TranscriptionListInstance(this); + return this._transcription; + } + + /** Getter for type resource */ + get type(): TypeListInstance { + this._type = this._type || TypeListInstance(this); + return this._type; + } + +} diff --git a/rest/voice/V3.ts b/rest/voice/V3.ts new file mode 100644 index 000000000..32d7fb006 --- /dev/null +++ b/rest/voice/V3.ts @@ -0,0 +1,38 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio API definition for public-api voice + * Powers Twilio public-api voice + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import VoiceBase from "../VoiceBase"; +import Version from "../../base/Version"; +import { TranscriptionListInstance } from "./v3/transcription"; + +export default class V3 extends Version { + /** + * Initialize the V3 version of Voice + * + * @param domain - The Twilio (Twilio.Voice) domain + */ + constructor(domain: VoiceBase) { + super(domain, "v3"); + } + + /** transcriptions - { Twilio.Voice.V3.TranscriptionListInstance } resource */ + protected _transcriptions?: TranscriptionListInstance; + + /** Getter for transcriptions resource */ + get transcriptions(): TranscriptionListInstance { + this._transcriptions = this._transcriptions || TranscriptionListInstance(this); + return this._transcriptions; + } + +} diff --git a/rest/voice/v1/archivedCall.ts b/rest/voice/v1/archivedCall.ts new file mode 100644 index 000000000..d41614d7c --- /dev/null +++ b/rest/voice/v1/archivedCall.ts @@ -0,0 +1,166 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +export interface ArchivedCallContext { + + /** + * Remove a ArchivedCallInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ArchivedCallInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ArchivedCallContextSolution { + "date": Date; + "sid": string; +} + +export class ArchivedCallContextImpl implements ArchivedCallContext { + protected _solution: ArchivedCallContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, date: Date, sid: string) { + if (!isValidPathParam(date)) { + throw new Error('Parameter \'date\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { date, sid, }; + this._uri = `/Archives/${date}/Calls/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + +export interface ArchivedCallSolution { +} + +export interface ArchivedCallListInstance { + _version: V1; + _solution: ArchivedCallSolution; + _uri: string; + + (date: Date, sid: string, ): ArchivedCallContext; + get(date: Date, sid: string, ): ArchivedCallContext; + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ArchivedCallListInstance(version: V1): ArchivedCallListInstance { + const instance = ((date, sid, ) => instance.get(date, sid, )) as ArchivedCallListInstance; + + instance.get = function get(date, sid, ): ArchivedCallContext { + return new ArchivedCallContextImpl(version, date, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/voice/v1/bulkCountryUpdate.ts b/rest/voice/v1/bulkCountryUpdate.ts new file mode 100644 index 000000000..2c4af8877 --- /dev/null +++ b/rest/voice/v1/bulkCountryUpdate.ts @@ -0,0 +1,202 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + +/** + * Options to pass to create a BulkCountryUpdateInstance + */ +export interface BulkCountryUpdateListInstanceCreateOptions { + /** URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` */ + "updateRequest": string; +} + + +export interface BulkCountryUpdateSolution { +} + +export interface BulkCountryUpdateListInstance { + _version: V1; + _solution: BulkCountryUpdateSolution; + _uri: string; + + + + /** + * Create a BulkCountryUpdateInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkCountryUpdateInstance + */ + create(params: BulkCountryUpdateListInstanceCreateOptions, callback?: (error: Error | null, item?: BulkCountryUpdateInstance) => any): Promise<BulkCountryUpdateInstance>; + + /** + * Create a BulkCountryUpdateInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed BulkCountryUpdateInstance with HTTP metadata + */ + createWithHttpInfo(params: BulkCountryUpdateListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<BulkCountryUpdateInstance>) => any): Promise<ApiResponse<BulkCountryUpdateInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function BulkCountryUpdateListInstance(version: V1): BulkCountryUpdateListInstance { + const instance = {} as BulkCountryUpdateListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/DialingPermissions/BulkCountryUpdates`; + + instance.create = function create(params: BulkCountryUpdateListInstanceCreateOptions, callback?: (error: Error | null, items: BulkCountryUpdateInstance) => any): Promise<BulkCountryUpdateInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["updateRequest"] === null || params["updateRequest"] === undefined) { + throw new Error('Required parameter "params[\'updateRequest\']" missing.'); + } + + let data: any = {}; + + + + data["UpdateRequest"] = params["updateRequest"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new BulkCountryUpdateInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: BulkCountryUpdateListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<BulkCountryUpdateInstance>) => any): Promise<ApiResponse<BulkCountryUpdateInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["updateRequest"] === null || params["updateRequest"] === undefined) { + throw new Error('Required parameter "params[\'updateRequest\']" missing.'); + } + + let data: any = {}; + + + + data["UpdateRequest"] = params["updateRequest"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<BulkCountryUpdateResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<BulkCountryUpdateInstance> => ({ + ...response, + body: new BulkCountryUpdateInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface BulkCountryUpdatePayload extends BulkCountryUpdateResource {} + +interface BulkCountryUpdateResource { + update_count: number; + update_request: string; +} + +export class BulkCountryUpdateInstance { + + constructor(protected _version: V1, payload: BulkCountryUpdateResource) { + + this.updateCount = deserialize.integer(payload.update_count); + this.updateRequest = (payload.update_request); + + } + + /** + * The number of countries updated + */ + updateCount: number; + /** + * A bulk update request to change voice dialing country permissions stored as a URL-encoded, JSON array of update objects. For example : `[ { \"iso_code\": \"GB\", \"low_risk_numbers_enabled\": \"true\", \"high_risk_special_numbers_enabled\":\"true\", \"high_risk_tollfraud_numbers_enabled\": \"false\" } ]` + */ + updateRequest: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + updateCount: this.updateCount, + updateRequest: this.updateRequest, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/voice/v1/byocTrunk.ts b/rest/voice/v1/byocTrunk.ts new file mode 100644 index 000000000..43a91271d --- /dev/null +++ b/rest/voice/v1/byocTrunk.ts @@ -0,0 +1,1074 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a ByocTrunkInstance + */ +export interface ByocTrunkContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. */ + "friendlyName"?: string; + /** The URL we should call when the BYOC Trunk receives a call. */ + "voiceUrl"?: string; + /** The HTTP method we should use to call `voice_url` */ + "voiceMethod"?: string; + /** The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL that we should call to pass status parameters (such as call ended) to your application. */ + "statusCallbackUrl"?: string; + /** The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. */ + "statusCallbackMethod"?: string; + /** Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. */ + "cnamLookupEnabled"?: boolean; + /** The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. */ + "connectionPolicySid"?: string; + /** The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". */ + "fromDomainSid"?: string; +} + +/** + * Options to pass to create a ByocTrunkInstance + */ +export interface ByocTrunkListInstanceCreateOptions { + /** A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. */ + "friendlyName"?: string; + /** The URL we should call when the BYOC Trunk receives a call. */ + "voiceUrl"?: string; + /** The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. */ + "voiceMethod"?: string; + /** The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. */ + "voiceFallbackUrl"?: string; + /** The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. */ + "voiceFallbackMethod"?: string; + /** The URL that we should call to pass status parameters (such as call ended) to your application. */ + "statusCallbackUrl"?: string; + /** The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. */ + "statusCallbackMethod"?: string; + /** Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. */ + "cnamLookupEnabled"?: boolean; + /** The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. */ + "connectionPolicySid"?: string; + /** The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". */ + "fromDomainSid"?: string; +} + +/** + * Options to pass to each + */ +export interface ByocTrunkListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ByocTrunkInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ByocTrunkListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ByocTrunkListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ByocTrunkContext { + + /** + * Remove a ByocTrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ByocTrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ByocTrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance + */ + fetch(callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance> + + /** + * Fetch a ByocTrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>> + + /** + * Update a ByocTrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance + */ + update(callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; + /** + * Update a ByocTrunkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance + */ + update(params: ByocTrunkContextUpdateOptions, callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; + + /** + * Update a ByocTrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>>; + /** + * Update a ByocTrunkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance with HTTP metadata + */ + updateWithHttpInfo(params: ByocTrunkContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ByocTrunkContextSolution { + "sid": string; +} + +export class ByocTrunkContextImpl implements ByocTrunkContext { + protected _solution: ByocTrunkContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/ByocTrunks/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ByocTrunkInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ByocTrunkResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ByocTrunkInstance> => ({ + ...response, + body: new ByocTrunkInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ByocTrunkContextUpdateOptions | ((error: Error | null, item?: ByocTrunkInstance) => any),callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["cnamLookupEnabled"] !== undefined) + data["CnamLookupEnabled"] = serialize.bool(params["cnamLookupEnabled"]); + if (params["connectionPolicySid"] !== undefined) + data["ConnectionPolicySid"] = params["connectionPolicySid"]; + if (params["fromDomainSid"] !== undefined) + data["FromDomainSid"] = params["fromDomainSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ByocTrunkInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ByocTrunkContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["cnamLookupEnabled"] !== undefined) + data["CnamLookupEnabled"] = serialize.bool(params["cnamLookupEnabled"]); + if (params["connectionPolicySid"] !== undefined) + data["ConnectionPolicySid"] = params["connectionPolicySid"]; + if (params["fromDomainSid"] !== undefined) + data["FromDomainSid"] = params["fromDomainSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ByocTrunkResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ByocTrunkInstance> => ({ + ...response, + body: new ByocTrunkInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ByocTrunkPayload extends TwilioResponsePayload { + byoc_trunks: ByocTrunkResource[]; +} + +interface ByocTrunkResource { + account_sid: string; + sid: string; + friendly_name: string; + voice_url: string; + voice_method: string; + voice_fallback_url: string; + voice_fallback_method: string; + status_callback_url: string; + status_callback_method: string; + cnam_lookup_enabled: boolean; + connection_policy_sid: string; + from_domain_sid: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class ByocTrunkInstance { + protected _solution: ByocTrunkContextSolution; + protected _context?: ByocTrunkContext; + + constructor(protected _version: V1, payload: ByocTrunkResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.voiceUrl = (payload.voice_url); + this.voiceMethod = (payload.voice_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.statusCallbackUrl = (payload.status_callback_url); + this.statusCallbackMethod = (payload.status_callback_method); + this.cnamLookupEnabled = (payload.cnam_lookup_enabled); + this.connectionPolicySid = (payload.connection_policy_sid); + this.fromDomainSid = (payload.from_domain_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the BYOC Trunk resource. + */ + accountSid: string; + /** + * The unique string that that we created to identify the BYOC Trunk resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The URL we call using the `voice_method` when the BYOC Trunk receives a call. + */ + voiceUrl: string; + /** + * The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + */ + voiceMethod: string; + /** + * The URL that we call when an error occurs while retrieving or executing the TwiML requested from `voice_url`. + */ + voiceFallbackUrl: string; + /** + * The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + */ + voiceFallbackMethod: string; + /** + * The URL that we call to pass status parameters (such as call ended) to your application. + */ + statusCallbackUrl: string; + /** + * The HTTP method we use to call `status_callback_url`. Either `GET` or `POST`. + */ + statusCallbackMethod: string; + /** + * Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + */ + cnamLookupEnabled: boolean; + /** + * The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + */ + connectionPolicySid: string; + /** + * The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \"call back\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \"sip.twilio.com\". + */ + fromDomainSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): ByocTrunkContext { + this._context = this._context || new ByocTrunkContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ByocTrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ByocTrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ByocTrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance + */ + fetch(callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ByocTrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ByocTrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance + */ + update(callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; + /** + * Update a ByocTrunkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance + */ + update(params: ByocTrunkContextUpdateOptions, callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ByocTrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>>; + /** + * Update a ByocTrunkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance with HTTP metadata + */ + updateWithHttpInfo(params: ByocTrunkContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + friendlyName: this.friendlyName, + voiceUrl: this.voiceUrl, + voiceMethod: this.voiceMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceFallbackMethod: this.voiceFallbackMethod, + statusCallbackUrl: this.statusCallbackUrl, + statusCallbackMethod: this.statusCallbackMethod, + cnamLookupEnabled: this.cnamLookupEnabled, + connectionPolicySid: this.connectionPolicySid, + fromDomainSid: this.fromDomainSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ByocTrunkSolution { +} + +export interface ByocTrunkListInstance { + _version: V1; + _solution: ByocTrunkSolution; + _uri: string; + + (sid: string, ): ByocTrunkContext; + get(sid: string, ): ByocTrunkContext; + + + + + + + + + /** + * Create a ByocTrunkInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance + */ + create(callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; + /** + * Create a ByocTrunkInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance + */ + create(params: ByocTrunkListInstanceCreateOptions, callback?: (error: Error | null, item?: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; + + /** + * Create a ByocTrunkInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>>; + /** + * Create a ByocTrunkInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ByocTrunkInstance with HTTP metadata + */ + createWithHttpInfo(params: ByocTrunkListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>>; + + + + + /** + * Streams ByocTrunkInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ByocTrunkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ByocTrunkInstance, done: (err?: Error) => void) => void): void; + each(params: ByocTrunkListInstanceEachOptions, callback?: (item: ByocTrunkInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ByocTrunkInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ByocTrunkListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ByocTrunkInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ByocTrunkListInstanceEachOptions, callback?: (item: ByocTrunkInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ByocTrunkInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ByocTrunkPage) => any): Promise<ByocTrunkPage>; + /** + * Retrieve a single target page of ByocTrunkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ByocTrunkPage>) => any): Promise<ApiResponse<ByocTrunkPage>>; + /** + * Lists ByocTrunkInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ByocTrunkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ByocTrunkInstance[]) => any): Promise<ByocTrunkInstance[]>; + list(params: ByocTrunkListInstanceOptions, callback?: (error: Error | null, items: ByocTrunkInstance[]) => any): Promise<ByocTrunkInstance[]>; + /** + * Lists ByocTrunkInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ByocTrunkListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ByocTrunkInstance[]>) => any): Promise<ApiResponse<ByocTrunkInstance[]>>; + listWithHttpInfo(params: ByocTrunkListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ByocTrunkInstance[]>) => any): Promise<ApiResponse<ByocTrunkInstance[]>>; + /** + * Retrieve a single page of ByocTrunkInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ByocTrunkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ByocTrunkPage) => any): Promise<ByocTrunkPage>; + page(params: ByocTrunkListInstancePageOptions, callback?: (error: Error | null, items: ByocTrunkPage) => any): Promise<ByocTrunkPage>; + /** + * Retrieve a single page of ByocTrunkInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ByocTrunkListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ByocTrunkPage>) => any): Promise<ApiResponse<ByocTrunkPage>>; + pageWithHttpInfo(params: ByocTrunkListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ByocTrunkPage>) => any): Promise<ApiResponse<ByocTrunkPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ByocTrunkListInstance(version: V1): ByocTrunkListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ByocTrunkListInstance; + + instance.get = function get(sid, ): ByocTrunkContext { + return new ByocTrunkContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ByocTrunks`; + + instance.create = function create(params?: ByocTrunkListInstanceCreateOptions | ((error: Error | null, items: ByocTrunkInstance) => any), callback?: (error: Error | null, items: ByocTrunkInstance) => any): Promise<ByocTrunkInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["cnamLookupEnabled"] !== undefined) + data["CnamLookupEnabled"] = serialize.bool(params["cnamLookupEnabled"]); + if (params["connectionPolicySid"] !== undefined) + data["ConnectionPolicySid"] = params["connectionPolicySid"]; + if (params["fromDomainSid"] !== undefined) + data["FromDomainSid"] = params["fromDomainSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ByocTrunkInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ByocTrunkListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<ByocTrunkInstance>) => any), callback?: (error: Error | null, items: ApiResponse<ByocTrunkInstance>) => any): Promise<ApiResponse<ByocTrunkInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["statusCallbackUrl"] !== undefined) + data["StatusCallbackUrl"] = params["statusCallbackUrl"]; + if (params["statusCallbackMethod"] !== undefined) + data["StatusCallbackMethod"] = params["statusCallbackMethod"]; + if (params["cnamLookupEnabled"] !== undefined) + data["CnamLookupEnabled"] = serialize.bool(params["cnamLookupEnabled"]); + if (params["connectionPolicySid"] !== undefined) + data["ConnectionPolicySid"] = params["connectionPolicySid"]; + if (params["fromDomainSid"] !== undefined) + data["FromDomainSid"] = params["fromDomainSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ByocTrunkResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ByocTrunkInstance> => ({ + ...response, + body: new ByocTrunkInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ByocTrunkListInstancePageOptions | ((error: Error | null, items: ByocTrunkPage) => any), callback?: (error: Error | null, items: ByocTrunkPage) => any): Promise<ByocTrunkPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ByocTrunkPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ByocTrunkPage) => any): Promise<ByocTrunkPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ByocTrunkPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ByocTrunkListInstancePageOptions | ((error: Error | null, items: ApiResponse<ByocTrunkPage>) => any), callback?: (error: Error | null, items: ApiResponse<ByocTrunkPage>) => any): Promise<ApiResponse<ByocTrunkPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ByocTrunkPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ByocTrunkPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ByocTrunkPage>) => any): Promise<ApiResponse<ByocTrunkPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ByocTrunkPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ByocTrunkPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ByocTrunkPage extends Page<V1, ByocTrunkPayload, ByocTrunkResource, ByocTrunkInstance> { +/** +* Initialize the ByocTrunkPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ByocTrunkSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ByocTrunkInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ByocTrunkResource): ByocTrunkInstance { + + return new ByocTrunkInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/v1/connectionPolicy.ts b/rest/voice/v1/connectionPolicy.ts new file mode 100644 index 000000000..f649dab4d --- /dev/null +++ b/rest/voice/v1/connectionPolicy.ts @@ -0,0 +1,925 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { ConnectionPolicyTargetListInstance } from "./connectionPolicy/connectionPolicyTarget"; + + + + + +/** + * Options to pass to update a ConnectionPolicyInstance + */ +export interface ConnectionPolicyContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a ConnectionPolicyInstance + */ +export interface ConnectionPolicyListInstanceCreateOptions { + /** A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. */ + "friendlyName"?: string; +} + +/** + * Options to pass to each + */ +export interface ConnectionPolicyListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConnectionPolicyInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConnectionPolicyListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConnectionPolicyListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ConnectionPolicyContext { + targets: ConnectionPolicyTargetListInstance; + + /** + * Remove a ConnectionPolicyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ConnectionPolicyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ConnectionPolicyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance + */ + fetch(callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance> + + /** + * Fetch a ConnectionPolicyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>> + + /** + * Update a ConnectionPolicyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance + */ + update(callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance>; + /** + * Update a ConnectionPolicyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance + */ + update(params: ConnectionPolicyContextUpdateOptions, callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance>; + + /** + * Update a ConnectionPolicyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>>; + /** + * Update a ConnectionPolicyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConnectionPolicyContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConnectionPolicyContextSolution { + "sid": string; +} + +export class ConnectionPolicyContextImpl implements ConnectionPolicyContext { + protected _solution: ConnectionPolicyContextSolution; + protected _uri: string; + + protected _targets?: ConnectionPolicyTargetListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/ConnectionPolicies/${sid}`; + } + + get targets(): ConnectionPolicyTargetListInstance { + this._targets = this._targets || ConnectionPolicyTargetListInstance(this._version, this._solution.sid); + return this._targets; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConnectionPolicyInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ConnectionPolicyResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ConnectionPolicyInstance> => ({ + ...response, + body: new ConnectionPolicyInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ConnectionPolicyContextUpdateOptions | ((error: Error | null, item?: ConnectionPolicyInstance) => any),callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConnectionPolicyInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ConnectionPolicyContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ConnectionPolicyResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ConnectionPolicyInstance> => ({ + ...response, + body: new ConnectionPolicyInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConnectionPolicyPayload extends TwilioResponsePayload { + connection_policies: ConnectionPolicyResource[]; +} + +interface ConnectionPolicyResource { + account_sid: string; + sid: string; + friendly_name: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; +} + +export class ConnectionPolicyInstance { + protected _solution: ConnectionPolicyContextSolution; + protected _context?: ConnectionPolicyContext; + + constructor(protected _version: V1, payload: ConnectionPolicyResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Connection Policy resource. + */ + accountSid: string; + /** + * The unique string that we created to identify the Connection Policy resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related resources. + */ + links: Record<string, string>; + + private get _proxy(): ConnectionPolicyContext { + this._context = this._context || new ConnectionPolicyContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a ConnectionPolicyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ConnectionPolicyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ConnectionPolicyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance + */ + fetch(callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConnectionPolicyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ConnectionPolicyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance + */ + update(callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance>; + /** + * Update a ConnectionPolicyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance + */ + update(params: ConnectionPolicyContextUpdateOptions, callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConnectionPolicyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>>; + /** + * Update a ConnectionPolicyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConnectionPolicyContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the targets. + */ + targets(): ConnectionPolicyTargetListInstance { + return this._proxy.targets; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + friendlyName: this.friendlyName, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConnectionPolicySolution { +} + +export interface ConnectionPolicyListInstance { + _version: V1; + _solution: ConnectionPolicySolution; + _uri: string; + + (sid: string, ): ConnectionPolicyContext; + get(sid: string, ): ConnectionPolicyContext; + + + + + + + + + /** + * Create a ConnectionPolicyInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance + */ + create(callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance>; + /** + * Create a ConnectionPolicyInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance + */ + create(params: ConnectionPolicyListInstanceCreateOptions, callback?: (error: Error | null, item?: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance>; + + /** + * Create a ConnectionPolicyInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>>; + /** + * Create a ConnectionPolicyInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyInstance with HTTP metadata + */ + createWithHttpInfo(params: ConnectionPolicyListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>>; + + + + + /** + * Streams ConnectionPolicyInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConnectionPolicyInstance, done: (err?: Error) => void) => void): void; + each(params: ConnectionPolicyListInstanceEachOptions, callback?: (item: ConnectionPolicyInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConnectionPolicyInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConnectionPolicyInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConnectionPolicyListInstanceEachOptions, callback?: (item: ConnectionPolicyInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConnectionPolicyInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConnectionPolicyPage) => any): Promise<ConnectionPolicyPage>; + /** + * Retrieve a single target page of ConnectionPolicyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyPage>) => any): Promise<ApiResponse<ConnectionPolicyPage>>; + /** + * Lists ConnectionPolicyInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConnectionPolicyInstance[]) => any): Promise<ConnectionPolicyInstance[]>; + list(params: ConnectionPolicyListInstanceOptions, callback?: (error: Error | null, items: ConnectionPolicyInstance[]) => any): Promise<ConnectionPolicyInstance[]>; + /** + * Lists ConnectionPolicyInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyInstance[]>) => any): Promise<ApiResponse<ConnectionPolicyInstance[]>>; + listWithHttpInfo(params: ConnectionPolicyListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyInstance[]>) => any): Promise<ApiResponse<ConnectionPolicyInstance[]>>; + /** + * Retrieve a single page of ConnectionPolicyInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConnectionPolicyPage) => any): Promise<ConnectionPolicyPage>; + page(params: ConnectionPolicyListInstancePageOptions, callback?: (error: Error | null, items: ConnectionPolicyPage) => any): Promise<ConnectionPolicyPage>; + /** + * Retrieve a single page of ConnectionPolicyInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyPage>) => any): Promise<ApiResponse<ConnectionPolicyPage>>; + pageWithHttpInfo(params: ConnectionPolicyListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyPage>) => any): Promise<ApiResponse<ConnectionPolicyPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConnectionPolicyListInstance(version: V1): ConnectionPolicyListInstance { + const instance = ((sid, ) => instance.get(sid, )) as ConnectionPolicyListInstance; + + instance.get = function get(sid, ): ConnectionPolicyContext { + return new ConnectionPolicyContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/ConnectionPolicies`; + + instance.create = function create(params?: ConnectionPolicyListInstanceCreateOptions | ((error: Error | null, items: ConnectionPolicyInstance) => any), callback?: (error: Error | null, items: ConnectionPolicyInstance) => any): Promise<ConnectionPolicyInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConnectionPolicyInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: ConnectionPolicyListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<ConnectionPolicyInstance>) => any), callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyInstance>) => any): Promise<ApiResponse<ConnectionPolicyInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ConnectionPolicyResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ConnectionPolicyInstance> => ({ + ...response, + body: new ConnectionPolicyInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ConnectionPolicyListInstancePageOptions | ((error: Error | null, items: ConnectionPolicyPage) => any), callback?: (error: Error | null, items: ConnectionPolicyPage) => any): Promise<ConnectionPolicyPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConnectionPolicyPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConnectionPolicyPage) => any): Promise<ConnectionPolicyPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConnectionPolicyPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConnectionPolicyListInstancePageOptions | ((error: Error | null, items: ApiResponse<ConnectionPolicyPage>) => any), callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyPage>) => any): Promise<ApiResponse<ConnectionPolicyPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ConnectionPolicyPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConnectionPolicyPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ConnectionPolicyPage>) => any): Promise<ApiResponse<ConnectionPolicyPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ConnectionPolicyPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConnectionPolicyPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConnectionPolicyPage extends Page<V1, ConnectionPolicyPayload, ConnectionPolicyResource, ConnectionPolicyInstance> { +/** +* Initialize the ConnectionPolicyPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ConnectionPolicySolution) { + super(version, response, solution); + } + + /** + * Build an instance of ConnectionPolicyInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConnectionPolicyResource): ConnectionPolicyInstance { + + return new ConnectionPolicyInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/v1/connectionPolicy/connectionPolicyTarget.ts b/rest/voice/v1/connectionPolicy/connectionPolicyTarget.ts new file mode 100644 index 000000000..bfdabaa27 --- /dev/null +++ b/rest/voice/v1/connectionPolicy/connectionPolicyTarget.ts @@ -0,0 +1,983 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a ConnectionPolicyTargetInstance + */ +export interface ConnectionPolicyTargetContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. */ + "friendlyName"?: string; + /** The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. */ + "target"?: string; + /** The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. */ + "priority"?: number; + /** The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. */ + "weight"?: number; + /** Whether the Target is enabled. */ + "enabled"?: boolean; +} + +/** + * Options to pass to create a ConnectionPolicyTargetInstance + */ +export interface ConnectionPolicyTargetListInstanceCreateOptions { + /** The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. */ + "target": string; + /** A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. */ + "friendlyName"?: string; + /** The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. */ + "priority"?: number; + /** The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. */ + "weight"?: number; + /** Whether the Target is enabled. The default is `true`. */ + "enabled"?: boolean; +} + +/** + * Options to pass to each + */ +export interface ConnectionPolicyTargetListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: ConnectionPolicyTargetInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface ConnectionPolicyTargetListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface ConnectionPolicyTargetListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface ConnectionPolicyTargetContext { + + /** + * Remove a ConnectionPolicyTargetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a ConnectionPolicyTargetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a ConnectionPolicyTargetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance + */ + fetch(callback?: (error: Error | null, item?: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance> + + /** + * Fetch a ConnectionPolicyTargetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>> + + /** + * Update a ConnectionPolicyTargetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance + */ + update(callback?: (error: Error | null, item?: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance>; + /** + * Update a ConnectionPolicyTargetInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance + */ + update(params: ConnectionPolicyTargetContextUpdateOptions, callback?: (error: Error | null, item?: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance>; + + /** + * Update a ConnectionPolicyTargetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>>; + /** + * Update a ConnectionPolicyTargetInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConnectionPolicyTargetContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConnectionPolicyTargetContextSolution { + "connectionPolicySid": string; + "sid": string; +} + +export class ConnectionPolicyTargetContextImpl implements ConnectionPolicyTargetContext { + protected _solution: ConnectionPolicyTargetContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, connectionPolicySid: string, sid: string) { + if (!isValidPathParam(connectionPolicySid)) { + throw new Error('Parameter \'connectionPolicySid\' is not valid.'); + } + + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { connectionPolicySid, sid, }; + this._uri = `/ConnectionPolicies/${connectionPolicySid}/Targets/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new ConnectionPolicyTargetInstance(operationVersion, payload, instance._solution.connectionPolicySid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<ConnectionPolicyTargetResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<ConnectionPolicyTargetInstance> => ({ + ...response, + body: new ConnectionPolicyTargetInstance(operationVersion, response.body, instance._solution.connectionPolicySid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: ConnectionPolicyTargetContextUpdateOptions | ((error: Error | null, item?: ConnectionPolicyTargetInstance) => any),callback?: (error: Error | null, item?: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["target"] !== undefined) + data["Target"] = params["target"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["weight"] !== undefined) + data["Weight"] = params["weight"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConnectionPolicyTargetInstance(operationVersion, payload, instance._solution.connectionPolicySid, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: ConnectionPolicyTargetContextUpdateOptions | ((error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["target"] !== undefined) + data["Target"] = params["target"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["weight"] !== undefined) + data["Weight"] = params["weight"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<ConnectionPolicyTargetResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ConnectionPolicyTargetInstance> => ({ + ...response, + body: new ConnectionPolicyTargetInstance(operationVersion, response.body, instance._solution.connectionPolicySid, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConnectionPolicyTargetPayload extends TwilioResponsePayload { + targets: ConnectionPolicyTargetResource[]; +} + +interface ConnectionPolicyTargetResource { + account_sid: string; + connection_policy_sid: string; + sid: string; + friendly_name: string; + target: string; + priority: number; + weight: number; + enabled: boolean; + date_created: Date; + date_updated: Date; + url: string; +} + +export class ConnectionPolicyTargetInstance { + protected _solution: ConnectionPolicyTargetContextSolution; + protected _context?: ConnectionPolicyTargetContext; + + constructor(protected _version: V1, payload: ConnectionPolicyTargetResource, connectionPolicySid: string, sid?: string) { + + this.accountSid = (payload.account_sid); + this.connectionPolicySid = (payload.connection_policy_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.target = (payload.target); + this.priority = deserialize.integer(payload.priority); + this.weight = deserialize.integer(payload.weight); + this.enabled = (payload.enabled); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { connectionPolicySid, sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Target resource. + */ + accountSid: string; + /** + * The SID of the Connection Policy that owns the Target. + */ + connectionPolicySid: string; + /** + * The unique string that we created to identify the Target resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + */ + target: string; + /** + * The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + */ + priority: number; + /** + * The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + */ + weight: number; + /** + * Whether the target is enabled. The default is `true`. + */ + enabled: boolean; + /** + * The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): ConnectionPolicyTargetContext { + this._context = this._context || new ConnectionPolicyTargetContextImpl(this._version, this._solution.connectionPolicySid, this._solution.sid); + return this._context; + } + + /** + * Remove a ConnectionPolicyTargetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a ConnectionPolicyTargetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a ConnectionPolicyTargetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance + */ + fetch(callback?: (error: Error | null, item?: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a ConnectionPolicyTargetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a ConnectionPolicyTargetInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance + */ + update(callback?: (error: Error | null, item?: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance>; + /** + * Update a ConnectionPolicyTargetInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance + */ + update(params: ConnectionPolicyTargetContextUpdateOptions, callback?: (error: Error | null, item?: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance>; + + update(params?: any, callback?: (error: Error | null, item?: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a ConnectionPolicyTargetInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>>; + /** + * Update a ConnectionPolicyTargetInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance with HTTP metadata + */ + updateWithHttpInfo(params: ConnectionPolicyTargetContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + connectionPolicySid: this.connectionPolicySid, + sid: this.sid, + friendlyName: this.friendlyName, + target: this.target, + priority: this.priority, + weight: this.weight, + enabled: this.enabled, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConnectionPolicyTargetSolution { + connectionPolicySid: string; +} + +export interface ConnectionPolicyTargetListInstance { + _version: V1; + _solution: ConnectionPolicyTargetSolution; + _uri: string; + + (sid: string, ): ConnectionPolicyTargetContext; + get(sid: string, ): ConnectionPolicyTargetContext; + + + + + + + + + /** + * Create a ConnectionPolicyTargetInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance + */ + create(params: ConnectionPolicyTargetListInstanceCreateOptions, callback?: (error: Error | null, item?: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance>; + + /** + * Create a ConnectionPolicyTargetInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConnectionPolicyTargetInstance with HTTP metadata + */ + createWithHttpInfo(params: ConnectionPolicyTargetListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>>; + + + + + /** + * Streams ConnectionPolicyTargetInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyTargetListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: ConnectionPolicyTargetInstance, done: (err?: Error) => void) => void): void; + each(params: ConnectionPolicyTargetListInstanceEachOptions, callback?: (item: ConnectionPolicyTargetInstance, done: (err?: Error) => void) => void): void; + /** + * Streams ConnectionPolicyTargetInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyTargetListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: ConnectionPolicyTargetInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: ConnectionPolicyTargetListInstanceEachOptions, callback?: (item: ConnectionPolicyTargetInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of ConnectionPolicyTargetInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: ConnectionPolicyTargetPage) => any): Promise<ConnectionPolicyTargetPage>; + /** + * Retrieve a single target page of ConnectionPolicyTargetInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyTargetPage>) => any): Promise<ApiResponse<ConnectionPolicyTargetPage>>; + /** + * Lists ConnectionPolicyTargetInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyTargetListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: ConnectionPolicyTargetInstance[]) => any): Promise<ConnectionPolicyTargetInstance[]>; + list(params: ConnectionPolicyTargetListInstanceOptions, callback?: (error: Error | null, items: ConnectionPolicyTargetInstance[]) => any): Promise<ConnectionPolicyTargetInstance[]>; + /** + * Lists ConnectionPolicyTargetInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyTargetListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyTargetInstance[]>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance[]>>; + listWithHttpInfo(params: ConnectionPolicyTargetListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyTargetInstance[]>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance[]>>; + /** + * Retrieve a single page of ConnectionPolicyTargetInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyTargetListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: ConnectionPolicyTargetPage) => any): Promise<ConnectionPolicyTargetPage>; + page(params: ConnectionPolicyTargetListInstancePageOptions, callback?: (error: Error | null, items: ConnectionPolicyTargetPage) => any): Promise<ConnectionPolicyTargetPage>; + /** + * Retrieve a single page of ConnectionPolicyTargetInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { ConnectionPolicyTargetListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyTargetPage>) => any): Promise<ApiResponse<ConnectionPolicyTargetPage>>; + pageWithHttpInfo(params: ConnectionPolicyTargetListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyTargetPage>) => any): Promise<ApiResponse<ConnectionPolicyTargetPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConnectionPolicyTargetListInstance(version: V1, connectionPolicySid: string): ConnectionPolicyTargetListInstance { + if (!isValidPathParam(connectionPolicySid)) { + throw new Error('Parameter \'connectionPolicySid\' is not valid.'); + } + + const instance = ((sid, ) => instance.get(sid, )) as ConnectionPolicyTargetListInstance; + + instance.get = function get(sid, ): ConnectionPolicyTargetContext { + return new ConnectionPolicyTargetContextImpl(version, connectionPolicySid, sid); + } + + instance._version = version; + instance._solution = { connectionPolicySid, }; + instance._uri = `/ConnectionPolicies/${connectionPolicySid}/Targets`; + + instance.create = function create(params: ConnectionPolicyTargetListInstanceCreateOptions, callback?: (error: Error | null, items: ConnectionPolicyTargetInstance) => any): Promise<ConnectionPolicyTargetInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["target"] === null || params["target"] === undefined) { + throw new Error('Required parameter "params[\'target\']" missing.'); + } + + let data: any = {}; + + + + data["Target"] = params["target"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["weight"] !== undefined) + data["Weight"] = params["weight"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConnectionPolicyTargetInstance(operationVersion, payload, instance._solution.connectionPolicySid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: ConnectionPolicyTargetListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyTargetInstance>) => any): Promise<ApiResponse<ConnectionPolicyTargetInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["target"] === null || params["target"] === undefined) { + throw new Error('Required parameter "params[\'target\']" missing.'); + } + + let data: any = {}; + + + + data["Target"] = params["target"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["priority"] !== undefined) + data["Priority"] = params["priority"]; + if (params["weight"] !== undefined) + data["Weight"] = params["weight"]; + if (params["enabled"] !== undefined) + data["Enabled"] = serialize.bool(params["enabled"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ConnectionPolicyTargetResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ConnectionPolicyTargetInstance> => ({ + ...response, + body: new ConnectionPolicyTargetInstance(operationVersion, response.body, instance._solution.connectionPolicySid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: ConnectionPolicyTargetListInstancePageOptions | ((error: Error | null, items: ConnectionPolicyTargetPage) => any), callback?: (error: Error | null, items: ConnectionPolicyTargetPage) => any): Promise<ConnectionPolicyTargetPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new ConnectionPolicyTargetPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: ConnectionPolicyTargetPage) => any): Promise<ConnectionPolicyTargetPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new ConnectionPolicyTargetPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: ConnectionPolicyTargetListInstancePageOptions | ((error: Error | null, items: ApiResponse<ConnectionPolicyTargetPage>) => any), callback?: (error: Error | null, items: ApiResponse<ConnectionPolicyTargetPage>) => any): Promise<ApiResponse<ConnectionPolicyTargetPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ConnectionPolicyTargetPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConnectionPolicyTargetPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<ConnectionPolicyTargetPage>) => any): Promise<ApiResponse<ConnectionPolicyTargetPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<ConnectionPolicyTargetPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new ConnectionPolicyTargetPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConnectionPolicyTargetPage extends Page<V1, ConnectionPolicyTargetPayload, ConnectionPolicyTargetResource, ConnectionPolicyTargetInstance> { +/** +* Initialize the ConnectionPolicyTargetPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: ConnectionPolicyTargetSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ConnectionPolicyTargetInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConnectionPolicyTargetResource): ConnectionPolicyTargetInstance { + + return new ConnectionPolicyTargetInstance( + this._version, + payload, + this._solution.connectionPolicySid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/v1/country.ts b/rest/voice/v1/country.ts new file mode 100644 index 000000000..90063583d --- /dev/null +++ b/rest/voice/v1/country.ts @@ -0,0 +1,647 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { HighriskSpecialPrefixListInstance } from "./country/highriskSpecialPrefix"; + + + + +/** + * Options to pass to each + */ +export interface CountryListInstanceEachOptions { + /** Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) */ + "isoCode"?: string; + /** Filter to retrieve the country permissions by specifying the continent */ + "continent"?: string; + /** Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) */ + "countryCode"?: string; + /** Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. */ + "lowRiskNumbersEnabled"?: boolean; + /** Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` */ + "highRiskSpecialNumbersEnabled"?: boolean; + /** Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. */ + "highRiskTollfraudNumbersEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CountryInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CountryListInstanceOptions { + /** Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) */ + "isoCode"?: string; + /** Filter to retrieve the country permissions by specifying the continent */ + "continent"?: string; + /** Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) */ + "countryCode"?: string; + /** Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. */ + "lowRiskNumbersEnabled"?: boolean; + /** Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` */ + "highRiskSpecialNumbersEnabled"?: boolean; + /** Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. */ + "highRiskTollfraudNumbersEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CountryListInstancePageOptions { + /** Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) */ + "isoCode"?: string; + /** Filter to retrieve the country permissions by specifying the continent */ + "continent"?: string; + /** Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) */ + "countryCode"?: string; + /** Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. */ + "lowRiskNumbersEnabled"?: boolean; + /** Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` */ + "highRiskSpecialNumbersEnabled"?: boolean; + /** Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. */ + "highRiskTollfraudNumbersEnabled"?: boolean; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CountryContext { + highriskSpecialPrefixes: HighriskSpecialPrefixListInstance; + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CountryContextSolution { + "isoCode": string; +} + +export class CountryContextImpl implements CountryContext { + protected _solution: CountryContextSolution; + protected _uri: string; + + protected _highriskSpecialPrefixes?: HighriskSpecialPrefixListInstance; + + constructor(protected _version: V1, isoCode: string) { + if (!isValidPathParam(isoCode)) { + throw new Error('Parameter \'isoCode\' is not valid.'); + } + + this._solution = { isoCode, }; + this._uri = `/DialingPermissions/Countries/${isoCode}`; + } + + get highriskSpecialPrefixes(): HighriskSpecialPrefixListInstance { + this._highriskSpecialPrefixes = this._highriskSpecialPrefixes || HighriskSpecialPrefixListInstance(this._version, this._solution.isoCode); + return this._highriskSpecialPrefixes; + } + + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CountryInstance(operationVersion, payload, instance._solution.isoCode)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CountryResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CountryInstance> => ({ + ...response, + body: new CountryInstance(operationVersion, response.body, instance._solution.isoCode) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CountryPayload extends TwilioResponsePayload { + content: CountryResource[]; +} + +interface CountryResource { + iso_code: string; + name: string; + continent: string; + country_codes: Array<string>; + low_risk_numbers_enabled: boolean; + high_risk_special_numbers_enabled: boolean; + high_risk_tollfraud_numbers_enabled: boolean; + url: string; + links: Record<string, string>; +} + +export class CountryInstance { + protected _solution: CountryContextSolution; + protected _context?: CountryContext; + + constructor(protected _version: V1, payload: CountryResource, isoCode?: string) { + + this.isoCode = (payload.iso_code); + this.name = (payload.name); + this.continent = (payload.continent); + this.countryCodes = (payload.country_codes); + this.lowRiskNumbersEnabled = (payload.low_risk_numbers_enabled); + this.highRiskSpecialNumbersEnabled = (payload.high_risk_special_numbers_enabled); + this.highRiskTollfraudNumbersEnabled = (payload.high_risk_tollfraud_numbers_enabled); + this.url = (payload.url); + this.links = (payload.links); + + this._solution = { isoCode: isoCode, }; + } + + /** + * The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + */ + isoCode: string; + /** + * The name of the country. + */ + name: string; + /** + * The name of the continent in which the country is located. + */ + continent: string; + /** + * The E.164 assigned [country codes(s)](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + */ + countryCodes: Array<string>; + /** + * Whether dialing to low-risk numbers is enabled. + */ + lowRiskNumbersEnabled: boolean; + /** + * Whether dialing to high-risk special services numbers is enabled. These prefixes include number ranges allocated by the country and include premium numbers, special services, shared cost, and others + */ + highRiskSpecialNumbersEnabled: boolean; + /** + * Whether dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers is enabled. These prefixes include narrow number ranges that have a high-risk of international revenue sharing fraud (IRSF) attacks, also known as [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html). These prefixes are collected from anti-fraud databases and verified by analyzing calls on our network. These prefixes are not available for download and are updated frequently + */ + highRiskTollfraudNumbersEnabled: boolean; + /** + * The absolute URL of this resource. + */ + url: string; + /** + * A list of URLs related to this resource. + */ + links: Record<string, string>; + + private get _proxy(): CountryContext { + this._context = this._context || new CountryContextImpl(this._version, this._solution.isoCode); + return this._context; + } + + /** + * Fetch a CountryInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance + */ + fetch(callback?: (error: Error | null, item?: CountryInstance) => any): Promise<CountryInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CountryInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CountryInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CountryInstance>) => any): Promise<ApiResponse<CountryInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Access the highriskSpecialPrefixes. + */ + highriskSpecialPrefixes(): HighriskSpecialPrefixListInstance { + return this._proxy.highriskSpecialPrefixes; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + isoCode: this.isoCode, + name: this.name, + continent: this.continent, + countryCodes: this.countryCodes, + lowRiskNumbersEnabled: this.lowRiskNumbersEnabled, + highRiskSpecialNumbersEnabled: this.highRiskSpecialNumbersEnabled, + highRiskTollfraudNumbersEnabled: this.highRiskTollfraudNumbersEnabled, + url: this.url, + links: this.links, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CountrySolution { +} + +export interface CountryListInstance { + _version: V1; + _solution: CountrySolution; + _uri: string; + + (isoCode: string, ): CountryContext; + get(isoCode: string, ): CountryContext; + + + + + + /** + * Streams CountryInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + each(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CountryInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CountryListInstanceEachOptions, callback?: (item: CountryInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single target page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + /** + * Lists CountryInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + list(params: CountryListInstanceOptions, callback?: (error: Error | null, items: CountryInstance[]) => any): Promise<CountryInstance[]>; + /** + * Lists CountryInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + listWithHttpInfo(params: CountryListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CountryInstance[]>) => any): Promise<ApiResponse<CountryInstance[]>>; + /** + * Retrieve a single page of CountryInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + page(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage>; + /** + * Retrieve a single page of CountryInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CountryListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + pageWithHttpInfo(params: CountryListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CountryListInstance(version: V1): CountryListInstance { + const instance = ((isoCode, ) => instance.get(isoCode, )) as CountryListInstance; + + instance.get = function get(isoCode, ): CountryContext { + return new CountryContextImpl(version, isoCode); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/DialingPermissions/Countries`; + + instance.page = function page(params?: CountryListInstancePageOptions | ((error: Error | null, items: CountryPage) => any), callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["isoCode"] !== undefined) + data["IsoCode"] = params["isoCode"]; + if (params["continent"] !== undefined) + data["Continent"] = params["continent"]; + if (params["countryCode"] !== undefined) + data["CountryCode"] = params["countryCode"]; + if (params["lowRiskNumbersEnabled"] !== undefined) + data["LowRiskNumbersEnabled"] = serialize.bool(params["lowRiskNumbersEnabled"]); + if (params["highRiskSpecialNumbersEnabled"] !== undefined) + data["HighRiskSpecialNumbersEnabled"] = serialize.bool(params["highRiskSpecialNumbersEnabled"]); + if (params["highRiskTollfraudNumbersEnabled"] !== undefined) + data["HighRiskTollfraudNumbersEnabled"] = serialize.bool(params["highRiskTollfraudNumbersEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CountryPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CountryPage) => any): Promise<CountryPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CountryPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CountryListInstancePageOptions | ((error: Error | null, items: ApiResponse<CountryPage>) => any), callback?: (error: Error | null, items: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["isoCode"] !== undefined) + data["IsoCode"] = params["isoCode"]; + if (params["continent"] !== undefined) + data["Continent"] = params["continent"]; + if (params["countryCode"] !== undefined) + data["CountryCode"] = params["countryCode"]; + if (params["lowRiskNumbersEnabled"] !== undefined) + data["LowRiskNumbersEnabled"] = serialize.bool(params["lowRiskNumbersEnabled"]); + if (params["highRiskSpecialNumbersEnabled"] !== undefined) + data["HighRiskSpecialNumbersEnabled"] = serialize.bool(params["highRiskSpecialNumbersEnabled"]); + if (params["highRiskTollfraudNumbersEnabled"] !== undefined) + data["HighRiskTollfraudNumbersEnabled"] = serialize.bool(params["highRiskTollfraudNumbersEnabled"]); + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CountryPage>) => any): Promise<ApiResponse<CountryPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CountryPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CountryPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CountryPage extends Page<V1, CountryPayload, CountryResource, CountryInstance> { +/** +* Initialize the CountryPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CountrySolution) { + super(version, response, solution); + } + + /** + * Build an instance of CountryInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CountryResource): CountryInstance { + + return new CountryInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/v1/country/highriskSpecialPrefix.ts b/rest/voice/v1/country/highriskSpecialPrefix.ts new file mode 100644 index 000000000..7c850a5b3 --- /dev/null +++ b/rest/voice/v1/country/highriskSpecialPrefix.ts @@ -0,0 +1,384 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface HighriskSpecialPrefixListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: HighriskSpecialPrefixInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface HighriskSpecialPrefixListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface HighriskSpecialPrefixListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface HighriskSpecialPrefixSolution { + isoCode: string; +} + +export interface HighriskSpecialPrefixListInstance { + _version: V1; + _solution: HighriskSpecialPrefixSolution; + _uri: string; + + + + + /** + * Streams HighriskSpecialPrefixInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HighriskSpecialPrefixListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: HighriskSpecialPrefixInstance, done: (err?: Error) => void) => void): void; + each(params: HighriskSpecialPrefixListInstanceEachOptions, callback?: (item: HighriskSpecialPrefixInstance, done: (err?: Error) => void) => void): void; + /** + * Streams HighriskSpecialPrefixInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HighriskSpecialPrefixListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: HighriskSpecialPrefixInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: HighriskSpecialPrefixListInstanceEachOptions, callback?: (item: HighriskSpecialPrefixInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of HighriskSpecialPrefixInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: HighriskSpecialPrefixPage) => any): Promise<HighriskSpecialPrefixPage>; + /** + * Retrieve a single target page of HighriskSpecialPrefixInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<HighriskSpecialPrefixPage>) => any): Promise<ApiResponse<HighriskSpecialPrefixPage>>; + /** + * Lists HighriskSpecialPrefixInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HighriskSpecialPrefixListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: HighriskSpecialPrefixInstance[]) => any): Promise<HighriskSpecialPrefixInstance[]>; + list(params: HighriskSpecialPrefixListInstanceOptions, callback?: (error: Error | null, items: HighriskSpecialPrefixInstance[]) => any): Promise<HighriskSpecialPrefixInstance[]>; + /** + * Lists HighriskSpecialPrefixInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HighriskSpecialPrefixListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<HighriskSpecialPrefixInstance[]>) => any): Promise<ApiResponse<HighriskSpecialPrefixInstance[]>>; + listWithHttpInfo(params: HighriskSpecialPrefixListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<HighriskSpecialPrefixInstance[]>) => any): Promise<ApiResponse<HighriskSpecialPrefixInstance[]>>; + /** + * Retrieve a single page of HighriskSpecialPrefixInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HighriskSpecialPrefixListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: HighriskSpecialPrefixPage) => any): Promise<HighriskSpecialPrefixPage>; + page(params: HighriskSpecialPrefixListInstancePageOptions, callback?: (error: Error | null, items: HighriskSpecialPrefixPage) => any): Promise<HighriskSpecialPrefixPage>; + /** + * Retrieve a single page of HighriskSpecialPrefixInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { HighriskSpecialPrefixListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<HighriskSpecialPrefixPage>) => any): Promise<ApiResponse<HighriskSpecialPrefixPage>>; + pageWithHttpInfo(params: HighriskSpecialPrefixListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<HighriskSpecialPrefixPage>) => any): Promise<ApiResponse<HighriskSpecialPrefixPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function HighriskSpecialPrefixListInstance(version: V1, isoCode: string): HighriskSpecialPrefixListInstance { + if (!isValidPathParam(isoCode)) { + throw new Error('Parameter \'isoCode\' is not valid.'); + } + + const instance = {} as HighriskSpecialPrefixListInstance; + + instance._version = version; + instance._solution = { isoCode, }; + instance._uri = `/DialingPermissions/Countries/${isoCode}/HighRiskSpecialPrefixes`; + + instance.page = function page(params?: HighriskSpecialPrefixListInstancePageOptions | ((error: Error | null, items: HighriskSpecialPrefixPage) => any), callback?: (error: Error | null, items: HighriskSpecialPrefixPage) => any): Promise<HighriskSpecialPrefixPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new HighriskSpecialPrefixPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: HighriskSpecialPrefixPage) => any): Promise<HighriskSpecialPrefixPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new HighriskSpecialPrefixPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: HighriskSpecialPrefixListInstancePageOptions | ((error: Error | null, items: ApiResponse<HighriskSpecialPrefixPage>) => any), callback?: (error: Error | null, items: ApiResponse<HighriskSpecialPrefixPage>) => any): Promise<ApiResponse<HighriskSpecialPrefixPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<HighriskSpecialPrefixPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new HighriskSpecialPrefixPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<HighriskSpecialPrefixPage>) => any): Promise<ApiResponse<HighriskSpecialPrefixPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<HighriskSpecialPrefixPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new HighriskSpecialPrefixPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface HighriskSpecialPrefixPayload extends TwilioResponsePayload { + content: HighriskSpecialPrefixResource[]; +} + +interface HighriskSpecialPrefixResource { + prefix: string; +} + +export class HighriskSpecialPrefixInstance { + + constructor(protected _version: V1, payload: HighriskSpecialPrefixResource, isoCode: string) { + + this.prefix = (payload.prefix); + + } + + /** + * A prefix is a contiguous number range for a block of E.164 numbers that includes the E.164 assigned country code. For example, a North American Numbering Plan prefix like `+1510720` written like `+1(510) 720` matches all numbers inclusive from `+1(510) 720-0000` to `+1(510) 720-9999`. + */ + prefix: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + prefix: this.prefix, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class HighriskSpecialPrefixPage extends Page<V1, HighriskSpecialPrefixPayload, HighriskSpecialPrefixResource, HighriskSpecialPrefixInstance> { +/** +* Initialize the HighriskSpecialPrefixPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: HighriskSpecialPrefixSolution) { + super(version, response, solution); + } + + /** + * Build an instance of HighriskSpecialPrefixInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: HighriskSpecialPrefixResource): HighriskSpecialPrefixInstance { + + return new HighriskSpecialPrefixInstance( + this._version, + payload, + this._solution.isoCode, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/v1/ipRecord.ts b/rest/voice/v1/ipRecord.ts new file mode 100644 index 000000000..12b1e777e --- /dev/null +++ b/rest/voice/v1/ipRecord.ts @@ -0,0 +1,915 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a IpRecordInstance + */ +export interface IpRecordContextUpdateOptions { + /** A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a IpRecordInstance + */ +export interface IpRecordListInstanceCreateOptions { + /** An IP address in dotted decimal notation, IPv4 only. */ + "ipAddress": string; + /** A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. */ + "friendlyName"?: string; + /** An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. */ + "cidrPrefixLength"?: number; +} + +/** + * Options to pass to each + */ +export interface IpRecordListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: IpRecordInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface IpRecordListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface IpRecordListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface IpRecordContext { + + /** + * Remove a IpRecordInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a IpRecordInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a IpRecordInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance + */ + fetch(callback?: (error: Error | null, item?: IpRecordInstance) => any): Promise<IpRecordInstance> + + /** + * Fetch a IpRecordInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>> + + /** + * Update a IpRecordInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance + */ + update(callback?: (error: Error | null, item?: IpRecordInstance) => any): Promise<IpRecordInstance>; + /** + * Update a IpRecordInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance + */ + update(params: IpRecordContextUpdateOptions, callback?: (error: Error | null, item?: IpRecordInstance) => any): Promise<IpRecordInstance>; + + /** + * Update a IpRecordInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>>; + /** + * Update a IpRecordInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance with HTTP metadata + */ + updateWithHttpInfo(params: IpRecordContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface IpRecordContextSolution { + "sid": string; +} + +export class IpRecordContextImpl implements IpRecordContext { + protected _solution: IpRecordContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/IpRecords/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: IpRecordInstance) => any): Promise<IpRecordInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new IpRecordInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<IpRecordResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<IpRecordInstance> => ({ + ...response, + body: new IpRecordInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: IpRecordContextUpdateOptions | ((error: Error | null, item?: IpRecordInstance) => any),callback?: (error: Error | null, item?: IpRecordInstance) => any): Promise<IpRecordInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IpRecordInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: IpRecordContextUpdateOptions | ((error: Error | null, item?: ApiResponse<IpRecordInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<IpRecordResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<IpRecordInstance> => ({ + ...response, + body: new IpRecordInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface IpRecordPayload extends TwilioResponsePayload { + ip_records: IpRecordResource[]; +} + +interface IpRecordResource { + account_sid: string; + sid: string; + friendly_name: string; + ip_address: string; + cidr_prefix_length: number; + date_created: Date; + date_updated: Date; + url: string; +} + +export class IpRecordInstance { + protected _solution: IpRecordContextSolution; + protected _context?: IpRecordContext; + + constructor(protected _version: V1, payload: IpRecordResource, sid?: string) { + + this.accountSid = (payload.account_sid); + this.sid = (payload.sid); + this.friendlyName = (payload.friendly_name); + this.ipAddress = (payload.ip_address); + this.cidrPrefixLength = deserialize.integer(payload.cidr_prefix_length); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IP Record resource. + */ + accountSid: string; + /** + * The unique string that we created to identify the IP Record resource. + */ + sid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * An IP address in dotted decimal notation, IPv4 only. + */ + ipAddress: string; + /** + * An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + */ + cidrPrefixLength: number; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): IpRecordContext { + this._context = this._context || new IpRecordContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a IpRecordInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a IpRecordInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a IpRecordInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance + */ + fetch(callback?: (error: Error | null, item?: IpRecordInstance) => any): Promise<IpRecordInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a IpRecordInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a IpRecordInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance + */ + update(callback?: (error: Error | null, item?: IpRecordInstance) => any): Promise<IpRecordInstance>; + /** + * Update a IpRecordInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance + */ + update(params: IpRecordContextUpdateOptions, callback?: (error: Error | null, item?: IpRecordInstance) => any): Promise<IpRecordInstance>; + + update(params?: any, callback?: (error: Error | null, item?: IpRecordInstance) => any): Promise<IpRecordInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a IpRecordInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>>; + /** + * Update a IpRecordInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance with HTTP metadata + */ + updateWithHttpInfo(params: IpRecordContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + sid: this.sid, + friendlyName: this.friendlyName, + ipAddress: this.ipAddress, + cidrPrefixLength: this.cidrPrefixLength, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface IpRecordSolution { +} + +export interface IpRecordListInstance { + _version: V1; + _solution: IpRecordSolution; + _uri: string; + + (sid: string, ): IpRecordContext; + get(sid: string, ): IpRecordContext; + + + + + + + + + /** + * Create a IpRecordInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance + */ + create(params: IpRecordListInstanceCreateOptions, callback?: (error: Error | null, item?: IpRecordInstance) => any): Promise<IpRecordInstance>; + + /** + * Create a IpRecordInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed IpRecordInstance with HTTP metadata + */ + createWithHttpInfo(params: IpRecordListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>>; + + + + + /** + * Streams IpRecordInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpRecordListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: IpRecordInstance, done: (err?: Error) => void) => void): void; + each(params: IpRecordListInstanceEachOptions, callback?: (item: IpRecordInstance, done: (err?: Error) => void) => void): void; + /** + * Streams IpRecordInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpRecordListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: IpRecordInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: IpRecordListInstanceEachOptions, callback?: (item: IpRecordInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of IpRecordInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: IpRecordPage) => any): Promise<IpRecordPage>; + /** + * Retrieve a single target page of IpRecordInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<IpRecordPage>) => any): Promise<ApiResponse<IpRecordPage>>; + /** + * Lists IpRecordInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpRecordListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: IpRecordInstance[]) => any): Promise<IpRecordInstance[]>; + list(params: IpRecordListInstanceOptions, callback?: (error: Error | null, items: IpRecordInstance[]) => any): Promise<IpRecordInstance[]>; + /** + * Lists IpRecordInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpRecordListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<IpRecordInstance[]>) => any): Promise<ApiResponse<IpRecordInstance[]>>; + listWithHttpInfo(params: IpRecordListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<IpRecordInstance[]>) => any): Promise<ApiResponse<IpRecordInstance[]>>; + /** + * Retrieve a single page of IpRecordInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpRecordListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: IpRecordPage) => any): Promise<IpRecordPage>; + page(params: IpRecordListInstancePageOptions, callback?: (error: Error | null, items: IpRecordPage) => any): Promise<IpRecordPage>; + /** + * Retrieve a single page of IpRecordInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { IpRecordListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<IpRecordPage>) => any): Promise<ApiResponse<IpRecordPage>>; + pageWithHttpInfo(params: IpRecordListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<IpRecordPage>) => any): Promise<ApiResponse<IpRecordPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function IpRecordListInstance(version: V1): IpRecordListInstance { + const instance = ((sid, ) => instance.get(sid, )) as IpRecordListInstance; + + instance.get = function get(sid, ): IpRecordContext { + return new IpRecordContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/IpRecords`; + + instance.create = function create(params: IpRecordListInstanceCreateOptions, callback?: (error: Error | null, items: IpRecordInstance) => any): Promise<IpRecordInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["ipAddress"] === null || params["ipAddress"] === undefined) { + throw new Error('Required parameter "params[\'ipAddress\']" missing.'); + } + + let data: any = {}; + + + + data["IpAddress"] = params["ipAddress"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["cidrPrefixLength"] !== undefined) + data["CidrPrefixLength"] = params["cidrPrefixLength"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new IpRecordInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: IpRecordListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<IpRecordInstance>) => any): Promise<ApiResponse<IpRecordInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["ipAddress"] === null || params["ipAddress"] === undefined) { + throw new Error('Required parameter "params[\'ipAddress\']" missing.'); + } + + let data: any = {}; + + + + data["IpAddress"] = params["ipAddress"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["cidrPrefixLength"] !== undefined) + data["CidrPrefixLength"] = params["cidrPrefixLength"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<IpRecordResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<IpRecordInstance> => ({ + ...response, + body: new IpRecordInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: IpRecordListInstancePageOptions | ((error: Error | null, items: IpRecordPage) => any), callback?: (error: Error | null, items: IpRecordPage) => any): Promise<IpRecordPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new IpRecordPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: IpRecordPage) => any): Promise<IpRecordPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new IpRecordPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: IpRecordListInstancePageOptions | ((error: Error | null, items: ApiResponse<IpRecordPage>) => any), callback?: (error: Error | null, items: ApiResponse<IpRecordPage>) => any): Promise<ApiResponse<IpRecordPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<IpRecordPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpRecordPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<IpRecordPage>) => any): Promise<ApiResponse<IpRecordPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<IpRecordPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new IpRecordPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class IpRecordPage extends Page<V1, IpRecordPayload, IpRecordResource, IpRecordInstance> { +/** +* Initialize the IpRecordPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: IpRecordSolution) { + super(version, response, solution); + } + + /** + * Build an instance of IpRecordInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: IpRecordResource): IpRecordInstance { + + return new IpRecordInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/v1/settings.ts b/rest/voice/v1/settings.ts new file mode 100644 index 000000000..a0e8a1011 --- /dev/null +++ b/rest/voice/v1/settings.ts @@ -0,0 +1,397 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + +/** + * Options to pass to update a SettingsInstance + */ +export interface SettingsContextUpdateOptions { + /** `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. */ + "dialingPermissionsInheritance"?: boolean; +} + +export interface SettingsContext { + + /** + * Fetch a SettingsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance + */ + fetch(callback?: (error: Error | null, item?: SettingsInstance) => any): Promise<SettingsInstance> + + /** + * Fetch a SettingsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SettingsInstance>) => any): Promise<ApiResponse<SettingsInstance>> + + /** + * Update a SettingsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance + */ + update(callback?: (error: Error | null, item?: SettingsInstance) => any): Promise<SettingsInstance>; + /** + * Update a SettingsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance + */ + update(params: SettingsContextUpdateOptions, callback?: (error: Error | null, item?: SettingsInstance) => any): Promise<SettingsInstance>; + + /** + * Update a SettingsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SettingsInstance>) => any): Promise<ApiResponse<SettingsInstance>>; + /** + * Update a SettingsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance with HTTP metadata + */ + updateWithHttpInfo(params: SettingsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SettingsInstance>) => any): Promise<ApiResponse<SettingsInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SettingsContextSolution { +} + +export class SettingsContextImpl implements SettingsContext { + protected _solution: SettingsContextSolution; + protected _uri: string; + + + constructor(protected _version: V1) { + this._solution = { }; + this._uri = `/Settings`; + } + + fetch(callback?: (error: Error | null, item?: SettingsInstance) => any): Promise<SettingsInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SettingsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SettingsInstance>) => any): Promise<ApiResponse<SettingsInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SettingsResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SettingsInstance> => ({ + ...response, + body: new SettingsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SettingsContextUpdateOptions | ((error: Error | null, item?: SettingsInstance) => any),callback?: (error: Error | null, item?: SettingsInstance) => any): Promise<SettingsInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["dialingPermissionsInheritance"] !== undefined) + data["DialingPermissionsInheritance"] = serialize.bool(params["dialingPermissionsInheritance"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SettingsInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SettingsContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SettingsInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SettingsInstance>) => any): Promise<ApiResponse<SettingsInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["dialingPermissionsInheritance"] !== undefined) + data["DialingPermissionsInheritance"] = serialize.bool(params["dialingPermissionsInheritance"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SettingsResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SettingsInstance> => ({ + ...response, + body: new SettingsInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SettingsPayload extends SettingsResource {} + +interface SettingsResource { + dialing_permissions_inheritance: boolean; + url: string; +} + +export class SettingsInstance { + protected _solution: SettingsContextSolution; + protected _context?: SettingsContext; + + constructor(protected _version: V1, payload: SettingsResource) { + + this.dialingPermissionsInheritance = (payload.dialing_permissions_inheritance); + this.url = (payload.url); + + this._solution = { }; + } + + /** + * `true` if the sub-account will inherit voice dialing permissions from the Master Project; otherwise `false`. + */ + dialingPermissionsInheritance: boolean; + /** + * The absolute URL of this resource. + */ + url: string; + + private get _proxy(): SettingsContext { + this._context = this._context || new SettingsContextImpl(this._version); + return this._context; + } + + /** + * Fetch a SettingsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance + */ + fetch(callback?: (error: Error | null, item?: SettingsInstance) => any): Promise<SettingsInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SettingsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SettingsInstance>) => any): Promise<ApiResponse<SettingsInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SettingsInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance + */ + update(callback?: (error: Error | null, item?: SettingsInstance) => any): Promise<SettingsInstance>; + /** + * Update a SettingsInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance + */ + update(params: SettingsContextUpdateOptions, callback?: (error: Error | null, item?: SettingsInstance) => any): Promise<SettingsInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SettingsInstance) => any): Promise<SettingsInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SettingsInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SettingsInstance>) => any): Promise<ApiResponse<SettingsInstance>>; + /** + * Update a SettingsInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SettingsInstance with HTTP metadata + */ + updateWithHttpInfo(params: SettingsContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SettingsInstance>) => any): Promise<ApiResponse<SettingsInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SettingsInstance>) => any): Promise<ApiResponse<SettingsInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + dialingPermissionsInheritance: this.dialingPermissionsInheritance, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SettingsSolution { +} + +export interface SettingsListInstance { + _version: V1; + _solution: SettingsSolution; + _uri: string; + + (): SettingsContext; + get(): SettingsContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SettingsListInstance(version: V1): SettingsListInstance { + const instance = (() => instance.get()) as SettingsListInstance; + + instance.get = function get(): SettingsContext { + return new SettingsContextImpl(version); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/voice/v1/sourceIpMapping.ts b/rest/voice/v1/sourceIpMapping.ts new file mode 100644 index 000000000..8bda144fc --- /dev/null +++ b/rest/voice/v1/sourceIpMapping.ts @@ -0,0 +1,873 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Voice + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + + + + +/** + * Options to pass to update a SourceIpMappingInstance + */ +export interface SourceIpMappingContextUpdateOptions { + /** The SID of the SIP Domain that the IP Record should be mapped to. */ + "sipDomainSid": string; +} + +/** + * Options to pass to create a SourceIpMappingInstance + */ +export interface SourceIpMappingListInstanceCreateOptions { + /** The Twilio-provided string that uniquely identifies the IP Record resource to map from. */ + "ipRecordSid": string; + /** The SID of the SIP Domain that the IP Record should be mapped to. */ + "sipDomainSid": string; +} + +/** + * Options to pass to each + */ +export interface SourceIpMappingListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SourceIpMappingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SourceIpMappingListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SourceIpMappingListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SourceIpMappingContext { + + /** + * Remove a SourceIpMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SourceIpMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SourceIpMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SourceIpMappingInstance + */ + fetch(callback?: (error: Error | null, item?: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance> + + /** + * Fetch a SourceIpMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SourceIpMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SourceIpMappingInstance>) => any): Promise<ApiResponse<SourceIpMappingInstance>> + + /** + * Update a SourceIpMappingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SourceIpMappingInstance + */ + update(params: SourceIpMappingContextUpdateOptions, callback?: (error: Error | null, item?: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance>; + + /** + * Update a SourceIpMappingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SourceIpMappingInstance with HTTP metadata + */ + updateWithHttpInfo(params: SourceIpMappingContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SourceIpMappingInstance>) => any): Promise<ApiResponse<SourceIpMappingInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SourceIpMappingContextSolution { + "sid": string; +} + +export class SourceIpMappingContextImpl implements SourceIpMappingContext { + protected _solution: SourceIpMappingContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/SourceIpMappings/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SourceIpMappingInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SourceIpMappingInstance>) => any): Promise<ApiResponse<SourceIpMappingInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SourceIpMappingResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SourceIpMappingInstance> => ({ + ...response, + body: new SourceIpMappingInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params: SourceIpMappingContextUpdateOptions,callback?: (error: Error | null, item?: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["sipDomainSid"] === null || params["sipDomainSid"] === undefined) { + throw new Error('Required parameter "params[\'sipDomainSid\']" missing.'); + } + + let data: any = {}; + + + + data["SipDomainSid"] = params["sipDomainSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SourceIpMappingInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params: SourceIpMappingContextUpdateOptions,callback?: (error: Error | null, item?: ApiResponse<SourceIpMappingInstance>) => any): Promise<ApiResponse<SourceIpMappingInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["sipDomainSid"] === null || params["sipDomainSid"] === undefined) { + throw new Error('Required parameter "params[\'sipDomainSid\']" missing.'); + } + + let data: any = {}; + + + + data["SipDomainSid"] = params["sipDomainSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SourceIpMappingResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SourceIpMappingInstance> => ({ + ...response, + body: new SourceIpMappingInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SourceIpMappingPayload extends TwilioResponsePayload { + source_ip_mappings: SourceIpMappingResource[]; +} + +interface SourceIpMappingResource { + sid: string; + ip_record_sid: string; + sip_domain_sid: string; + date_created: Date; + date_updated: Date; + url: string; +} + +export class SourceIpMappingInstance { + protected _solution: SourceIpMappingContextSolution; + protected _context?: SourceIpMappingContext; + + constructor(protected _version: V1, payload: SourceIpMappingResource, sid?: string) { + + this.sid = (payload.sid); + this.ipRecordSid = (payload.ip_record_sid); + this.sipDomainSid = (payload.sip_domain_sid); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the IP Record resource. + */ + sid: string; + /** + * The Twilio-provided string that uniquely identifies the IP Record resource to map from. + */ + ipRecordSid: string; + /** + * The SID of the SIP Domain that the IP Record is mapped to. + */ + sipDomainSid: string; + /** + * The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateCreated: Date; + /** + * The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): SourceIpMappingContext { + this._context = this._context || new SourceIpMappingContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a SourceIpMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SourceIpMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SourceIpMappingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SourceIpMappingInstance + */ + fetch(callback?: (error: Error | null, item?: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SourceIpMappingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SourceIpMappingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SourceIpMappingInstance>) => any): Promise<ApiResponse<SourceIpMappingInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SourceIpMappingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SourceIpMappingInstance + */ + update(params: SourceIpMappingContextUpdateOptions, callback?: (error: Error | null, item?: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SourceIpMappingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SourceIpMappingInstance with HTTP metadata + */ + updateWithHttpInfo(params: SourceIpMappingContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SourceIpMappingInstance>) => any): Promise<ApiResponse<SourceIpMappingInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SourceIpMappingInstance>) => any): Promise<ApiResponse<SourceIpMappingInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + ipRecordSid: this.ipRecordSid, + sipDomainSid: this.sipDomainSid, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SourceIpMappingSolution { +} + +export interface SourceIpMappingListInstance { + _version: V1; + _solution: SourceIpMappingSolution; + _uri: string; + + (sid: string, ): SourceIpMappingContext; + get(sid: string, ): SourceIpMappingContext; + + + + + + + + + /** + * Create a SourceIpMappingInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SourceIpMappingInstance + */ + create(params: SourceIpMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance>; + + /** + * Create a SourceIpMappingInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SourceIpMappingInstance with HTTP metadata + */ + createWithHttpInfo(params: SourceIpMappingListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<SourceIpMappingInstance>) => any): Promise<ApiResponse<SourceIpMappingInstance>>; + + + + + /** + * Streams SourceIpMappingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SourceIpMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SourceIpMappingInstance, done: (err?: Error) => void) => void): void; + each(params: SourceIpMappingListInstanceEachOptions, callback?: (item: SourceIpMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SourceIpMappingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SourceIpMappingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SourceIpMappingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SourceIpMappingListInstanceEachOptions, callback?: (item: SourceIpMappingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SourceIpMappingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SourceIpMappingPage) => any): Promise<SourceIpMappingPage>; + /** + * Retrieve a single target page of SourceIpMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SourceIpMappingPage>) => any): Promise<ApiResponse<SourceIpMappingPage>>; + /** + * Lists SourceIpMappingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SourceIpMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SourceIpMappingInstance[]) => any): Promise<SourceIpMappingInstance[]>; + list(params: SourceIpMappingListInstanceOptions, callback?: (error: Error | null, items: SourceIpMappingInstance[]) => any): Promise<SourceIpMappingInstance[]>; + /** + * Lists SourceIpMappingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SourceIpMappingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SourceIpMappingInstance[]>) => any): Promise<ApiResponse<SourceIpMappingInstance[]>>; + listWithHttpInfo(params: SourceIpMappingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SourceIpMappingInstance[]>) => any): Promise<ApiResponse<SourceIpMappingInstance[]>>; + /** + * Retrieve a single page of SourceIpMappingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SourceIpMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SourceIpMappingPage) => any): Promise<SourceIpMappingPage>; + page(params: SourceIpMappingListInstancePageOptions, callback?: (error: Error | null, items: SourceIpMappingPage) => any): Promise<SourceIpMappingPage>; + /** + * Retrieve a single page of SourceIpMappingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SourceIpMappingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SourceIpMappingPage>) => any): Promise<ApiResponse<SourceIpMappingPage>>; + pageWithHttpInfo(params: SourceIpMappingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SourceIpMappingPage>) => any): Promise<ApiResponse<SourceIpMappingPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SourceIpMappingListInstance(version: V1): SourceIpMappingListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SourceIpMappingListInstance; + + instance.get = function get(sid, ): SourceIpMappingContext { + return new SourceIpMappingContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/SourceIpMappings`; + + instance.create = function create(params: SourceIpMappingListInstanceCreateOptions, callback?: (error: Error | null, items: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["ipRecordSid"] === null || params["ipRecordSid"] === undefined) { + throw new Error('Required parameter "params[\'ipRecordSid\']" missing.'); + } + + if (params["sipDomainSid"] === null || params["sipDomainSid"] === undefined) { + throw new Error('Required parameter "params[\'sipDomainSid\']" missing.'); + } + + let data: any = {}; + + + + data["IpRecordSid"] = params["ipRecordSid"]; + + data["SipDomainSid"] = params["sipDomainSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SourceIpMappingInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: SourceIpMappingListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<SourceIpMappingInstance>) => any): Promise<ApiResponse<SourceIpMappingInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["ipRecordSid"] === null || params["ipRecordSid"] === undefined) { + throw new Error('Required parameter "params[\'ipRecordSid\']" missing.'); + } + + if (params["sipDomainSid"] === null || params["sipDomainSid"] === undefined) { + throw new Error('Required parameter "params[\'sipDomainSid\']" missing.'); + } + + let data: any = {}; + + + + data["IpRecordSid"] = params["ipRecordSid"]; + + data["SipDomainSid"] = params["sipDomainSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<SourceIpMappingResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SourceIpMappingInstance> => ({ + ...response, + body: new SourceIpMappingInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: SourceIpMappingListInstancePageOptions | ((error: Error | null, items: SourceIpMappingPage) => any), callback?: (error: Error | null, items: SourceIpMappingPage) => any): Promise<SourceIpMappingPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SourceIpMappingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SourceIpMappingPage) => any): Promise<SourceIpMappingPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SourceIpMappingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SourceIpMappingListInstancePageOptions | ((error: Error | null, items: ApiResponse<SourceIpMappingPage>) => any), callback?: (error: Error | null, items: ApiResponse<SourceIpMappingPage>) => any): Promise<ApiResponse<SourceIpMappingPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SourceIpMappingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SourceIpMappingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SourceIpMappingPage>) => any): Promise<ApiResponse<SourceIpMappingPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SourceIpMappingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SourceIpMappingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SourceIpMappingPage extends Page<V1, SourceIpMappingPayload, SourceIpMappingResource, SourceIpMappingInstance> { +/** +* Initialize the SourceIpMappingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SourceIpMappingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SourceIpMappingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SourceIpMappingResource): SourceIpMappingInstance { + + return new SourceIpMappingInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/v2/accountDefaultConfiguration.ts b/rest/voice/v2/accountDefaultConfiguration.ts new file mode 100644 index 000000000..98af531b5 --- /dev/null +++ b/rest/voice/v2/accountDefaultConfiguration.ts @@ -0,0 +1,703 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio API definition for public-api voice + * Powers Twilio public-api voice + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class VoiceV2AccountDefaultConfigurationRequest { + /** + * The description + */ + "description"?: string | null; + "configuration"?: Record<string, object>; + + constructor(payload) { + this.description = payload["description"]; + this.configuration = payload["configuration"]; + } +} + + + +/** + * Options to pass to create a AccountDefaultConfigurationInstance + */ +export interface AccountDefaultConfigurationContextCreateOptions { + /** */ + "voiceV2AccountDefaultConfigurationRequest"?: VoiceV2AccountDefaultConfigurationRequest; +} + + + +/** + * Options to pass to update a AccountDefaultConfigurationInstance + */ +export interface AccountDefaultConfigurationContextUpdateOptions { + /** */ + "voiceV2AccountDefaultConfigurationRequest"?: VoiceV2AccountDefaultConfigurationRequest; +} + +export interface AccountDefaultConfigurationContext { + + /** + * Create a AccountDefaultConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance + */ + create(callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance>; + /** + * Create a AccountDefaultConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance + */ + create(params: VoiceV2AccountDefaultConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance>; + + /** + * Create a AccountDefaultConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>>; + /** + * Create a AccountDefaultConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: VoiceV2AccountDefaultConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>>; + + /** + * Remove a AccountDefaultConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a AccountDefaultConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a AccountDefaultConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance> + + /** + * Fetch a AccountDefaultConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>> + + /** + * Update a AccountDefaultConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance + */ + update(callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance>; + /** + * Update a AccountDefaultConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance + */ + update(params: VoiceV2AccountDefaultConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance>; + + /** + * Update a AccountDefaultConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>>; + /** + * Update a AccountDefaultConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: VoiceV2AccountDefaultConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface AccountDefaultConfigurationContextSolution { + "type": string; +} + +export class AccountDefaultConfigurationContextImpl implements AccountDefaultConfigurationContext { + protected _solution: AccountDefaultConfigurationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, type: string) { + if (!isValidPathParam(type)) { + throw new Error('Parameter \'type\' is not valid.'); + } + + this._solution = { type, }; + this._uri = `/AccountDefaultConfiguration/${type}`; + } + + create(params?: VoiceV2AccountDefaultConfigurationRequest | ((error: Error | null, item?: AccountDefaultConfigurationInstance) => any), headers?: any,callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2AccountDefaultConfigurationRequest> as VoiceV2AccountDefaultConfigurationRequest; + } else { + params = params || {} as Partial<VoiceV2AccountDefaultConfigurationRequest> as VoiceV2AccountDefaultConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new AccountDefaultConfigurationInstance(operationVersion, payload, instance._solution.type)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params?: VoiceV2AccountDefaultConfigurationRequest | ((error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2AccountDefaultConfigurationRequest> as VoiceV2AccountDefaultConfigurationRequest; + } else { + params = params || {} as Partial<VoiceV2AccountDefaultConfigurationRequest> as VoiceV2AccountDefaultConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<AccountDefaultConfigurationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<AccountDefaultConfigurationInstance> => ({ + ...response, + body: new AccountDefaultConfigurationInstance(operationVersion, response.body, instance._solution.type) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new AccountDefaultConfigurationInstance(operationVersion, payload, instance._solution.type)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<AccountDefaultConfigurationResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<AccountDefaultConfigurationInstance> => ({ + ...response, + body: new AccountDefaultConfigurationInstance(operationVersion, response.body, instance._solution.type) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: VoiceV2AccountDefaultConfigurationRequest | ((error: Error | null, item?: AccountDefaultConfigurationInstance) => any), headers?: any,callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2AccountDefaultConfigurationRequest> as VoiceV2AccountDefaultConfigurationRequest; + } else { + params = params || {} as Partial<VoiceV2AccountDefaultConfigurationRequest> as VoiceV2AccountDefaultConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new AccountDefaultConfigurationInstance(operationVersion, payload, instance._solution.type)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: VoiceV2AccountDefaultConfigurationRequest | ((error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2AccountDefaultConfigurationRequest> as VoiceV2AccountDefaultConfigurationRequest; + } else { + params = params || {} as Partial<VoiceV2AccountDefaultConfigurationRequest> as VoiceV2AccountDefaultConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<AccountDefaultConfigurationResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<AccountDefaultConfigurationInstance> => ({ + ...response, + body: new AccountDefaultConfigurationInstance(operationVersion, response.body, instance._solution.type) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface AccountDefaultConfigurationPayload extends AccountDefaultConfigurationResource {} + +interface AccountDefaultConfigurationResource { + account_sid: string; + description: string; + date_created: Date; + date_updated: Date; + configuration: Record<string, object>; + message: string; + code: number; + status: number; + more_info: string; +} + +export class AccountDefaultConfigurationInstance { + protected _solution: AccountDefaultConfigurationContextSolution; + protected _context?: AccountDefaultConfigurationContext; + + constructor(protected _version: V2, payload: AccountDefaultConfigurationResource, type?: string) { + + this.accountSid = (payload.account_sid); + this.description = (payload.description); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.configuration = (payload.configuration); + this.message = (payload.message); + this.code = (payload.code); + this.status = (payload.status); + this.moreInfo = (payload.more_info); + + this._solution = { type: type, }; + } + + /** + * Account sid + */ + accountSid: string; + /** + * The description + */ + description: string; + dateCreated: Date; + dateUpdated: Date; + configuration: Record<string, object>; + /** + * Error message + */ + message: string; + /** + * Twilio error code + */ + code: number; + /** + * status code + */ + status: number; + /** + * More information about the error + */ + moreInfo: string; + + private get _proxy(): AccountDefaultConfigurationContext { + this._context = this._context || new AccountDefaultConfigurationContextImpl(this._version, this._solution.type); + return this._context; + } + + /** + * Create a AccountDefaultConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance + */ + create(callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance>; + /** + * Create a AccountDefaultConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance + */ + create(params: VoiceV2AccountDefaultConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance>; + + create(params?: any, callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance> + { + return this._proxy.create(params, callback); + } + + /** + * Create a AccountDefaultConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>>; + /** + * Create a AccountDefaultConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: VoiceV2AccountDefaultConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Remove a AccountDefaultConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a AccountDefaultConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a AccountDefaultConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance + */ + fetch(callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a AccountDefaultConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a AccountDefaultConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance + */ + update(callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance>; + /** + * Update a AccountDefaultConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance + */ + update(params: VoiceV2AccountDefaultConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance>; + + update(params?: any, callback?: (error: Error | null, item?: AccountDefaultConfigurationInstance) => any): Promise<AccountDefaultConfigurationInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a AccountDefaultConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>>; + /** + * Update a AccountDefaultConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed AccountDefaultConfigurationInstance with HTTP metadata + */ + updateWithHttpInfo(params: VoiceV2AccountDefaultConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<AccountDefaultConfigurationInstance>) => any): Promise<ApiResponse<AccountDefaultConfigurationInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + description: this.description, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + configuration: this.configuration, + message: this.message, + code: this.code, + status: this.status, + moreInfo: this.moreInfo, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface AccountDefaultConfigurationSolution { +} + +export interface AccountDefaultConfigurationListInstance { + _version: V2; + _solution: AccountDefaultConfigurationSolution; + _uri: string; + + (type: string, ): AccountDefaultConfigurationContext; + get(type: string, ): AccountDefaultConfigurationContext; + + + + + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function AccountDefaultConfigurationListInstance(version: V2): AccountDefaultConfigurationListInstance { + const instance = ((type, ) => instance.get(type, )) as AccountDefaultConfigurationListInstance; + + instance.get = function get(type, ): AccountDefaultConfigurationContext { + return new AccountDefaultConfigurationContextImpl(version, type); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/voice/v2/configuration.ts b/rest/voice/v2/configuration.ts new file mode 100644 index 000000000..8bfd3924d --- /dev/null +++ b/rest/voice/v2/configuration.ts @@ -0,0 +1,632 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio API definition for public-api voice + * Powers Twilio public-api voice + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class VoiceV2ConfigurationRequest { + /** + * The unique name + */ + "uniqueName"?: string | null; + /** + * The description + */ + "description"?: string | null; + "configuration"?: Record<string, object>; + + constructor(payload) { + this.uniqueName = payload["unique_name"]; + this.description = payload["description"]; + this.configuration = payload["configuration"]; + } +} + + +export class VoiceV2ConfigurationResponse { + /** + * Configuration Identifier + */ + "id"?: string; + /** + * Account sid + */ + "accountSid"?: string; + /** + * The unique name + */ + "uniqueName"?: string | null; + /** + * The description + */ + "description"?: string | null; + "dateCreated"?: Date; + "dateUpdated"?: Date; + "configuration"?: Record<string, object>; + /** + * The list of Client Configurations + */ + "content"?: Array<VoiceV2ConfigurationResponse>; + "meta"?: VoiceV2PaginatedConfigurationResponseMeta; + + constructor(payload) { + this.id = payload["id"]; + this.accountSid = payload["account_sid"]; + this.uniqueName = payload["unique_name"]; + this.description = payload["description"]; + this.dateCreated = payload["date_created"]; + this.dateUpdated = payload["date_updated"]; + this.configuration = payload["configuration"]; + this.content = payload["content"]; + this.meta = payload["meta"]; + } +} + + +export class VoiceV2PaginatedConfigurationResponseMeta { + "listKey"?: string; + "previousToken"?: string; + "nextToken"?: string; + "directToken"?: boolean; + "pageSize"?: number; + + constructor(payload) { + this.listKey = payload["list_key"]; + this.previousToken = payload["previous_token"]; + this.nextToken = payload["next_token"]; + this.directToken = payload["direct_token"]; + this.pageSize = payload["page_size"]; + } +} + + + +/** + * Options to pass to create a ConfigurationInstance + */ +export interface ConfigurationContextCreateOptions { + /** */ + "voiceV2ConfigurationRequest"?: VoiceV2ConfigurationRequest; +} + +/** + * Options to pass to page a ConfigurationInstance + */ +export interface ConfigurationContextPageOptions { + /** The size of the page. */ + "pageSize"?: number; +} + +export interface ConfigurationContext { + + /** + * Create a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + create(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise<ConfigurationInstance>; + /** + * Create a ConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + create(params: VoiceV2ConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise<ConfigurationInstance>; + + /** + * Create a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConfigurationInstance>) => any): Promise<ApiResponse<ConfigurationInstance>>; + /** + * Create a ConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: VoiceV2ConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ConfigurationInstance>) => any): Promise<ApiResponse<ConfigurationInstance>>; + + /** + * Page a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationPage + */ + page(callback?: (error: Error | null, item?: ConfigurationPage) => any): Promise<ConfigurationPage>; + /** + * Page a ConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + page(params: ConfigurationContextPageOptions, callback?: (error: Error | null, item?: ConfigurationPage) => any): Promise<ConfigurationPage>; + + /** + * Page a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationPage with HTTP metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConfigurationPage>) => any): Promise<ApiResponse<ConfigurationPage>>; + /** + * Page a ConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + pageWithHttpInfo(params: ConfigurationContextPageOptions, callback?: (error: Error | null, item?: ApiResponse<ConfigurationPage>) => any): Promise<ApiResponse<ConfigurationPage>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface ConfigurationContextSolution { + "type": string; +} + +export class ConfigurationContextImpl implements ConfigurationContext { + protected _solution: ConfigurationContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, type: string) { + if (!isValidPathParam(type)) { + throw new Error('Parameter \'type\' is not valid.'); + } + + this._solution = { type, }; + this._uri = `/Configurations/${type}`; + } + + create(params?: VoiceV2ConfigurationRequest | ((error: Error | null, item?: ConfigurationInstance) => any), headers?: any,callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise<ConfigurationInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationRequest> as VoiceV2ConfigurationRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationRequest> as VoiceV2ConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload, instance._solution.type)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + createWithHttpInfo(params?: VoiceV2ConfigurationRequest | ((error: Error | null, item?: ApiResponse<ConfigurationInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<ConfigurationInstance>) => any): Promise<ApiResponse<ConfigurationInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationRequest> as VoiceV2ConfigurationRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationRequest> as VoiceV2ConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<ConfigurationResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<ConfigurationInstance> => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body, instance._solution.type) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + page(params?: ConfigurationContextPageOptions | ((error: Error | null, item?: ConfigurationPage) => any),callback?: (error: Error | null, item?: ConfigurationPage) => any): Promise<ConfigurationPage> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + operationPromise = operationPromise.then(payload => new ConfigurationInstance(operationVersion, payload, instance._solution.type)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + pageWithHttpInfo(params?: ConfigurationContextPageOptions | ((error: Error | null, item?: ApiResponse<ConfigurationPage>) => any),callback?: (error: Error | null, item?: ApiResponse<ConfigurationPage>) => any): Promise<ApiResponse<ConfigurationPage>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + + + + + + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.pageWithResponseInfo<ConfigurationResource>({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<ConfigurationPage> => ({ + ...response, + body: new ConfigurationInstance(operationVersion, response.body, instance._solution.type) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface ConfigurationPayload extends TwilioResponsePayload { + content: ConfigurationResource[]; +} + +interface ConfigurationResource { + id: string; + account_sid: string; + unique_name: string; + description: string; + date_created: Date; + date_updated: Date; + configuration: Record<string, object>; + content: Array<VoiceV2ConfigurationResponse>; + meta: VoiceV2PaginatedConfigurationResponseMeta; +} + +export class ConfigurationInstance { + protected _solution: ConfigurationContextSolution; + protected _context?: ConfigurationContext; + + constructor(protected _version: V2, payload: ConfigurationResource, type?: string) { + + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.uniqueName = (payload.unique_name); + this.description = (payload.description); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.configuration = (payload.configuration); + this.content = payload.content !== null && payload.content !== undefined ? payload.content.map( + (payload: any) => new VoiceV2ConfigurationResponse(payload) + ) : null; + this.meta = payload.meta !== null && payload.meta !== undefined ? new VoiceV2PaginatedConfigurationResponseMeta(payload.meta) : null; + + this._solution = { type: type, }; + } + + /** + * Configuration Identifier + */ + id: string; + /** + * Account sid + */ + accountSid: string; + /** + * The unique name + */ + uniqueName: string; + /** + * The description + */ + description: string; + dateCreated: Date; + dateUpdated: Date; + configuration: Record<string, object>; + /** + * The list of Client Configurations + */ + content: Array<VoiceV2ConfigurationResponse>; + meta: VoiceV2PaginatedConfigurationResponseMeta; + + private get _proxy(): ConfigurationContext { + this._context = this._context || new ConfigurationContextImpl(this._version, this._solution.type); + return this._context; + } + + /** + * Create a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + create(callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise<ConfigurationInstance>; + /** + * Create a ConfigurationInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + create(params: VoiceV2ConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise<ConfigurationInstance>; + + create(params?: any, callback?: (error: Error | null, item?: ConfigurationInstance) => any): Promise<ConfigurationInstance> + { + return this._proxy.create(params, callback); + } + + /** + * Create a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConfigurationInstance>) => any): Promise<ApiResponse<ConfigurationInstance>>; + /** + * Create a ConfigurationInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + createWithHttpInfo(params: VoiceV2ConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<ConfigurationInstance>) => any): Promise<ApiResponse<ConfigurationInstance>>; + + createWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ConfigurationInstance>) => any): Promise<ApiResponse<ConfigurationInstance>> + { + return this._proxy.createWithHttpInfo(params, callback); + } + + /** + * Page a ConfigurationInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationPage + */ + page(callback?: (error: Error | null, item?: ConfigurationPage) => any): Promise<ConfigurationPage>; + /** + * Page a ConfigurationInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance + */ + page(params: ConfigurationContextPageOptions, callback?: (error: Error | null, item?: ConfigurationPage) => any): Promise<ConfigurationPage>; + + page(params?: any, callback?: (error: Error | null, item?: ConfigurationPage) => any): Promise<ConfigurationPage> + { + return this._proxy.page(params, callback); + } + + /** + * Page a ConfigurationInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationPage with HTTP metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<ConfigurationPage>) => any): Promise<ApiResponse<ConfigurationPage>>; + /** + * Page a ConfigurationInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed ConfigurationInstance with HTTP metadata + */ + pageWithHttpInfo(params: ConfigurationContextPageOptions, callback?: (error: Error | null, item?: ApiResponse<ConfigurationPage>) => any): Promise<ApiResponse<ConfigurationPage>>; + + pageWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<ConfigurationPage>) => any): Promise<ApiResponse<ConfigurationPage>> + { + return this._proxy.pageWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + accountSid: this.accountSid, + uniqueName: this.uniqueName, + description: this.description, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + configuration: this.configuration, + content: this.content, + meta: this.meta, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface ConfigurationSolution { +} + +export interface ConfigurationListInstance { + _version: V2; + _solution: ConfigurationSolution; + _uri: string; + + (type: string, ): ConfigurationContext; + get(type: string, ): ConfigurationContext; + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function ConfigurationListInstance(version: V2): ConfigurationListInstance { + const instance = ((type, ) => instance.get(type, )) as ConfigurationListInstance; + + instance.get = function get(type, ): ConfigurationContext { + return new ConfigurationContextImpl(version, type); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class ConfigurationPage extends Page<V2, ConfigurationPayload, ConfigurationResource, ConfigurationInstance> { +/** +* Initialize the ConfigurationPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: ConfigurationSolution) { + super(version, response, solution); + } + + /** + * Build an instance of ConfigurationInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: ConfigurationResource): ConfigurationInstance { + + return new ConfigurationInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/v2/default.ts b/rest/voice/v2/default.ts new file mode 100644 index 000000000..fdae9ac4a --- /dev/null +++ b/rest/voice/v2/default.ts @@ -0,0 +1,413 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio API definition for public-api voice + * Powers Twilio public-api voice + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class DefaultConfigurationRequest { + "configurationId"?: string; + + constructor(payload) { + this.configurationId = payload["configuration_id"]; + } +} + + +export class VoiceV2ConfigurationResponse { + /** + * Configuration Identifier + */ + "id"?: string; + /** + * Account sid + */ + "accountSid"?: string; + /** + * The unique name + */ + "uniqueName"?: string | null; + /** + * The description + */ + "description"?: string | null; + "dateCreated"?: Date; + "dateUpdated"?: Date; + "configuration"?: Record<string, object>; + /** + * The list of Client Configurations + */ + "content"?: Array<VoiceV2ConfigurationResponse>; + "meta"?: VoiceV2PaginatedConfigurationResponseMeta; + + constructor(payload) { + this.id = payload["id"]; + this.accountSid = payload["account_sid"]; + this.uniqueName = payload["unique_name"]; + this.description = payload["description"]; + this.dateCreated = payload["date_created"]; + this.dateUpdated = payload["date_updated"]; + this.configuration = payload["configuration"]; + this.content = payload["content"]; + this.meta = payload["meta"]; + } +} + + +export class VoiceV2PaginatedConfigurationResponseMeta { + "listKey"?: string; + "previousToken"?: string; + "nextToken"?: string; + "directToken"?: boolean; + "pageSize"?: number; + + constructor(payload) { + this.listKey = payload["list_key"]; + this.previousToken = payload["previous_token"]; + this.nextToken = payload["next_token"]; + this.directToken = payload["direct_token"]; + this.pageSize = payload["page_size"]; + } +} + + + +/** + * Options to pass to create a DefaultInstance + */ +export interface DefaultListInstanceCreateOptions { + /** */ + "defaultConfigurationRequest"?: DefaultConfigurationRequest; +} + + + +export interface DefaultSolution { + type: string; +} + +export interface DefaultListInstance { + _version: V2; + _solution: DefaultSolution; + _uri: string; + + + + /** + * Create a DefaultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DefaultInstance + */ + create(callback?: (error: Error | null, item?: DefaultInstance) => any): Promise<DefaultInstance>; + /** + * Create a DefaultInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DefaultInstance + */ + create(params: DefaultConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: DefaultInstance) => any): Promise<DefaultInstance>; + + /** + * Create a DefaultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DefaultInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DefaultInstance>) => any): Promise<ApiResponse<DefaultInstance>>; + /** + * Create a DefaultInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DefaultInstance with HTTP metadata + */ + createWithHttpInfo(params: DefaultConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<DefaultInstance>) => any): Promise<ApiResponse<DefaultInstance>>; + + + + /** + * Fetch a DefaultInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DefaultInstance + */ + fetch(callback?: (error: Error | null, item?: DefaultInstance) => any): Promise<DefaultInstance> + + /** + * Fetch a DefaultInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed DefaultInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<DefaultInstance>) => any): Promise<ApiResponse<DefaultInstance>> + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DefaultListInstance(version: V2, type: string): DefaultListInstance { + if (!isValidPathParam(type)) { + throw new Error('Parameter \'type\' is not valid.'); + } + + const instance = {} as DefaultListInstance; + + instance._version = version; + instance._solution = { type, }; + instance._uri = `/Configurations/${type}/Default`; + + instance.create = function create(params?: DefaultConfigurationRequest | ((error: Error | null, items: DefaultInstance) => any), headers?: any, callback?: (error: Error | null, items: DefaultInstance) => any): Promise<DefaultInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<DefaultConfigurationRequest> as DefaultConfigurationRequest; + } else { + params = params || {} as Partial<DefaultConfigurationRequest> as DefaultConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new DefaultInstance(operationVersion, payload, instance._solution.type)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: DefaultConfigurationRequest | ((error: Error | null, items: ApiResponse<DefaultInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<DefaultInstance>) => any): Promise<ApiResponse<DefaultInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<DefaultConfigurationRequest> as DefaultConfigurationRequest; + } else { + params = params || {} as Partial<DefaultConfigurationRequest> as DefaultConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<DefaultResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<DefaultInstance> => ({ + ...response, + body: new DefaultInstance(operationVersion, response.body, instance._solution.type) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetch = function fetch( callback?: (error: Error | null, items: DefaultInstance) => any): Promise<DefaultInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new DefaultInstance(operationVersion, payload, instance._solution.type)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.fetchWithHttpInfo = function fetchWithHttpInfo( callback?: (error: Error | null, items: ApiResponse<DefaultInstance>) => any): Promise<ApiResponse<DefaultInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<DefaultResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<DefaultInstance> => ({ + ...response, + body: new DefaultInstance(operationVersion, response.body, instance._solution.type) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface DefaultPayload extends DefaultResource {} + +interface DefaultResource { + message: string; + code: number; + status: number; + more_info: string; + id: string; + account_sid: string; + unique_name: string; + description: string; + date_created: Date; + date_updated: Date; + configuration: Record<string, object>; + content: Array<VoiceV2ConfigurationResponse>; + meta: VoiceV2PaginatedConfigurationResponseMeta; +} + +/** + * Twilio error response + */ +export class DefaultInstance { + + constructor(protected _version: V2, payload: DefaultResource, type?: string) { + + this.message = (payload.message); + this.code = (payload.code); + this.status = (payload.status); + this.moreInfo = (payload.more_info); + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.uniqueName = (payload.unique_name); + this.description = (payload.description); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.configuration = (payload.configuration); + this.content = payload.content !== null && payload.content !== undefined ? payload.content.map( + (payload: any) => new VoiceV2ConfigurationResponse(payload) + ) : null; + this.meta = payload.meta !== null && payload.meta !== undefined ? new VoiceV2PaginatedConfigurationResponseMeta(payload.meta) : null; + + } + + /** + * Error message + */ + message: string; + /** + * Twilio error code + */ + code: number; + /** + * status code + */ + status: number; + /** + * More information about the error + */ + moreInfo: string; + /** + * Configuration Identifier + */ + id: string; + /** + * Account sid + */ + accountSid: string; + /** + * The unique name + */ + uniqueName: string; + /** + * The description + */ + description: string; + dateCreated: Date; + dateUpdated: Date; + configuration: Record<string, object>; + /** + * The list of Client Configurations + */ + content: Array<VoiceV2ConfigurationResponse>; + meta: VoiceV2PaginatedConfigurationResponseMeta; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + code: this.code, + status: this.status, + moreInfo: this.moreInfo, + id: this.id, + accountSid: this.accountSid, + uniqueName: this.uniqueName, + description: this.description, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + configuration: this.configuration, + content: this.content, + meta: this.meta, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + diff --git a/rest/voice/v2/recording.ts b/rest/voice/v2/recording.ts new file mode 100644 index 000000000..e72bc463a --- /dev/null +++ b/rest/voice/v2/recording.ts @@ -0,0 +1,1131 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio API definition for public-api voice + * Powers Twilio public-api voice + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The composition configuration for recordings. + */ +export class VoiceV2ConfigurationRecordingCompositionPolicy { + /** + * The number of channels to be composed. + */ + "channels"?: string | null; + /** + * Trim the silence in the recordings. + */ + "trim"?: string | null; + /** + * The audio track to record for the call. + */ + "track"?: string | null; + + constructor(payload) { + this.channels = payload["channels"]; + this.trim = payload["trim"]; + this.track = payload["track"]; + } +} + + +/** + * Configuration for Twilio Voice Recording Service. + */ +export class VoiceV2ConfigurationRecordingConfiguration { + /** + * The configuration type discriminator. Always \"Recording\" for this resource. + */ + "configurationType": string; + "compositionPolicy"?: VoiceV2ConfigurationRecordingCompositionPolicy; + "callRecordingStatusCallback"?: VoiceV2ConfigurationRecordingStatusCallback; + "conferenceRecordingStatusCallback"?: VoiceV2ConfigurationRecordingStatusCallback; + /** + * The features to apply to this recording. + */ + "features"?: Array<VoiceV2ConfigurationRecordingFeature> | null; + + constructor(payload) { + this.configurationType = payload["configurationType"]; + this.compositionPolicy = payload["compositionPolicy"]; + this.callRecordingStatusCallback = payload["callRecordingStatusCallback"]; + this.conferenceRecordingStatusCallback = payload["conferenceRecordingStatusCallback"]; + this.features = payload["features"]; + } +} + + +/** + * A feature to apply to a recording. + */ +export class VoiceV2ConfigurationRecordingFeature { + /** + * The type of feature. + */ + "type": string; + /** + * The ID of the feature. + */ + "featureId": string; + /** + * The description of the feature. + */ + "description"?: string | null; + + constructor(payload) { + this.type = payload["type"]; + this.featureId = payload["featureId"]; + this.description = payload["description"]; + } +} + + +/** + * Request body for creating or updating a Recording Configuration. + */ +export class VoiceV2ConfigurationRecordingRequest { + /** + * The unique name. + */ + "uniqueName"?: string | null; + /** + * The description. + */ + "description"?: string | null; + "configuration": VoiceV2ConfigurationRecordingConfiguration; + + constructor(payload) { + this.uniqueName = payload["unique_name"]; + this.description = payload["description"]; + this.configuration = payload["configuration"]; + } +} + + +/** + * Callback configuration for a recording status. + */ +export class VoiceV2ConfigurationRecordingStatusCallback { + /** + * The recording status callback URL. + */ + "url"?: string | null; + /** + * The recording status callback method. + */ + "method"?: string | null; + /** + * The recording status callback events. + */ + "events"?: Array<string> | null; + + constructor(payload) { + this.url = payload["url"]; + this.method = payload["method"]; + this.events = payload["events"]; + } +} + + +export class VoiceV2ConfigurationResponse { + /** + * Configuration Identifier + */ + "id"?: string; + /** + * Account sid + */ + "accountSid"?: string; + /** + * The unique name + */ + "uniqueName"?: string | null; + /** + * The description + */ + "description"?: string | null; + "dateCreated"?: Date; + "dateUpdated"?: Date; + "configuration"?: Record<string, object>; + /** + * The list of Client Configurations + */ + "content"?: Array<VoiceV2ConfigurationResponse>; + "meta"?: VoiceV2PaginatedConfigurationResponseMeta; + + constructor(payload) { + this.id = payload["id"]; + this.accountSid = payload["account_sid"]; + this.uniqueName = payload["unique_name"]; + this.description = payload["description"]; + this.dateCreated = payload["date_created"]; + this.dateUpdated = payload["date_updated"]; + this.configuration = payload["configuration"]; + this.content = payload["content"]; + this.meta = payload["meta"]; + } +} + + +export class VoiceV2PaginatedConfigurationResponseMeta { + "listKey"?: string; + "previousToken"?: string; + "nextToken"?: string; + "directToken"?: boolean; + "pageSize"?: number; + + constructor(payload) { + this.listKey = payload["list_key"]; + this.previousToken = payload["previous_token"]; + this.nextToken = payload["next_token"]; + this.directToken = payload["direct_token"]; + this.pageSize = payload["page_size"]; + } +} + + + + + +/** + * Options to pass to update a RecordingInstance + */ +export interface RecordingContextUpdateOptions { + /** */ + "voiceV2ConfigurationRecordingRequest"?: VoiceV2ConfigurationRecordingRequest; +} + +/** + * Options to pass to create a RecordingInstance + */ +export interface RecordingListInstanceCreateOptions { + /** */ + "voiceV2ConfigurationRecordingRequest"?: VoiceV2ConfigurationRecordingRequest; +} + +/** + * Options to pass to each + */ +export interface RecordingListInstanceEachOptions { + /** The size of the page. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RecordingInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RecordingListInstanceOptions { + /** The size of the page. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RecordingListInstancePageOptions { + /** The size of the page. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RecordingContext { + + /** + * Remove a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> + + /** + * Update a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance>; + /** + * Update a RecordingInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(params: VoiceV2ConfigurationRecordingRequest, headers?: any, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance>; + + /** + * Update a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>>; + /** + * Update a RecordingInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(params: VoiceV2ConfigurationRecordingRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RecordingContextSolution { + "idOrUniqueName": string; +} + +export class RecordingContextImpl implements RecordingContext { + protected _solution: RecordingContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, idOrUniqueName: string) { + if (!isValidPathParam(idOrUniqueName)) { + throw new Error('Parameter \'idOrUniqueName\' is not valid.'); + } + + this._solution = { idOrUniqueName, }; + this._uri = `/Configurations/Recording/${idOrUniqueName}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.idOrUniqueName)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RecordingResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<RecordingInstance> => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.idOrUniqueName) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: VoiceV2ConfigurationRecordingRequest | ((error: Error | null, item?: RecordingInstance) => any), headers?: any,callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationRecordingRequest> as VoiceV2ConfigurationRecordingRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationRecordingRequest> as VoiceV2ConfigurationRecordingRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload, instance._solution.idOrUniqueName)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: VoiceV2ConfigurationRecordingRequest | ((error: Error | null, item?: ApiResponse<RecordingInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationRecordingRequest> as VoiceV2ConfigurationRecordingRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationRecordingRequest> as VoiceV2ConfigurationRecordingRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<RecordingResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<RecordingInstance> => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body, instance._solution.idOrUniqueName) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RecordingPayload extends TwilioResponsePayload { + content: RecordingResource[]; +} + +interface RecordingResource { + id: string; + account_sid: string; + unique_name: string; + description: string; + date_created: Date; + date_updated: Date; + configuration: VoiceV2ConfigurationRecordingConfiguration; + message: string; + code: number; + status: number; + more_info: string; + content: Array<VoiceV2ConfigurationResponse>; + meta: VoiceV2PaginatedConfigurationResponseMeta; +} + +/** + * Response body for a Recording Configuration. + */ +export class RecordingInstance { + protected _solution: RecordingContextSolution; + protected _context?: RecordingContext; + + constructor(protected _version: V2, payload: RecordingResource, idOrUniqueName?: string) { + + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.uniqueName = (payload.unique_name); + this.description = (payload.description); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.configuration = payload.configuration !== null && payload.configuration !== undefined ? new VoiceV2ConfigurationRecordingConfiguration(payload.configuration) : null; + this.message = (payload.message); + this.code = (payload.code); + this.status = (payload.status); + this.moreInfo = (payload.more_info); + this.content = payload.content !== null && payload.content !== undefined ? payload.content.map( + (payload: any) => new VoiceV2ConfigurationResponse(payload) + ) : null; + this.meta = payload.meta !== null && payload.meta !== undefined ? new VoiceV2PaginatedConfigurationResponseMeta(payload.meta) : null; + + this._solution = { idOrUniqueName: idOrUniqueName, }; + } + + /** + * Configuration Identifier. + */ + id: string; + /** + * Account sid. + */ + accountSid: string; + /** + * The unique name. + */ + uniqueName: string; + /** + * The description. + */ + description: string; + dateCreated: Date; + dateUpdated: Date; + configuration: VoiceV2ConfigurationRecordingConfiguration; + /** + * Error message + */ + message: string; + /** + * Twilio error code + */ + code: number; + /** + * status code + */ + status: number; + /** + * More information about the error + */ + moreInfo: string; + /** + * The list of Client Configurations + */ + content: Array<VoiceV2ConfigurationResponse>; + meta: VoiceV2PaginatedConfigurationResponseMeta; + + private get _proxy(): RecordingContext { + this._context = this._context || new RecordingContextImpl(this._version, this._solution.idOrUniqueName); + return this._context; + } + + /** + * Remove a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + fetch(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance>; + /** + * Update a RecordingInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + update(params: VoiceV2ConfigurationRecordingRequest, headers?: any, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance>; + + update(params?: any, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>>; + /** + * Update a RecordingInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + updateWithHttpInfo(params: VoiceV2ConfigurationRecordingRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + accountSid: this.accountSid, + uniqueName: this.uniqueName, + description: this.description, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + configuration: this.configuration, + message: this.message, + code: this.code, + status: this.status, + moreInfo: this.moreInfo, + content: this.content, + meta: this.meta, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RecordingSolution { +} + +export interface RecordingListInstance { + _version: V2; + _solution: RecordingSolution; + _uri: string; + + (idOrUniqueName: string, ): RecordingContext; + get(idOrUniqueName: string, ): RecordingContext; + + + + + + + + + /** + * Create a RecordingInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + create(callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance>; + /** + * Create a RecordingInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance + */ + create(params: VoiceV2ConfigurationRecordingRequest, headers?: any, callback?: (error: Error | null, item?: RecordingInstance) => any): Promise<RecordingInstance>; + + /** + * Create a RecordingInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>>; + /** + * Create a RecordingInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RecordingInstance with HTTP metadata + */ + createWithHttpInfo(params: VoiceV2ConfigurationRecordingRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>>; + + + + + /** + * Streams RecordingInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + each(params: RecordingListInstanceEachOptions, callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RecordingInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RecordingListInstanceEachOptions, callback?: (item: RecordingInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RecordingInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RecordingPage) => any): Promise<RecordingPage>; + /** + * Retrieve a single target page of RecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RecordingPage>) => any): Promise<ApiResponse<RecordingPage>>; + /** + * Lists RecordingInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RecordingInstance[]) => any): Promise<RecordingInstance[]>; + list(params: RecordingListInstanceOptions, callback?: (error: Error | null, items: RecordingInstance[]) => any): Promise<RecordingInstance[]>; + /** + * Lists RecordingInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RecordingInstance[]>) => any): Promise<ApiResponse<RecordingInstance[]>>; + listWithHttpInfo(params: RecordingListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RecordingInstance[]>) => any): Promise<ApiResponse<RecordingInstance[]>>; + /** + * Retrieve a single page of RecordingInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RecordingPage) => any): Promise<RecordingPage>; + page(params: RecordingListInstancePageOptions, callback?: (error: Error | null, items: RecordingPage) => any): Promise<RecordingPage>; + /** + * Retrieve a single page of RecordingInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RecordingListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RecordingPage>) => any): Promise<ApiResponse<RecordingPage>>; + pageWithHttpInfo(params: RecordingListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RecordingPage>) => any): Promise<ApiResponse<RecordingPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RecordingListInstance(version: V2): RecordingListInstance { + const instance = ((idOrUniqueName, ) => instance.get(idOrUniqueName, )) as RecordingListInstance; + + instance.get = function get(idOrUniqueName, ): RecordingContext { + return new RecordingContextImpl(version, idOrUniqueName); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Configurations/Recording`; + + instance.create = function create(params?: VoiceV2ConfigurationRecordingRequest | ((error: Error | null, items: RecordingInstance) => any), headers?: any, callback?: (error: Error | null, items: RecordingInstance) => any): Promise<RecordingInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationRecordingRequest> as VoiceV2ConfigurationRecordingRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationRecordingRequest> as VoiceV2ConfigurationRecordingRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RecordingInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: VoiceV2ConfigurationRecordingRequest | ((error: Error | null, items: ApiResponse<RecordingInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<RecordingInstance>) => any): Promise<ApiResponse<RecordingInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationRecordingRequest> as VoiceV2ConfigurationRecordingRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationRecordingRequest> as VoiceV2ConfigurationRecordingRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<RecordingResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RecordingInstance> => ({ + ...response, + body: new RecordingInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RecordingListInstancePageOptions | ((error: Error | null, items: RecordingPage) => any), callback?: (error: Error | null, items: RecordingPage) => any): Promise<RecordingPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RecordingPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RecordingPage) => any): Promise<RecordingPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RecordingPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RecordingListInstancePageOptions | ((error: Error | null, items: ApiResponse<RecordingPage>) => any), callback?: (error: Error | null, items: ApiResponse<RecordingPage>) => any): Promise<ApiResponse<RecordingPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RecordingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordingPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RecordingPage>) => any): Promise<ApiResponse<RecordingPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RecordingPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RecordingPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RecordingPage extends Page<V2, RecordingPayload, RecordingResource, RecordingInstance> { +/** +* Initialize the RecordingPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: RecordingSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RecordingInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RecordingResource): RecordingInstance { + + return new RecordingInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/v2/transcription.ts b/rest/voice/v2/transcription.ts new file mode 100644 index 000000000..df499eaba --- /dev/null +++ b/rest/voice/v2/transcription.ts @@ -0,0 +1,1112 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio API definition for public-api voice + * Powers Twilio public-api voice + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class VoiceV2ConfigurationResponse { + /** + * Configuration Identifier + */ + "id"?: string; + /** + * Account sid + */ + "accountSid"?: string; + /** + * The unique name + */ + "uniqueName"?: string | null; + /** + * The description + */ + "description"?: string | null; + "dateCreated"?: Date; + "dateUpdated"?: Date; + "configuration"?: Record<string, object>; + /** + * The list of Client Configurations + */ + "content"?: Array<VoiceV2ConfigurationResponse>; + "meta"?: VoiceV2PaginatedConfigurationResponseMeta; + + constructor(payload) { + this.id = payload["id"]; + this.accountSid = payload["account_sid"]; + this.uniqueName = payload["unique_name"]; + this.description = payload["description"]; + this.dateCreated = payload["date_created"]; + this.dateUpdated = payload["date_updated"]; + this.configuration = payload["configuration"]; + this.content = payload["content"]; + this.meta = payload["meta"]; + } +} + + +/** + * Configuration for Twilio Voice Transcription Service. Either transcriptionStatusCallback or conversationConfigurationId (or both) must be provided. + */ +export class VoiceV2ConfigurationTranscriptionConfiguration { + /** + * The configuration type discriminator. Always \"Transcription\" for this resource. + */ + "configurationType": string; + /** + * The transcription engine provider. Supported values: \'google\', \'deepgram\', \'twilio_managed\'. When using \'twilio_managed\', do not specify a speechModel. + */ + "transcriptionEngine": string; + /** + * The specific speech model to use for transcription. Valid models depend on transcriptionEngine: For \'google\': chirp_2. For \'deepgram\': nova-3, nova-2. For \'twilio_managed\': twilio_managed. + */ + "speechModel"?: string | null; + /** + * Controls how the ASR handles language. Can be a supported BCP-47 language code, or \'multi\' for multilingual code switching (Deepgram engine only). Supported language codes: en-US, en-GB, en-AU, de-DE, fr-FR, it-IT, es-MX, es-ES, es-US, pt-BR, pt-PT, nl-NL, no-NO, pl-PL, sv-SE, da-DK. + */ + "language": string; + "transcriptionStatusCallback"?: VoiceV2ConfigurationTranscriptionStatusCallback; + /** + * The ID of the Maestro Conversations Configuration for transcription storage and optional add-ons. + */ + "conversationConfigurationId"?: string | null; + /** + * Default participant roles and channel mappings for diarization and implicit participant creation. Must include exactly 2 participants mapping audioChannelIndex 1 and 2. + */ + "participantDefaults": Array<VoiceV2ConfigurationTranscriptionParticipantDefault>; + + constructor(payload) { + this.configurationType = payload["configurationType"]; + this.transcriptionEngine = payload["transcriptionEngine"]; + this.speechModel = payload["speechModel"]; + this.language = payload["language"]; + this.transcriptionStatusCallback = payload["transcriptionStatusCallback"]; + this.conversationConfigurationId = payload["conversationConfigurationId"]; + this.participantDefaults = payload["participantDefaults"]; + } +} + + +/** + * Default participant role and channel mapping for diarization and implicit participant creation. + */ +export class VoiceV2ConfigurationTranscriptionParticipantDefault { + /** + * One-based index of the audio channel in a multi-channel recording associated with this role. + */ + "audioChannelIndex": number; + /** + * The participant role to apply when inferring participants. + */ + "type": string; + + constructor(payload) { + this.audioChannelIndex = payload["audioChannelIndex"]; + this.type = payload["type"]; + } +} + + +/** + * Request body for creating or updating a Transcription Configuration. + */ +export class VoiceV2ConfigurationTranscriptionRequest { + /** + * The unique name. + */ + "uniqueName"?: string | null; + /** + * The description. + */ + "description"?: string | null; + "configuration": VoiceV2ConfigurationTranscriptionConfiguration; + + constructor(payload) { + this.uniqueName = payload["unique_name"]; + this.description = payload["description"]; + this.configuration = payload["configuration"]; + } +} + + +/** + * Callback configuration for notifications when transcription is complete. + */ +export class VoiceV2ConfigurationTranscriptionStatusCallback { + /** + * The webhook callback URL. + */ + "url"?: string | null; + /** + * The HTTP method to use for the webhook callback. + */ + "method"?: string | null; + + constructor(payload) { + this.url = payload["url"]; + this.method = payload["method"]; + } +} + + +export class VoiceV2PaginatedConfigurationResponseMeta { + "listKey"?: string; + "previousToken"?: string; + "nextToken"?: string; + "directToken"?: boolean; + "pageSize"?: number; + + constructor(payload) { + this.listKey = payload["list_key"]; + this.previousToken = payload["previous_token"]; + this.nextToken = payload["next_token"]; + this.directToken = payload["direct_token"]; + this.pageSize = payload["page_size"]; + } +} + + + + + +/** + * Options to pass to update a TranscriptionInstance + */ +export interface TranscriptionContextUpdateOptions { + /** */ + "voiceV2ConfigurationTranscriptionRequest"?: VoiceV2ConfigurationTranscriptionRequest; +} + +/** + * Options to pass to create a TranscriptionInstance + */ +export interface TranscriptionListInstanceCreateOptions { + /** */ + "voiceV2ConfigurationTranscriptionRequest"?: VoiceV2ConfigurationTranscriptionRequest; +} + +/** + * Options to pass to each + */ +export interface TranscriptionListInstanceEachOptions { + /** The size of the page. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface TranscriptionListInstanceOptions { + /** The size of the page. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface TranscriptionListInstancePageOptions { + /** The size of the page. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface TranscriptionContext { + + /** + * Remove a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance> + + /** + * Fetch a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>> + + /** + * Update a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + update(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance>; + /** + * Update a TranscriptionInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + update(params: VoiceV2ConfigurationTranscriptionRequest, headers?: any, callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance>; + + /** + * Update a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>>; + /** + * Update a TranscriptionInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + updateWithHttpInfo(params: VoiceV2ConfigurationTranscriptionRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TranscriptionContextSolution { + "idOrUniqueName": string; +} + +export class TranscriptionContextImpl implements TranscriptionContext { + protected _solution: TranscriptionContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, idOrUniqueName: string) { + if (!isValidPathParam(idOrUniqueName)) { + throw new Error('Parameter \'idOrUniqueName\' is not valid.'); + } + + this._solution = { idOrUniqueName, }; + this._uri = `/Configurations/Transcription/${idOrUniqueName}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionInstance(operationVersion, payload, instance._solution.idOrUniqueName)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TranscriptionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TranscriptionInstance> => ({ + ...response, + body: new TranscriptionInstance(operationVersion, response.body, instance._solution.idOrUniqueName) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: VoiceV2ConfigurationTranscriptionRequest | ((error: Error | null, item?: TranscriptionInstance) => any), headers?: any,callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationTranscriptionRequest> as VoiceV2ConfigurationTranscriptionRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationTranscriptionRequest> as VoiceV2ConfigurationTranscriptionRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionInstance(operationVersion, payload, instance._solution.idOrUniqueName)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: VoiceV2ConfigurationTranscriptionRequest | ((error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationTranscriptionRequest> as VoiceV2ConfigurationTranscriptionRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationTranscriptionRequest> as VoiceV2ConfigurationTranscriptionRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<TranscriptionResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<TranscriptionInstance> => ({ + ...response, + body: new TranscriptionInstance(operationVersion, response.body, instance._solution.idOrUniqueName) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TranscriptionPayload extends TwilioResponsePayload { + content: TranscriptionResource[]; +} + +interface TranscriptionResource { + id: string; + account_sid: string; + unique_name: string; + description: string; + date_created: Date; + date_updated: Date; + configuration: VoiceV2ConfigurationTranscriptionConfiguration; + message: string; + code: number; + status: number; + more_info: string; + content: Array<VoiceV2ConfigurationResponse>; + meta: VoiceV2PaginatedConfigurationResponseMeta; +} + +/** + * Response body for a Transcription Configuration. + */ +export class TranscriptionInstance { + protected _solution: TranscriptionContextSolution; + protected _context?: TranscriptionContext; + + constructor(protected _version: V2, payload: TranscriptionResource, idOrUniqueName?: string) { + + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.uniqueName = (payload.unique_name); + this.description = (payload.description); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.configuration = payload.configuration !== null && payload.configuration !== undefined ? new VoiceV2ConfigurationTranscriptionConfiguration(payload.configuration) : null; + this.message = (payload.message); + this.code = (payload.code); + this.status = (payload.status); + this.moreInfo = (payload.more_info); + this.content = payload.content !== null && payload.content !== undefined ? payload.content.map( + (payload: any) => new VoiceV2ConfigurationResponse(payload) + ) : null; + this.meta = payload.meta !== null && payload.meta !== undefined ? new VoiceV2PaginatedConfigurationResponseMeta(payload.meta) : null; + + this._solution = { idOrUniqueName: idOrUniqueName, }; + } + + /** + * Configuration Identifier. + */ + id: string; + /** + * Account sid. + */ + accountSid: string; + /** + * The unique name. + */ + uniqueName: string; + /** + * The description. + */ + description: string; + dateCreated: Date; + dateUpdated: Date; + configuration: VoiceV2ConfigurationTranscriptionConfiguration; + /** + * Error message + */ + message: string; + /** + * Twilio error code + */ + code: number; + /** + * status code + */ + status: number; + /** + * More information about the error + */ + moreInfo: string; + /** + * The list of Client Configurations + */ + content: Array<VoiceV2ConfigurationResponse>; + meta: VoiceV2PaginatedConfigurationResponseMeta; + + private get _proxy(): TranscriptionContext { + this._context = this._context || new TranscriptionContextImpl(this._version, this._solution.idOrUniqueName); + return this._context; + } + + /** + * Remove a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + update(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance>; + /** + * Update a TranscriptionInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + update(params: VoiceV2ConfigurationTranscriptionRequest, headers?: any, callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance>; + + update(params?: any, callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>>; + /** + * Update a TranscriptionInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + updateWithHttpInfo(params: VoiceV2ConfigurationTranscriptionRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + id: this.id, + accountSid: this.accountSid, + uniqueName: this.uniqueName, + description: this.description, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + configuration: this.configuration, + message: this.message, + code: this.code, + status: this.status, + moreInfo: this.moreInfo, + content: this.content, + meta: this.meta, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TranscriptionSolution { +} + +export interface TranscriptionListInstance { + _version: V2; + _solution: TranscriptionSolution; + _uri: string; + + (idOrUniqueName: string, ): TranscriptionContext; + get(idOrUniqueName: string, ): TranscriptionContext; + + + + + + + + + /** + * Create a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + create(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance>; + /** + * Create a TranscriptionInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + create(params: VoiceV2ConfigurationTranscriptionRequest, headers?: any, callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance>; + + /** + * Create a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>>; + /** + * Create a TranscriptionInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + createWithHttpInfo(params: VoiceV2ConfigurationTranscriptionRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>>; + + + + + /** + * Streams TranscriptionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + each(params: TranscriptionListInstanceEachOptions, callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams TranscriptionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: TranscriptionListInstanceEachOptions, callback?: (item: TranscriptionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of TranscriptionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: TranscriptionPage) => any): Promise<TranscriptionPage>; + /** + * Retrieve a single target page of TranscriptionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<TranscriptionPage>) => any): Promise<ApiResponse<TranscriptionPage>>; + /** + * Lists TranscriptionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: TranscriptionInstance[]) => any): Promise<TranscriptionInstance[]>; + list(params: TranscriptionListInstanceOptions, callback?: (error: Error | null, items: TranscriptionInstance[]) => any): Promise<TranscriptionInstance[]>; + /** + * Lists TranscriptionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TranscriptionInstance[]>) => any): Promise<ApiResponse<TranscriptionInstance[]>>; + listWithHttpInfo(params: TranscriptionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<TranscriptionInstance[]>) => any): Promise<ApiResponse<TranscriptionInstance[]>>; + /** + * Retrieve a single page of TranscriptionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: TranscriptionPage) => any): Promise<TranscriptionPage>; + page(params: TranscriptionListInstancePageOptions, callback?: (error: Error | null, items: TranscriptionPage) => any): Promise<TranscriptionPage>; + /** + * Retrieve a single page of TranscriptionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { TranscriptionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<TranscriptionPage>) => any): Promise<ApiResponse<TranscriptionPage>>; + pageWithHttpInfo(params: TranscriptionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<TranscriptionPage>) => any): Promise<ApiResponse<TranscriptionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TranscriptionListInstance(version: V2): TranscriptionListInstance { + const instance = ((idOrUniqueName, ) => instance.get(idOrUniqueName, )) as TranscriptionListInstance; + + instance.get = function get(idOrUniqueName, ): TranscriptionContext { + return new TranscriptionContextImpl(version, idOrUniqueName); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Configurations/Transcription`; + + instance.create = function create(params?: VoiceV2ConfigurationTranscriptionRequest | ((error: Error | null, items: TranscriptionInstance) => any), headers?: any, callback?: (error: Error | null, items: TranscriptionInstance) => any): Promise<TranscriptionInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationTranscriptionRequest> as VoiceV2ConfigurationTranscriptionRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationTranscriptionRequest> as VoiceV2ConfigurationTranscriptionRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: VoiceV2ConfigurationTranscriptionRequest | ((error: Error | null, items: ApiResponse<TranscriptionInstance>) => any), headers?: any, callback?: (error: Error | null, items: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationTranscriptionRequest> as VoiceV2ConfigurationTranscriptionRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationTranscriptionRequest> as VoiceV2ConfigurationTranscriptionRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TranscriptionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TranscriptionInstance> => ({ + ...response, + body: new TranscriptionInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: TranscriptionListInstancePageOptions | ((error: Error | null, items: TranscriptionPage) => any), callback?: (error: Error | null, items: TranscriptionPage) => any): Promise<TranscriptionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new TranscriptionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: TranscriptionPage) => any): Promise<TranscriptionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new TranscriptionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: TranscriptionListInstancePageOptions | ((error: Error | null, items: ApiResponse<TranscriptionPage>) => any), callback?: (error: Error | null, items: ApiResponse<TranscriptionPage>) => any): Promise<ApiResponse<TranscriptionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["pageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<TranscriptionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TranscriptionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<TranscriptionPage>) => any): Promise<ApiResponse<TranscriptionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<TranscriptionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new TranscriptionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class TranscriptionPage extends Page<V2, TranscriptionPayload, TranscriptionResource, TranscriptionInstance> { +/** +* Initialize the TranscriptionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V2, response: Response<string>, solution: TranscriptionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of TranscriptionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: TranscriptionResource): TranscriptionInstance { + + return new TranscriptionInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/voice/v2/type.ts b/rest/voice/v2/type.ts new file mode 100644 index 000000000..bc6a07d57 --- /dev/null +++ b/rest/voice/v2/type.ts @@ -0,0 +1,635 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio API definition for public-api voice + * Powers Twilio public-api voice + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V2 from "../V2"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class VoiceV2ConfigurationRequest { + /** + * The unique name + */ + "uniqueName"?: string | null; + /** + * The description + */ + "description"?: string | null; + "configuration"?: Record<string, object>; + + constructor(payload) { + this.uniqueName = payload["unique_name"]; + this.description = payload["description"]; + this.configuration = payload["configuration"]; + } +} + + +export class VoiceV2ConfigurationResponse { + /** + * Configuration Identifier + */ + "id"?: string; + /** + * Account sid + */ + "accountSid"?: string; + /** + * The unique name + */ + "uniqueName"?: string | null; + /** + * The description + */ + "description"?: string | null; + "dateCreated"?: Date; + "dateUpdated"?: Date; + "configuration"?: Record<string, object>; + /** + * The list of Client Configurations + */ + "content"?: Array<VoiceV2ConfigurationResponse>; + "meta"?: VoiceV2PaginatedConfigurationResponseMeta; + + constructor(payload) { + this.id = payload["id"]; + this.accountSid = payload["account_sid"]; + this.uniqueName = payload["unique_name"]; + this.description = payload["description"]; + this.dateCreated = payload["date_created"]; + this.dateUpdated = payload["date_updated"]; + this.configuration = payload["configuration"]; + this.content = payload["content"]; + this.meta = payload["meta"]; + } +} + + +export class VoiceV2PaginatedConfigurationResponseMeta { + "listKey"?: string; + "previousToken"?: string; + "nextToken"?: string; + "directToken"?: boolean; + "pageSize"?: number; + + constructor(payload) { + this.listKey = payload["list_key"]; + this.previousToken = payload["previous_token"]; + this.nextToken = payload["next_token"]; + this.directToken = payload["direct_token"]; + this.pageSize = payload["page_size"]; + } +} + + + + + +/** + * Options to pass to update a TypeInstance + */ +export interface TypeContextUpdateOptions { + /** */ + "voiceV2ConfigurationRequest"?: VoiceV2ConfigurationRequest; +} + +export interface TypeContext { + + /** + * Remove a TypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a TypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a TypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance + */ + fetch(callback?: (error: Error | null, item?: TypeInstance) => any): Promise<TypeInstance> + + /** + * Fetch a TypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TypeInstance>) => any): Promise<ApiResponse<TypeInstance>> + + /** + * Update a TypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance + */ + update(callback?: (error: Error | null, item?: TypeInstance) => any): Promise<TypeInstance>; + /** + * Update a TypeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance + */ + update(params: VoiceV2ConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: TypeInstance) => any): Promise<TypeInstance>; + + /** + * Update a TypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TypeInstance>) => any): Promise<ApiResponse<TypeInstance>>; + /** + * Update a TypeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance with HTTP metadata + */ + updateWithHttpInfo(params: VoiceV2ConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TypeInstance>) => any): Promise<ApiResponse<TypeInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TypeContextSolution { + "type": string; + "idOrUniqueName": string; +} + +export class TypeContextImpl implements TypeContext { + protected _solution: TypeContextSolution; + protected _uri: string; + + + constructor(protected _version: V2, type: string, idOrUniqueName: string) { + if (!isValidPathParam(type)) { + throw new Error('Parameter \'type\' is not valid.'); + } + + if (!isValidPathParam(idOrUniqueName)) { + throw new Error('Parameter \'idOrUniqueName\' is not valid.'); + } + + this._solution = { type, idOrUniqueName, }; + this._uri = `/Configurations/${type}/${idOrUniqueName}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: TypeInstance) => any): Promise<TypeInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TypeInstance(operationVersion, payload, instance._solution.type, instance._solution.idOrUniqueName)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TypeInstance>) => any): Promise<ApiResponse<TypeInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TypeResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TypeInstance> => ({ + ...response, + body: new TypeInstance(operationVersion, response.body, instance._solution.type, instance._solution.idOrUniqueName) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: VoiceV2ConfigurationRequest | ((error: Error | null, item?: TypeInstance) => any), headers?: any,callback?: (error: Error | null, item?: TypeInstance) => any): Promise<TypeInstance> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationRequest> as VoiceV2ConfigurationRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationRequest> as VoiceV2ConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "put", data, headers}); + + operationPromise = operationPromise.then(payload => new TypeInstance(operationVersion, payload, instance._solution.type, instance._solution.idOrUniqueName)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: VoiceV2ConfigurationRequest | ((error: Error | null, item?: ApiResponse<TypeInstance>) => any), headers?: any,callback?: (error: Error | null, item?: ApiResponse<TypeInstance>) => any): Promise<ApiResponse<TypeInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as Partial<VoiceV2ConfigurationRequest> as VoiceV2ConfigurationRequest; + } else { + params = params || {} as Partial<VoiceV2ConfigurationRequest> as VoiceV2ConfigurationRequest; + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<TypeResource>({ uri: instance._uri, method: "put", data, headers}).then((response) : ApiResponse<TypeInstance> => ({ + ...response, + body: new TypeInstance(operationVersion, response.body, instance._solution.type, instance._solution.idOrUniqueName) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface TypePayload extends TypeResource {} + +interface TypeResource { + message: string; + code: number; + status: number; + more_info: string; + id: string; + account_sid: string; + unique_name: string; + description: string; + date_created: Date; + date_updated: Date; + configuration: Record<string, object>; + content: Array<VoiceV2ConfigurationResponse>; + meta: VoiceV2PaginatedConfigurationResponseMeta; +} + +/** + * Twilio error response + */ +export class TypeInstance { + protected _solution: TypeContextSolution; + protected _context?: TypeContext; + + constructor(protected _version: V2, payload: TypeResource, type?: string, idOrUniqueName?: string) { + + this.message = (payload.message); + this.code = (payload.code); + this.status = (payload.status); + this.moreInfo = (payload.more_info); + this.id = (payload.id); + this.accountSid = (payload.account_sid); + this.uniqueName = (payload.unique_name); + this.description = (payload.description); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.configuration = (payload.configuration); + this.content = payload.content !== null && payload.content !== undefined ? payload.content.map( + (payload: any) => new VoiceV2ConfigurationResponse(payload) + ) : null; + this.meta = payload.meta !== null && payload.meta !== undefined ? new VoiceV2PaginatedConfigurationResponseMeta(payload.meta) : null; + + this._solution = { type: type, idOrUniqueName: idOrUniqueName, }; + } + + /** + * Error message + */ + message: string; + /** + * Twilio error code + */ + code: number; + /** + * status code + */ + status: number; + /** + * More information about the error + */ + moreInfo: string; + /** + * Configuration Identifier + */ + id: string; + /** + * Account sid + */ + accountSid: string; + /** + * The unique name + */ + uniqueName: string; + /** + * The description + */ + description: string; + dateCreated: Date; + dateUpdated: Date; + configuration: Record<string, object>; + /** + * The list of Client Configurations + */ + content: Array<VoiceV2ConfigurationResponse>; + meta: VoiceV2PaginatedConfigurationResponseMeta; + + private get _proxy(): TypeContext { + this._context = this._context || new TypeContextImpl(this._version, this._solution.type, this._solution.idOrUniqueName); + return this._context; + } + + /** + * Remove a TypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a TypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a TypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance + */ + fetch(callback?: (error: Error | null, item?: TypeInstance) => any): Promise<TypeInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TypeInstance>) => any): Promise<ApiResponse<TypeInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a TypeInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance + */ + update(callback?: (error: Error | null, item?: TypeInstance) => any): Promise<TypeInstance>; + /** + * Update a TypeInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance + */ + update(params: VoiceV2ConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: TypeInstance) => any): Promise<TypeInstance>; + + update(params?: any, callback?: (error: Error | null, item?: TypeInstance) => any): Promise<TypeInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a TypeInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TypeInstance>) => any): Promise<ApiResponse<TypeInstance>>; + /** + * Update a TypeInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TypeInstance with HTTP metadata + */ + updateWithHttpInfo(params: VoiceV2ConfigurationRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TypeInstance>) => any): Promise<ApiResponse<TypeInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<TypeInstance>) => any): Promise<ApiResponse<TypeInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + message: this.message, + code: this.code, + status: this.status, + moreInfo: this.moreInfo, + id: this.id, + accountSid: this.accountSid, + uniqueName: this.uniqueName, + description: this.description, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + configuration: this.configuration, + content: this.content, + meta: this.meta, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TypeSolution { +} + +export interface TypeListInstance { + _version: V2; + _solution: TypeSolution; + _uri: string; + + (type: string, idOrUniqueName: string, ): TypeContext; + get(type: string, idOrUniqueName: string, ): TypeContext; + + + + + + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TypeListInstance(version: V2): TypeListInstance { + const instance = ((type, idOrUniqueName, ) => instance.get(type, idOrUniqueName, )) as TypeListInstance; + + instance.get = function get(type, idOrUniqueName, ): TypeContext { + return new TypeContextImpl(version, type, idOrUniqueName); + } + + instance._version = version; + instance._solution = { }; + instance._uri = ``; + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/voice/v3/transcription.ts b/rest/voice/v3/transcription.ts new file mode 100644 index 000000000..160f8d13a --- /dev/null +++ b/rest/voice/v3/transcription.ts @@ -0,0 +1,649 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio API definition for public-api voice + * Powers Twilio public-api voice + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; +import V3 from "../V3"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +export class CreateV3TranscriptionsRequest { + /** + * The ID of the transcription configuration to use + */ + "transcriptionConfigurationId": string; + /** + * Discriminator indicating the input source type + */ + "inputSource"?: string; + /** + * The SID or TTID of the source audio to transcribe (e.g. a Twilio Recording SID). When provided, audioStartedAt is inferred from the recording\'s start time and does not need to be supplied by the caller. + */ + "sourceId": string; + /** + * Participants in the conversation. If omitted or partially specified, defaults from the transcription configuration will be applied. + */ + "participants"?: Array<VoiceV3TranscriptionParticipant>; + /** + * URL to the media file to transcribe + */ + "mediaUrl": string; + /** + * The start time of the audio recording + */ + "audioStartedAt"?: Date; + + constructor(payload) { + this.transcriptionConfigurationId = payload["transcriptionConfigurationId"]; + this.inputSource = payload["inputSource"]; + this.sourceId = payload["sourceId"]; + this.participants = payload["participants"]; + this.mediaUrl = payload["mediaUrl"]; + this.audioStartedAt = payload["audioStartedAt"]; + } +} + + +export class VoiceV3TranscriptionParticipant { + /** + * The role of this participant in the conversation. + */ + "type"?: string; + /** + * The phone number or identifier for this participant (E.164 format for phone numbers). Used to correlate this participant with their profile and conversation history. + */ + "address"?: string; + /** + * User-defined name for this participant + */ + "name"?: string; + /** + * One-based index of the audio channel in a multi-channel recording + */ + "audioChannelIndex": number; + + constructor(payload) { + this.type = payload["type"]; + this.address = payload["address"]; + this.name = payload["name"]; + this.audioChannelIndex = payload["audioChannelIndex"]; + } +} + + +export class VoiceV3TranscriptionResolvedConfiguration { + /** + * The engine used for transcription (Deepgram, Google, or auto) + */ + "transcriptionEngine"?: string; + /** + * The speech model used for transcription (e.g., nova-2, nova-3, chirp_2) + */ + "speechModel"?: string; + /** + * The language code for transcription + */ + "language"?: string; + "transcriptionStatusCallback"?: VoiceV3TranscriptionTranscriptionStatusCallback; + /** + * Maestro conversation configuration ID + */ + "conversationConfigurationId"?: string | null; + /** + * Default participant configurations for the transcription + */ + "participantDefaults"?: Array<VoiceV3TranscriptionResolvedConfigurationParticipantDefaults>; + + constructor(payload) { + this.transcriptionEngine = payload["transcriptionEngine"]; + this.speechModel = payload["speechModel"]; + this.language = payload["language"]; + this.transcriptionStatusCallback = payload["transcriptionStatusCallback"]; + this.conversationConfigurationId = payload["conversationConfigurationId"]; + this.participantDefaults = payload["participantDefaults"]; + } +} + + +export class VoiceV3TranscriptionResolvedConfigurationParticipantDefaults { + /** + * One-based index of the audio channel + */ + "audioChannelIndex": number; + /** + * The participant role type + */ + "type": string; + + constructor(payload) { + this.audioChannelIndex = payload["audioChannelIndex"]; + this.type = payload["type"]; + } +} + + +export class VoiceV3TranscriptionTranscription { + /** + * Unique identifier for a Transcription. This is also the transcriptionId returned in the LRO 202 response. + */ + "id": string; + /** + * Twilio Account SID + */ + "accountId": string; + /** + * The current status of the transcription operation + */ + "status": string; + /** + * Unique identifier for a Transcription configuration. + */ + "transcriptionConfigurationId": string; + /** + * The third party media URL + */ + "mediaUrl"?: string | null; + /** + * The source ID (recording ID) - used for tracking only + */ + "sourceId"?: string | null; + /** + * The call/recording start time. When the transcription was created using a sourceId, this value is inferred from the recording resource\'s start time. When created using a mediaUrl, this reflects the value supplied by the caller. + */ + "audioStartedAt"?: Date; + /** + * Maestro conversation ID, populated once the transcription has been stored in Maestro. + */ + "conversationId"?: string | null; + /** + * Array of participants in the conversation + */ + "participants"?: Array<VoiceV3TranscriptionParticipant>; + /** + * Audio duration in seconds + */ + "duration"?: number | null; + "resolvedConfiguration"?: VoiceV3TranscriptionResolvedConfiguration; + /** + * When this transcript was created + */ + "createdAt": Date; + /** + * When this transcript was last updated + */ + "updatedAt": Date; + /** + * The URL of this resource + */ + "url": string; + + constructor(payload) { + this.id = payload["id"]; + this.accountId = payload["accountId"]; + this.status = payload["status"]; + this.transcriptionConfigurationId = payload["transcriptionConfigurationId"]; + this.mediaUrl = payload["mediaUrl"]; + this.sourceId = payload["sourceId"]; + this.audioStartedAt = payload["audioStartedAt"]; + this.conversationId = payload["conversationId"]; + this.participants = payload["participants"]; + this.duration = payload["duration"]; + this.resolvedConfiguration = payload["resolvedConfiguration"]; + this.createdAt = payload["createdAt"]; + this.updatedAt = payload["updatedAt"]; + this.url = payload["url"]; + } +} + + +export class VoiceV3TranscriptionTranscriptionStatusCallback { + /** + * The URL to call when transcription status changes + */ + "url"?: string; + /** + * The HTTP method to use for the callback, currently only POST is supported + */ + "method"?: string; + /** + * The transcription events that will trigger the callback + */ + "events"?: Array<string> | null; + + constructor(payload) { + this.url = payload["url"]; + this.method = payload["method"]; + this.events = payload["events"]; + } +} + + + + +/** + * Options to pass to create a TranscriptionInstance + */ +export interface TranscriptionListInstanceCreateOptions { + /** */ + "createV3TranscriptionsRequest": CreateV3TranscriptionsRequest; + /** A unique key to ensure idempotency. We recommend using UUID v7. Requests with the same key within the idempotency window return the original response. */ + "idempotencyKey"?: string; +} + +export interface TranscriptionContext { + + /** + * Fetch a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance> + + /** + * Fetch a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface TranscriptionContextSolution { + "transcriptionId": string; +} + +export class TranscriptionContextImpl implements TranscriptionContext { + protected _solution: TranscriptionContextSolution; + protected _uri: string; + + + constructor(protected _version: V3, transcriptionId: string) { + if (!isValidPathParam(transcriptionId)) { + throw new Error('Parameter \'transcriptionId\' is not valid.'); + } + + this._solution = { transcriptionId, }; + this._uri = `/Transcriptions/${transcriptionId}`; + } + + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionInstance(operationVersion, payload, instance._solution.transcriptionId)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<TranscriptionResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<TranscriptionInstance> => ({ + ...response, + body: new TranscriptionInstance(operationVersion, response.body, instance._solution.transcriptionId) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} +/** + * Nested model for CreateV3TranscriptionsRequest + */ +export interface CreateV3TranscriptionsRequest { + transcriptionConfigurationId: string; + inputSource?: string; + sourceId: string; + participants?: Array<VoiceV3TranscriptionParticipant>; + mediaUrl: string; + audioStartedAt?: Date; +} + +/** + * Nested model for VoiceV3TranscriptionParticipant + */ +export interface VoiceV3TranscriptionParticipant { + type?: string; + address?: string; + name?: string; + audioChannelIndex: number; +} + +/** + * Nested model for VoiceV3TranscriptionResolvedConfiguration + */ +export interface VoiceV3TranscriptionResolvedConfiguration { + transcriptionEngine?: string; + speechModel?: string; + language?: string; + transcriptionStatusCallback?: VoiceV3TranscriptionTranscriptionStatusCallback; + conversationConfigurationId?: string; + participantDefaults?: Array<VoiceV3TranscriptionResolvedConfigurationParticipantDefaults>; +} + +/** + * Nested model for VoiceV3TranscriptionResolvedConfigurationParticipantDefaults + */ +export interface VoiceV3TranscriptionResolvedConfigurationParticipantDefaults { + audioChannelIndex: number; + type: string; +} + +/** + * Nested model for VoiceV3TranscriptionTranscription + */ +export interface VoiceV3TranscriptionTranscription { + id: string; + accountId: string; + status: string; + transcriptionConfigurationId: string; + mediaUrl?: string; + sourceId?: string; + audioStartedAt?: Date; + conversationId?: string; + participants?: Array<VoiceV3TranscriptionParticipant>; + duration?: number; + resolvedConfiguration?: VoiceV3TranscriptionResolvedConfiguration; + createdAt: Date; + updatedAt: Date; + url: string; +} + +/** + * Nested model for VoiceV3TranscriptionTranscriptionStatusCallback + */ +export interface VoiceV3TranscriptionTranscriptionStatusCallback { + url?: string; + method?: string; + events?: Array<string>; +} + + + + + +/** + * Response model for VoiceV3TranscriptionLongRunningOperation202Response operations + */ +interface VoiceV3TranscriptionLongRunningOperation202Response_ResponseResource { + status: string; + statusUrl: string; + transcription: VoiceV3TranscriptionTranscription; +} + +/** + * Response model for VoiceV3TranscriptionLongRunningOperationResponse operations + */ +interface VoiceV3TranscriptionLongRunningOperationResponse_ResponseResource { + operationId: string; + status: string; + statusUrl: string; + transcription: VoiceV3TranscriptionTranscription; +} + +/** + * Union type for all possible response models + */ +type TranscriptionResource = VoiceV3TranscriptionLongRunningOperation202Response_ResponseResource | VoiceV3TranscriptionLongRunningOperationResponse_ResponseResource; + +/** + * Response envelope for long-running operations (202 Accepted pattern). Returned immediately on acceptance and on each status poll. Extensible to allow additional fields in future versions. + */ +export class TranscriptionInstance { + protected _solution: TranscriptionContextSolution; + protected _context?: TranscriptionContext; + + constructor(protected _version: V3, _payload: TranscriptionResource, transcriptionId?: string) { + const payload: any = _payload; + this.status = (payload.status); + this.statusUrl = (payload.statusUrl); + this.transcription = payload.transcription !== null && payload.transcription !== undefined ? new VoiceV3TranscriptionTranscription(payload.transcription) : null; + this.operationId = (payload.operationId); + + this._solution = { transcriptionId: transcriptionId, }; + } + + /** + * Current status of the long-running operation. PENDING: accepted but not yet started. RUNNING: currently in progress. COMPLETED: successfully completed. FAILED: failed and cannot be completed. + */ + status?: string; + /** + * URI to poll for operation status. Mirrors the Location response header. Provided as a body field for programmatic access by JSON-parsing clients (RFC 9110 Section 15.3.3). + */ + statusUrl?: string; + transcription?: VoiceV3TranscriptionTranscription; + /** + * Unique identifier for the transcription operation. + */ + operationId?: string; + + private get _proxy(): TranscriptionContext { + this._context = this._context || new TranscriptionContextImpl(this._version, this._solution.transcriptionId); + return this._context; + } + + /** + * Fetch a TranscriptionInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + fetch(callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a TranscriptionInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + status: this.status, + statusUrl: this.statusUrl, + transcription: this.transcription, + operationId: this.operationId, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface TranscriptionSolution { +} + +export interface TranscriptionListInstance { + _version: V3; + _solution: TranscriptionSolution; + _uri: string; + + (transcriptionId: string, ): TranscriptionContext; + get(transcriptionId: string, ): TranscriptionContext; + + + + + /** + * Create a TranscriptionInstance + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance + */ + create(params: CreateV3TranscriptionsRequest, headers?: any, callback?: (error: Error | null, item?: TranscriptionInstance) => any): Promise<TranscriptionInstance>; + + /** + * Create a TranscriptionInstance and return HTTP info + * + * @param params - Body for request + * @param headers - header params for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed TranscriptionInstance with HTTP metadata + */ + createWithHttpInfo(params: CreateV3TranscriptionsRequest, headers?: any, callback?: (error: Error | null, item?: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>>; + + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function TranscriptionListInstance(version: V3): TranscriptionListInstance { + const instance = ((transcriptionId, ) => instance.get(transcriptionId, )) as TranscriptionListInstance; + + instance.get = function get(transcriptionId, ): TranscriptionContext { + return new TranscriptionContextImpl(version, transcriptionId); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Transcriptions`; + + instance.create = function create(params: CreateV3TranscriptionsRequest, headers?: any, callback?: (error: Error | null, items: TranscriptionInstance) => any): Promise<TranscriptionInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new TranscriptionInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CreateV3TranscriptionsRequest, headers?: any, callback?: (error: Error | null, items: ApiResponse<TranscriptionInstance>) => any): Promise<ApiResponse<TranscriptionInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + let data: any = {}; + + + + data = params + + if(headers === null || headers === undefined) { + headers = {}; + } + + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<TranscriptionResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<TranscriptionInstance> => ({ + ...response, + body: new TranscriptionInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + diff --git a/rest/wireless/V1.ts b/rest/wireless/V1.ts new file mode 100644 index 000000000..1a0180b19 --- /dev/null +++ b/rest/wireless/V1.ts @@ -0,0 +1,65 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Wireless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import WirelessBase from "../WirelessBase"; +import Version from "../../base/Version"; +import { CommandListInstance } from "./v1/command"; +import { RatePlanListInstance } from "./v1/ratePlan"; +import { SimListInstance } from "./v1/sim"; +import { UsageRecordListInstance } from "./v1/usageRecord"; + +export default class V1 extends Version { + /** + * Initialize the V1 version of Wireless + * + * @param domain - The Twilio (Twilio.Wireless) domain + */ + constructor(domain: WirelessBase) { + super(domain, "v1"); + } + + /** commands - { Twilio.Wireless.V1.CommandListInstance } resource */ + protected _commands?: CommandListInstance; + /** ratePlans - { Twilio.Wireless.V1.RatePlanListInstance } resource */ + protected _ratePlans?: RatePlanListInstance; + /** sims - { Twilio.Wireless.V1.SimListInstance } resource */ + protected _sims?: SimListInstance; + /** usageRecords - { Twilio.Wireless.V1.UsageRecordListInstance } resource */ + protected _usageRecords?: UsageRecordListInstance; + + /** Getter for commands resource */ + get commands(): CommandListInstance { + this._commands = this._commands || CommandListInstance(this); + return this._commands; + } + + /** Getter for ratePlans resource */ + get ratePlans(): RatePlanListInstance { + this._ratePlans = this._ratePlans || RatePlanListInstance(this); + return this._ratePlans; + } + + /** Getter for sims resource */ + get sims(): SimListInstance { + this._sims = this._sims || SimListInstance(this); + return this._sims; + } + + /** Getter for usageRecords resource */ + get usageRecords(): UsageRecordListInstance { + this._usageRecords = this._usageRecords || UsageRecordListInstance(this); + return this._usageRecords; + } + +} diff --git a/rest/wireless/v1/command.ts b/rest/wireless/v1/command.ts new file mode 100644 index 000000000..5eecd7824 --- /dev/null +++ b/rest/wireless/v1/command.ts @@ -0,0 +1,854 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Wireless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The mode used to send the SMS message. Can be: `text` or `binary`. The default SMS mode is `text`. + */ +export type CommandCommandMode = 'text'|'binary'; + +/** + * The direction of the Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + */ +export type CommandDirection = 'from_sim'|'to_sim'; + +/** + * The status of the Command. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. See [Status Values](https://www.twilio.com/docs/iot/wireless/api/command-resource#status-values) for a description of each state. + */ +export type CommandStatus = 'queued'|'sent'|'delivered'|'received'|'failed'; + +/** + * The type of transport used. Can be: `sms` or `ip`. + */ +export type CommandTransport = 'sms'|'ip'; + + + + +/** + * Options to pass to create a CommandInstance + */ +export interface CommandListInstanceCreateOptions { + /** The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. */ + "command": string; + /** The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. */ + "sim"?: string; + /** The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. */ + "callbackMethod"?: string; + /** The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. */ + "callbackUrl"?: string; + /** */ + "commandMode"?: CommandCommandMode; + /** Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. */ + "includeSid"?: string; + /** Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to \\\'delivered\\\' once the server has received a delivery receipt from the device. The default value is `true`. */ + "deliveryReceiptRequested"?: boolean; +} + +/** + * Options to pass to each + */ +export interface CommandListInstanceEachOptions { + /** The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. */ + "sim"?: string; + /** The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. */ + "status"?: CommandStatus; + /** Only return Commands with this direction value. */ + "direction"?: CommandDirection; + /** Only return Commands with this transport value. Can be: `sms` or `ip`. */ + "transport"?: CommandTransport; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: CommandInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface CommandListInstanceOptions { + /** The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. */ + "sim"?: string; + /** The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. */ + "status"?: CommandStatus; + /** Only return Commands with this direction value. */ + "direction"?: CommandDirection; + /** Only return Commands with this transport value. Can be: `sms` or `ip`. */ + "transport"?: CommandTransport; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface CommandListInstancePageOptions { + /** The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. */ + "sim"?: string; + /** The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. */ + "status"?: CommandStatus; + /** Only return Commands with this direction value. */ + "direction"?: CommandDirection; + /** Only return Commands with this transport value. Can be: `sms` or `ip`. */ + "transport"?: CommandTransport; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface CommandContext { + + /** + * Remove a CommandInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a CommandInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a CommandInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance + */ + fetch(callback?: (error: Error | null, item?: CommandInstance) => any): Promise<CommandInstance> + + /** + * Fetch a CommandInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CommandInstance>) => any): Promise<ApiResponse<CommandInstance>> + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface CommandContextSolution { + "sid": string; +} + +export class CommandContextImpl implements CommandContext { + protected _solution: CommandContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Commands/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: CommandInstance) => any): Promise<CommandInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new CommandInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CommandInstance>) => any): Promise<ApiResponse<CommandInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<CommandResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<CommandInstance> => ({ + ...response, + body: new CommandInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface CommandPayload extends TwilioResponsePayload { + commands: CommandResource[]; +} + +interface CommandResource { + sid: string; + account_sid: string; + sim_sid: string; + command: string; + command_mode: CommandCommandMode; + transport: CommandTransport; + delivery_receipt_requested: boolean; + status: CommandStatus; + direction: CommandDirection; + date_created: Date; + date_updated: Date; + url: string; +} + +export class CommandInstance { + protected _solution: CommandContextSolution; + protected _context?: CommandContext; + + constructor(protected _version: V1, payload: CommandResource, sid?: string) { + + this.sid = (payload.sid); + this.accountSid = (payload.account_sid); + this.simSid = (payload.sim_sid); + this.command = (payload.command); + this.commandMode = payload.command_mode; + this.transport = payload.transport; + this.deliveryReceiptRequested = (payload.delivery_receipt_requested); + this.status = payload.status; + this.direction = payload.direction; + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Command resource. + */ + sid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Command resource. + */ + accountSid: string; + /** + * The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that the Command was sent to or from. + */ + simSid: string; + /** + * The message being sent to or from the SIM. For text mode messages, this can be up to 160 characters. For binary mode messages, this is a series of up to 140 bytes of data encoded using base64. + */ + command: string; + commandMode: CommandCommandMode; + transport: CommandTransport; + /** + * Whether to request a delivery receipt. + */ + deliveryReceiptRequested: boolean; + status: CommandStatus; + direction: CommandDirection; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): CommandContext { + this._context = this._context || new CommandContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a CommandInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a CommandInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a CommandInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance + */ + fetch(callback?: (error: Error | null, item?: CommandInstance) => any): Promise<CommandInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a CommandInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<CommandInstance>) => any): Promise<ApiResponse<CommandInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + accountSid: this.accountSid, + simSid: this.simSid, + command: this.command, + commandMode: this.commandMode, + transport: this.transport, + deliveryReceiptRequested: this.deliveryReceiptRequested, + status: this.status, + direction: this.direction, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface CommandSolution { +} + +export interface CommandListInstance { + _version: V1; + _solution: CommandSolution; + _uri: string; + + (sid: string, ): CommandContext; + get(sid: string, ): CommandContext; + + + + + + + /** + * Create a CommandInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance + */ + create(params: CommandListInstanceCreateOptions, callback?: (error: Error | null, item?: CommandInstance) => any): Promise<CommandInstance>; + + /** + * Create a CommandInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed CommandInstance with HTTP metadata + */ + createWithHttpInfo(params: CommandListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<CommandInstance>) => any): Promise<ApiResponse<CommandInstance>>; + + + + + /** + * Streams CommandInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: CommandInstance, done: (err?: Error) => void) => void): void; + each(params: CommandListInstanceEachOptions, callback?: (item: CommandInstance, done: (err?: Error) => void) => void): void; + /** + * Streams CommandInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: CommandInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: CommandListInstanceEachOptions, callback?: (item: CommandInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of CommandInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: CommandPage) => any): Promise<CommandPage>; + /** + * Retrieve a single target page of CommandInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<CommandPage>) => any): Promise<ApiResponse<CommandPage>>; + /** + * Lists CommandInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: CommandInstance[]) => any): Promise<CommandInstance[]>; + list(params: CommandListInstanceOptions, callback?: (error: Error | null, items: CommandInstance[]) => any): Promise<CommandInstance[]>; + /** + * Lists CommandInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CommandInstance[]>) => any): Promise<ApiResponse<CommandInstance[]>>; + listWithHttpInfo(params: CommandListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<CommandInstance[]>) => any): Promise<ApiResponse<CommandInstance[]>>; + /** + * Retrieve a single page of CommandInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: CommandPage) => any): Promise<CommandPage>; + page(params: CommandListInstancePageOptions, callback?: (error: Error | null, items: CommandPage) => any): Promise<CommandPage>; + /** + * Retrieve a single page of CommandInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { CommandListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<CommandPage>) => any): Promise<ApiResponse<CommandPage>>; + pageWithHttpInfo(params: CommandListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<CommandPage>) => any): Promise<ApiResponse<CommandPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function CommandListInstance(version: V1): CommandListInstance { + const instance = ((sid, ) => instance.get(sid, )) as CommandListInstance; + + instance.get = function get(sid, ): CommandContext { + return new CommandContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Commands`; + + instance.create = function create(params: CommandListInstanceCreateOptions, callback?: (error: Error | null, items: CommandInstance) => any): Promise<CommandInstance> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["command"] === null || params["command"] === undefined) { + throw new Error('Required parameter "params[\'command\']" missing.'); + } + + let data: any = {}; + + + + data["Command"] = params["command"]; + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["commandMode"] !== undefined) + data["CommandMode"] = params["commandMode"]; + if (params["includeSid"] !== undefined) + data["IncludeSid"] = params["includeSid"]; + if (params["deliveryReceiptRequested"] !== undefined) + data["DeliveryReceiptRequested"] = serialize.bool(params["deliveryReceiptRequested"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new CommandInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params: CommandListInstanceCreateOptions, callback?: (error: Error | null, items: ApiResponse<CommandInstance>) => any): Promise<ApiResponse<CommandInstance>> { + if (params === null || params === undefined) { + throw new Error('Required parameter "params" missing.'); + } + + if (params["command"] === null || params["command"] === undefined) { + throw new Error('Required parameter "params[\'command\']" missing.'); + } + + let data: any = {}; + + + + data["Command"] = params["command"]; + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["commandMode"] !== undefined) + data["CommandMode"] = params["commandMode"]; + if (params["includeSid"] !== undefined) + data["IncludeSid"] = params["includeSid"]; + if (params["deliveryReceiptRequested"] !== undefined) + data["DeliveryReceiptRequested"] = serialize.bool(params["deliveryReceiptRequested"]); + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<CommandResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<CommandInstance> => ({ + ...response, + body: new CommandInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: CommandListInstancePageOptions | ((error: Error | null, items: CommandPage) => any), callback?: (error: Error | null, items: CommandPage) => any): Promise<CommandPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["transport"] !== undefined) + data["Transport"] = params["transport"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new CommandPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: CommandPage) => any): Promise<CommandPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new CommandPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: CommandListInstancePageOptions | ((error: Error | null, items: ApiResponse<CommandPage>) => any), callback?: (error: Error | null, items: ApiResponse<CommandPage>) => any): Promise<ApiResponse<CommandPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["sim"] !== undefined) + data["Sim"] = params["sim"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["direction"] !== undefined) + data["Direction"] = params["direction"]; + if (params["transport"] !== undefined) + data["Transport"] = params["transport"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<CommandPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CommandPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<CommandPage>) => any): Promise<ApiResponse<CommandPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<CommandPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new CommandPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class CommandPage extends Page<V1, CommandPayload, CommandResource, CommandInstance> { +/** +* Initialize the CommandPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: CommandSolution) { + super(version, response, solution); + } + + /** + * Build an instance of CommandInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: CommandResource): CommandInstance { + + return new CommandInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/wireless/v1/ratePlan.ts b/rest/wireless/v1/ratePlan.ts new file mode 100644 index 000000000..ea31bca66 --- /dev/null +++ b/rest/wireless/v1/ratePlan.ts @@ -0,0 +1,1050 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Wireless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * The way the home network (T-Mobile USA) will behave after a SIM\'s usage exceeds its `data_limit`. Can be either `block` or `throttle`. Default is `block`. + */ +export type RatePlanDataLimitStrategy = 'block'|'throttle'; + + + + +/** + * Options to pass to update a RatePlanInstance + */ +export interface RatePlanContextUpdateOptions { + /** An application-defined string that uniquely identifies the resource. It can be used in place of the resource\\\'s `sid` in the URL to address the resource. */ + "uniqueName"?: string; + /** A descriptive string that you create to describe the resource. It does not have to be unique. */ + "friendlyName"?: string; +} + +/** + * Options to pass to create a RatePlanInstance + */ +export interface RatePlanListInstanceCreateOptions { + /** An application-defined string that uniquely identifies the resource. It can be used in place of the resource\\\'s `sid` in the URL to address the resource. */ + "uniqueName"?: string; + /** A descriptive string that you create to describe the resource. It does not have to be unique. */ + "friendlyName"?: string; + /** Whether SIMs can use GPRS/3G/4G/LTE data connectivity. */ + "dataEnabled"?: boolean; + /** The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. */ + "dataLimit"?: number; + /** The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). */ + "dataMetering"?: string; + /** Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). */ + "messagingEnabled"?: boolean; + /** Deprecated. */ + "voiceEnabled"?: boolean; + /** Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). */ + "nationalRoamingEnabled"?: boolean; + /** The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. */ + "internationalRoaming"?: Array<string>; + /** The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. */ + "nationalRoamingDataLimit"?: number; + /** The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. */ + "internationalRoamingDataLimit"?: number; + /** */ + "dataLimitStrategy"?: RatePlanDataLimitStrategy; +} + +/** + * Options to pass to each + */ +export interface RatePlanListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: RatePlanInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface RatePlanListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface RatePlanListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface RatePlanContext { + + /** + * Remove a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + fetch(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance> + + /** + * Fetch a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> + + /** + * Update a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + update(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + /** + * Update a RatePlanInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + update(params: RatePlanContextUpdateOptions, callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + + /** + * Update a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + /** + * Update a RatePlanInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + updateWithHttpInfo(params: RatePlanContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface RatePlanContextSolution { + "sid": string; +} + +export class RatePlanContextImpl implements RatePlanContext { + protected _solution: RatePlanContextSolution; + protected _uri: string; + + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/RatePlans/${sid}`; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new RatePlanInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<RatePlanResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<RatePlanInstance> => ({ + ...response, + body: new RatePlanInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: RatePlanContextUpdateOptions | ((error: Error | null, item?: RatePlanInstance) => any),callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RatePlanInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: RatePlanContextUpdateOptions | ((error: Error | null, item?: ApiResponse<RatePlanInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<RatePlanResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RatePlanInstance> => ({ + ...response, + body: new RatePlanInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface RatePlanPayload extends TwilioResponsePayload { + rate_plans: RatePlanResource[]; +} + +interface RatePlanResource { + sid: string; + unique_name: string; + account_sid: string; + friendly_name: string; + data_enabled: boolean; + data_metering: string; + data_limit: number; + messaging_enabled: boolean; + voice_enabled: boolean; + national_roaming_enabled: boolean; + national_roaming_data_limit: number; + international_roaming: Array<string>; + international_roaming_data_limit: number; + date_created: Date; + date_updated: Date; + url: string; +} + +export class RatePlanInstance { + protected _solution: RatePlanContextSolution; + protected _context?: RatePlanContext; + + constructor(protected _version: V1, payload: RatePlanResource, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.friendlyName = (payload.friendly_name); + this.dataEnabled = (payload.data_enabled); + this.dataMetering = (payload.data_metering); + this.dataLimit = deserialize.integer(payload.data_limit); + this.messagingEnabled = (payload.messaging_enabled); + this.voiceEnabled = (payload.voice_enabled); + this.nationalRoamingEnabled = (payload.national_roaming_enabled); + this.nationalRoamingDataLimit = deserialize.integer(payload.national_roaming_data_limit); + this.internationalRoaming = (payload.international_roaming); + this.internationalRoamingDataLimit = deserialize.integer(payload.international_roaming_data_limit); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the RatePlan resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. + */ + uniqueName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RatePlan resource. + */ + accountSid: string; + /** + * The string that you assigned to describe the resource. + */ + friendlyName: string; + /** + * Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + */ + dataEnabled: boolean; + /** + * The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + */ + dataMetering: string; + /** + * The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. + */ + dataLimit: number; + /** + * Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + */ + messagingEnabled: boolean; + /** + * Deprecated. Whether SIMs can make and receive voice calls. + */ + voiceEnabled: boolean; + /** + * Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + */ + nationalRoamingEnabled: boolean; + /** + * The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. + */ + nationalRoamingDataLimit: number; + /** + * The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + */ + internationalRoaming: Array<string>; + /** + * The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + */ + internationalRoamingDataLimit: number; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + + private get _proxy(): RatePlanContext { + this._context = this._context || new RatePlanContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + fetch(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + update(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + /** + * Update a RatePlanInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + update(params: RatePlanContextUpdateOptions, callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + + update(params?: any, callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + /** + * Update a RatePlanInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + updateWithHttpInfo(params: RatePlanContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + friendlyName: this.friendlyName, + dataEnabled: this.dataEnabled, + dataMetering: this.dataMetering, + dataLimit: this.dataLimit, + messagingEnabled: this.messagingEnabled, + voiceEnabled: this.voiceEnabled, + nationalRoamingEnabled: this.nationalRoamingEnabled, + nationalRoamingDataLimit: this.nationalRoamingDataLimit, + internationalRoaming: this.internationalRoaming, + internationalRoamingDataLimit: this.internationalRoamingDataLimit, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface RatePlanSolution { +} + +export interface RatePlanListInstance { + _version: V1; + _solution: RatePlanSolution; + _uri: string; + + (sid: string, ): RatePlanContext; + get(sid: string, ): RatePlanContext; + + + + + + + + + /** + * Create a RatePlanInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + create(callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + /** + * Create a RatePlanInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance + */ + create(params: RatePlanListInstanceCreateOptions, callback?: (error: Error | null, item?: RatePlanInstance) => any): Promise<RatePlanInstance>; + + /** + * Create a RatePlanInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + createWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + /** + * Create a RatePlanInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed RatePlanInstance with HTTP metadata + */ + createWithHttpInfo(params: RatePlanListInstanceCreateOptions, callback?: (error: Error | null, item?: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>>; + + + + + /** + * Streams RatePlanInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: RatePlanInstance, done: (err?: Error) => void) => void): void; + each(params: RatePlanListInstanceEachOptions, callback?: (item: RatePlanInstance, done: (err?: Error) => void) => void): void; + /** + * Streams RatePlanInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: RatePlanInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: RatePlanListInstanceEachOptions, callback?: (item: RatePlanInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of RatePlanInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: RatePlanPage) => any): Promise<RatePlanPage>; + /** + * Retrieve a single target page of RatePlanInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<RatePlanPage>) => any): Promise<ApiResponse<RatePlanPage>>; + /** + * Lists RatePlanInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: RatePlanInstance[]) => any): Promise<RatePlanInstance[]>; + list(params: RatePlanListInstanceOptions, callback?: (error: Error | null, items: RatePlanInstance[]) => any): Promise<RatePlanInstance[]>; + /** + * Lists RatePlanInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RatePlanInstance[]>) => any): Promise<ApiResponse<RatePlanInstance[]>>; + listWithHttpInfo(params: RatePlanListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<RatePlanInstance[]>) => any): Promise<ApiResponse<RatePlanInstance[]>>; + /** + * Retrieve a single page of RatePlanInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: RatePlanPage) => any): Promise<RatePlanPage>; + page(params: RatePlanListInstancePageOptions, callback?: (error: Error | null, items: RatePlanPage) => any): Promise<RatePlanPage>; + /** + * Retrieve a single page of RatePlanInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { RatePlanListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<RatePlanPage>) => any): Promise<ApiResponse<RatePlanPage>>; + pageWithHttpInfo(params: RatePlanListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<RatePlanPage>) => any): Promise<ApiResponse<RatePlanPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function RatePlanListInstance(version: V1): RatePlanListInstance { + const instance = ((sid, ) => instance.get(sid, )) as RatePlanListInstance; + + instance.get = function get(sid, ): RatePlanContext { + return new RatePlanContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/RatePlans`; + + instance.create = function create(params?: RatePlanListInstanceCreateOptions | ((error: Error | null, items: RatePlanInstance) => any), callback?: (error: Error | null, items: RatePlanInstance) => any): Promise<RatePlanInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["dataEnabled"] !== undefined) + data["DataEnabled"] = serialize.bool(params["dataEnabled"]); + if (params["dataLimit"] !== undefined) + data["DataLimit"] = params["dataLimit"]; + if (params["dataMetering"] !== undefined) + data["DataMetering"] = params["dataMetering"]; + if (params["messagingEnabled"] !== undefined) + data["MessagingEnabled"] = serialize.bool(params["messagingEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["nationalRoamingEnabled"] !== undefined) + data["NationalRoamingEnabled"] = serialize.bool(params["nationalRoamingEnabled"]); + if (params["internationalRoaming"] !== undefined) + data["InternationalRoaming"] = serialize.map(params["internationalRoaming"], (e: string) => (e)); + if (params["nationalRoamingDataLimit"] !== undefined) + data["NationalRoamingDataLimit"] = params["nationalRoamingDataLimit"]; + if (params["internationalRoamingDataLimit"] !== undefined) + data["InternationalRoamingDataLimit"] = params["internationalRoamingDataLimit"]; + if (params["dataLimitStrategy"] !== undefined) + data["DataLimitStrategy"] = params["dataLimitStrategy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.create({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new RatePlanInstance(operationVersion, payload)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.createWithHttpInfo = function createWithHttpInfo(params?: RatePlanListInstanceCreateOptions | ((error: Error | null, items: ApiResponse<RatePlanInstance>) => any), callback?: (error: Error | null, items: ApiResponse<RatePlanInstance>) => any): Promise<ApiResponse<RatePlanInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["dataEnabled"] !== undefined) + data["DataEnabled"] = serialize.bool(params["dataEnabled"]); + if (params["dataLimit"] !== undefined) + data["DataLimit"] = params["dataLimit"]; + if (params["dataMetering"] !== undefined) + data["DataMetering"] = params["dataMetering"]; + if (params["messagingEnabled"] !== undefined) + data["MessagingEnabled"] = serialize.bool(params["messagingEnabled"]); + if (params["voiceEnabled"] !== undefined) + data["VoiceEnabled"] = serialize.bool(params["voiceEnabled"]); + if (params["nationalRoamingEnabled"] !== undefined) + data["NationalRoamingEnabled"] = serialize.bool(params["nationalRoamingEnabled"]); + if (params["internationalRoaming"] !== undefined) + data["InternationalRoaming"] = serialize.map(params["internationalRoaming"], (e: string) => (e)); + if (params["nationalRoamingDataLimit"] !== undefined) + data["NationalRoamingDataLimit"] = params["nationalRoamingDataLimit"]; + if (params["internationalRoamingDataLimit"] !== undefined) + data["InternationalRoamingDataLimit"] = params["internationalRoamingDataLimit"]; + if (params["dataLimitStrategy"] !== undefined) + data["DataLimitStrategy"] = params["dataLimitStrategy"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + let operationVersion = version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.createWithResponseInfo<RatePlanResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<RatePlanInstance> => ({ + ...response, + body: new RatePlanInstance(operationVersion, response.body) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + instance.page = function page(params?: RatePlanListInstancePageOptions | ((error: Error | null, items: RatePlanPage) => any), callback?: (error: Error | null, items: RatePlanPage) => any): Promise<RatePlanPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new RatePlanPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: RatePlanPage) => any): Promise<RatePlanPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new RatePlanPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: RatePlanListInstancePageOptions | ((error: Error | null, items: ApiResponse<RatePlanPage>) => any), callback?: (error: Error | null, items: ApiResponse<RatePlanPage>) => any): Promise<ApiResponse<RatePlanPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<RatePlanPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RatePlanPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<RatePlanPage>) => any): Promise<ApiResponse<RatePlanPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<RatePlanPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new RatePlanPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class RatePlanPage extends Page<V1, RatePlanPayload, RatePlanResource, RatePlanInstance> { +/** +* Initialize the RatePlanPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: RatePlanSolution) { + super(version, response, solution); + } + + /** + * Build an instance of RatePlanInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: RatePlanResource): RatePlanInstance { + + return new RatePlanInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/wireless/v1/sim.ts b/rest/wireless/v1/sim.ts new file mode 100644 index 000000000..1e19e2baf --- /dev/null +++ b/rest/wireless/v1/sim.ts @@ -0,0 +1,1102 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Wireless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; +import { DataSessionListInstance } from "./sim/dataSession"; +import { UsageRecordListInstance } from "./sim/usageRecord"; + + +/** + * The connectivity reset status of the SIM. Can be: null or `resetting`. When a connectivity reset is initiated on a SIM, this property is `resetting`. After the reset completes, it is null. + */ +export type SimResetStatus = 'resetting'; + +/** + * The status of the Sim resource. Can be: `new`, `ready`, `active`, `deactivated`, `canceled`, `deleted`, `scheduled`, or `updating`. See [Status Values](https://www.twilio.com/docs/iot/wireless/api/sim-resource#status-values) for the description of each status. + */ +export type SimStatus = 'new'|'ready'|'active'|'suspended'|'deactivated'|'canceled'|'scheduled'|'updating'; + + + + +/** + * Options to pass to update a SimInstance + */ +export interface SimContextUpdateOptions { + /** An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. */ + "uniqueName"?: string; + /** The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. */ + "callbackMethod"?: string; + /** The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). */ + "callbackUrl"?: string; + /** A descriptive string that you create to describe the Sim resource. It does not need to be unique. */ + "friendlyName"?: string; + /** The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. */ + "ratePlan"?: string; + /** */ + "status"?: SimStatus; + /** The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. */ + "commandsCallbackMethod"?: string; + /** The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. */ + "commandsCallbackUrl"?: string; + /** The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. */ + "smsFallbackMethod"?: string; + /** The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. */ + "smsFallbackUrl"?: string; + /** The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. */ + "smsMethod"?: string; + /** The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). */ + "smsUrl"?: string; + /** Deprecated. */ + "voiceFallbackMethod"?: string; + /** Deprecated. */ + "voiceFallbackUrl"?: string; + /** Deprecated. */ + "voiceMethod"?: string; + /** Deprecated. */ + "voiceUrl"?: string; + /** */ + "resetStatus"?: SimResetStatus; + /** The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource\\\'s status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). */ + "accountSid"?: string; +} + +/** + * Options to pass to each + */ +export interface SimListInstanceEachOptions { + /** Only return Sim resources with this status. */ + "status"?: SimStatus; + /** Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. */ + "iccid"?: string; + /** The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. */ + "ratePlan"?: string; + /** Deprecated. */ + "eId"?: string; + /** Only return Sim resources with this registration code. This will return a list with a maximum size of 1. */ + "simRegistrationCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: SimInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface SimListInstanceOptions { + /** Only return Sim resources with this status. */ + "status"?: SimStatus; + /** Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. */ + "iccid"?: string; + /** The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. */ + "ratePlan"?: string; + /** Deprecated. */ + "eId"?: string; + /** Only return Sim resources with this registration code. This will return a list with a maximum size of 1. */ + "simRegistrationCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface SimListInstancePageOptions { + /** Only return Sim resources with this status. */ + "status"?: SimStatus; + /** Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. */ + "iccid"?: string; + /** The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. */ + "ratePlan"?: string; + /** Deprecated. */ + "eId"?: string; + /** Only return Sim resources with this registration code. This will return a list with a maximum size of 1. */ + "simRegistrationCode"?: string; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + +export interface SimContext { + dataSessions: DataSessionListInstance; + usageRecords: UsageRecordListInstance; + + /** + * Remove a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + /** + * Remove a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + /** + * Fetch a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + fetch(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> + + /** + * Fetch a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> + + /** + * Update a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + /** + * Update a SimInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + + /** + * Update a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + /** + * Update a SimInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export interface SimContextSolution { + "sid": string; +} + +export class SimContextImpl implements SimContext { + protected _solution: SimContextSolution; + protected _uri: string; + + protected _dataSessions?: DataSessionListInstance; + protected _usageRecords?: UsageRecordListInstance; + + constructor(protected _version: V1, sid: string) { + if (!isValidPathParam(sid)) { + throw new Error('Parameter \'sid\' is not valid.'); + } + + this._solution = { sid, }; + this._uri = `/Sims/${sid}`; + } + + get dataSessions(): DataSessionListInstance { + this._dataSessions = this._dataSessions || DataSessionListInstance(this._version, this._solution.sid); + return this._dataSessions; + } + + get usageRecords(): UsageRecordListInstance { + this._usageRecords = this._usageRecords || UsageRecordListInstance(this._version, this._solution.sid); + return this._usageRecords; + } + + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.remove({ uri: instance._uri, method: "delete", headers}); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> { + const headers: any = {}; + + const instance = this; + let operationVersion = instance._version; + // DELETE operation - returns boolean based on status code + let operationPromise = operationVersion.removeWithResponseInfo({ uri: instance._uri, method: "delete", headers}).then((response) : ApiResponse<boolean> => ({ + ...response, + body: response.statusCode === 204 + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetch(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.fetch({ uri: instance._uri, method: "get", headers}); + + operationPromise = operationPromise.then(payload => new SimInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> { + const headers: any = {}; + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.fetchWithResponseInfo<SimResource>({ uri: instance._uri, method: "get", headers}).then((response) : ApiResponse<SimInstance> => ({ + ...response, + body: new SimInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + update(params?: SimContextUpdateOptions | ((error: Error | null, item?: SimInstance) => any),callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["ratePlan"] !== undefined) + data["RatePlan"] = params["ratePlan"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["commandsCallbackMethod"] !== undefined) + data["CommandsCallbackMethod"] = params["commandsCallbackMethod"]; + if (params["commandsCallbackUrl"] !== undefined) + data["CommandsCallbackUrl"] = params["commandsCallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["resetStatus"] !== undefined) + data["ResetStatus"] = params["resetStatus"]; + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version, + operationPromise = operationVersion.update({ uri: instance._uri, method: "post", data, headers}); + + operationPromise = operationPromise.then(payload => new SimInstance(operationVersion, payload, instance._solution.sid)); + + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + updateWithHttpInfo(params?: SimContextUpdateOptions | ((error: Error | null, item?: ApiResponse<SimInstance>) => any),callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> { + if (params instanceof Function) { + callback = params; + params = {} as any; + } else { + params = params || {} as any; + } + + let data: any = {}; + + + if (params["uniqueName"] !== undefined) + data["UniqueName"] = params["uniqueName"]; + if (params["callbackMethod"] !== undefined) + data["CallbackMethod"] = params["callbackMethod"]; + if (params["callbackUrl"] !== undefined) + data["CallbackUrl"] = params["callbackUrl"]; + if (params["friendlyName"] !== undefined) + data["FriendlyName"] = params["friendlyName"]; + if (params["ratePlan"] !== undefined) + data["RatePlan"] = params["ratePlan"]; + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["commandsCallbackMethod"] !== undefined) + data["CommandsCallbackMethod"] = params["commandsCallbackMethod"]; + if (params["commandsCallbackUrl"] !== undefined) + data["CommandsCallbackUrl"] = params["commandsCallbackUrl"]; + if (params["smsFallbackMethod"] !== undefined) + data["SmsFallbackMethod"] = params["smsFallbackMethod"]; + if (params["smsFallbackUrl"] !== undefined) + data["SmsFallbackUrl"] = params["smsFallbackUrl"]; + if (params["smsMethod"] !== undefined) + data["SmsMethod"] = params["smsMethod"]; + if (params["smsUrl"] !== undefined) + data["SmsUrl"] = params["smsUrl"]; + if (params["voiceFallbackMethod"] !== undefined) + data["VoiceFallbackMethod"] = params["voiceFallbackMethod"]; + if (params["voiceFallbackUrl"] !== undefined) + data["VoiceFallbackUrl"] = params["voiceFallbackUrl"]; + if (params["voiceMethod"] !== undefined) + data["VoiceMethod"] = params["voiceMethod"]; + if (params["voiceUrl"] !== undefined) + data["VoiceUrl"] = params["voiceUrl"]; + if (params["resetStatus"] !== undefined) + data["ResetStatus"] = params["resetStatus"]; + if (params["accountSid"] !== undefined) + data["AccountSid"] = params["accountSid"]; + + + + + const headers: any = {}; + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + const instance = this; + let operationVersion = instance._version; + // CREATE, FETCH, UPDATE operations + let operationPromise = operationVersion.updateWithResponseInfo<SimResource>({ uri: instance._uri, method: "post", data, headers}).then((response) : ApiResponse<SimInstance> => ({ + ...response, + body: new SimInstance(operationVersion, response.body, instance._solution.sid) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return this._solution; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + + interface SimPayload extends TwilioResponsePayload { + sims: SimResource[]; +} + +interface SimResource { + sid: string; + unique_name: string; + account_sid: string; + rate_plan_sid: string; + friendly_name: string; + iccid: string; + e_id: string; + status: SimStatus; + reset_status: SimResetStatus; + commands_callback_url: string; + commands_callback_method: string; + sms_fallback_method: string; + sms_fallback_url: string; + sms_method: string; + sms_url: string; + voice_fallback_method: string; + voice_fallback_url: string; + voice_method: string; + voice_url: string; + date_created: Date; + date_updated: Date; + url: string; + links: Record<string, string>; + ip_address: string; +} + +export class SimInstance { + protected _solution: SimContextSolution; + protected _context?: SimContext; + + constructor(protected _version: V1, payload: SimResource, sid?: string) { + + this.sid = (payload.sid); + this.uniqueName = (payload.unique_name); + this.accountSid = (payload.account_sid); + this.ratePlanSid = (payload.rate_plan_sid); + this.friendlyName = (payload.friendly_name); + this.iccid = (payload.iccid); + this.eId = (payload.e_id); + this.status = payload.status; + this.resetStatus = payload.reset_status; + this.commandsCallbackUrl = (payload.commands_callback_url); + this.commandsCallbackMethod = (payload.commands_callback_method); + this.smsFallbackMethod = (payload.sms_fallback_method); + this.smsFallbackUrl = (payload.sms_fallback_url); + this.smsMethod = (payload.sms_method); + this.smsUrl = (payload.sms_url); + this.voiceFallbackMethod = (payload.voice_fallback_method); + this.voiceFallbackUrl = (payload.voice_fallback_url); + this.voiceMethod = (payload.voice_method); + this.voiceUrl = (payload.voice_url); + this.dateCreated = deserialize.iso8601DateTime(payload.date_created); + this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); + this.url = (payload.url); + this.links = (payload.links); + this.ipAddress = (payload.ip_address); + + this._solution = { sid: sid, }; + } + + /** + * The unique string that we created to identify the Sim resource. + */ + sid: string; + /** + * An application-defined string that uniquely identifies the resource. It can be used in place of the resource\'s `sid` in the URL to address the resource. + */ + uniqueName: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource belongs. + */ + accountSid: string; + /** + * The SID of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource is assigned. + */ + ratePlanSid: string; + /** + * The string that you assigned to describe the Sim resource. + */ + friendlyName: string; + /** + * The [ICCID](https://en.wikipedia.org/wiki/SIM_card#ICCID) associated with the SIM. + */ + iccid: string; + /** + * Deprecated. + */ + eId: string; + status: SimStatus; + resetStatus: SimResetStatus; + /** + * The URL we call using the `commands_callback_method` when the SIM originates a machine-to-machine [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + */ + commandsCallbackUrl: string; + /** + * The HTTP method we use to call `commands_callback_url`. Can be: `POST` or `GET`. Default is `POST`. + */ + commandsCallbackMethod: string; + /** + * Deprecated. + */ + smsFallbackMethod: string; + /** + * Deprecated. + */ + smsFallbackUrl: string; + /** + * Deprecated. + */ + smsMethod: string; + /** + * Deprecated. + */ + smsUrl: string; + /** + * Deprecated. The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + */ + voiceFallbackMethod: string; + /** + * Deprecated. The URL we call using the `voice_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `voice_url`. + */ + voiceFallbackUrl: string; + /** + * Deprecated. The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. Default is `POST`. + */ + voiceMethod: string; + /** + * Deprecated. The URL we call using the `voice_method` when the SIM-connected device makes a voice call. + */ + voiceUrl: string; + /** + * The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + dateCreated: Date; + /** + * The date and time in GMT when the Sim resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + dateUpdated: Date; + /** + * The absolute URL of the resource. + */ + url: string; + /** + * The URLs of related subresources. + */ + links: Record<string, string>; + /** + * Deprecated. + */ + ipAddress: string; + + private get _proxy(): SimContext { + this._context = this._context || new SimContextImpl(this._version, this._solution.sid); + return this._context; + } + + /** + * Remove a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean + */ + remove(callback?: (error: Error | null, item?: boolean) => any): Promise<boolean> + + { + return this._proxy.remove(callback); + } + + /** + * Remove a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed boolean with HTTP metadata + */ + removeWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<boolean>) => any): Promise<ApiResponse<boolean>> + + { + return this._proxy.removeWithHttpInfo(callback); + } + + /** + * Fetch a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + fetch(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> + + { + return this._proxy.fetch(callback); + } + + /** + * Fetch a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + fetchWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> + + { + return this._proxy.fetchWithHttpInfo(callback); + } + + /** + * Update a SimInstance + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + /** + * Update a SimInstance + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance + */ + update(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance>; + + update(params?: any, callback?: (error: Error | null, item?: SimInstance) => any): Promise<SimInstance> + { + return this._proxy.update(params, callback); + } + + /** + * Update a SimInstance and return HTTP info + * + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + /** + * Update a SimInstance and return HTTP info + * + * @param params - Parameter for request + * @param callback - Callback to handle processed record + * + * @returns Resolves to processed SimInstance with HTTP metadata + */ + updateWithHttpInfo(params: SimContextUpdateOptions, callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>>; + + updateWithHttpInfo(params?: any, callback?: (error: Error | null, item?: ApiResponse<SimInstance>) => any): Promise<ApiResponse<SimInstance>> + { + return this._proxy.updateWithHttpInfo(params, callback); + } + + /** + * Access the dataSessions. + */ + dataSessions(): DataSessionListInstance { + return this._proxy.dataSessions; + } + + /** + * Access the usageRecords. + */ + usageRecords(): UsageRecordListInstance { + return this._proxy.usageRecords; + } + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + uniqueName: this.uniqueName, + accountSid: this.accountSid, + ratePlanSid: this.ratePlanSid, + friendlyName: this.friendlyName, + iccid: this.iccid, + eId: this.eId, + status: this.status, + resetStatus: this.resetStatus, + commandsCallbackUrl: this.commandsCallbackUrl, + commandsCallbackMethod: this.commandsCallbackMethod, + smsFallbackMethod: this.smsFallbackMethod, + smsFallbackUrl: this.smsFallbackUrl, + smsMethod: this.smsMethod, + smsUrl: this.smsUrl, + voiceFallbackMethod: this.voiceFallbackMethod, + voiceFallbackUrl: this.voiceFallbackUrl, + voiceMethod: this.voiceMethod, + voiceUrl: this.voiceUrl, + dateCreated: this.dateCreated, + dateUpdated: this.dateUpdated, + url: this.url, + links: this.links, + ipAddress: this.ipAddress, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + + +export interface SimSolution { +} + +export interface SimListInstance { + _version: V1; + _solution: SimSolution; + _uri: string; + + (sid: string, ): SimContext; + get(sid: string, ): SimContext; + + + + + + + + + + /** + * Streams SimInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + each(params: SimListInstanceEachOptions, callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + /** + * Streams SimInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: SimListInstanceEachOptions, callback?: (item: SimInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of SimInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage>; + /** + * Retrieve a single target page of SimInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>>; + /** + * Lists SimInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: SimInstance[]) => any): Promise<SimInstance[]>; + list(params: SimListInstanceOptions, callback?: (error: Error | null, items: SimInstance[]) => any): Promise<SimInstance[]>; + /** + * Lists SimInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SimInstance[]>) => any): Promise<ApiResponse<SimInstance[]>>; + listWithHttpInfo(params: SimListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<SimInstance[]>) => any): Promise<ApiResponse<SimInstance[]>>; + /** + * Retrieve a single page of SimInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage>; + page(params: SimListInstancePageOptions, callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage>; + /** + * Retrieve a single page of SimInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { SimListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>>; + pageWithHttpInfo(params: SimListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function SimListInstance(version: V1): SimListInstance { + const instance = ((sid, ) => instance.get(sid, )) as SimListInstance; + + instance.get = function get(sid, ): SimContext { + return new SimContextImpl(version, sid); + } + + instance._version = version; + instance._solution = { }; + instance._uri = `/Sims`; + + instance.page = function page(params?: SimListInstancePageOptions | ((error: Error | null, items: SimPage) => any), callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["iccid"] !== undefined) + data["Iccid"] = params["iccid"]; + if (params["ratePlan"] !== undefined) + data["RatePlan"] = params["ratePlan"]; + if (params["eId"] !== undefined) + data["EId"] = params["eId"]; + if (params["simRegistrationCode"] !== undefined) + data["SimRegistrationCode"] = params["simRegistrationCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new SimPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: SimPage) => any): Promise<SimPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new SimPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: SimListInstancePageOptions | ((error: Error | null, items: ApiResponse<SimPage>) => any), callback?: (error: Error | null, items: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["status"] !== undefined) + data["Status"] = params["status"]; + if (params["iccid"] !== undefined) + data["Iccid"] = params["iccid"]; + if (params["ratePlan"] !== undefined) + data["RatePlan"] = params["ratePlan"]; + if (params["eId"] !== undefined) + data["EId"] = params["eId"]; + if (params["simRegistrationCode"] !== undefined) + data["SimRegistrationCode"] = params["simRegistrationCode"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<SimPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SimPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<SimPage>) => any): Promise<ApiResponse<SimPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<SimPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new SimPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + +export class SimPage extends Page<V1, SimPayload, SimResource, SimInstance> { +/** +* Initialize the SimPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: SimSolution) { + super(version, response, solution); + } + + /** + * Build an instance of SimInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: SimResource): SimInstance { + + return new SimInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/wireless/v1/sim/dataSession.ts b/rest/wireless/v1/sim/dataSession.ts new file mode 100644 index 000000000..c57375092 --- /dev/null +++ b/rest/wireless/v1/sim/dataSession.ts @@ -0,0 +1,489 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Wireless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + + +/** + * Options to pass to each + */ +export interface DataSessionListInstanceEachOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: DataSessionInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface DataSessionListInstanceOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface DataSessionListInstancePageOptions { + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface DataSessionSolution { + simSid: string; +} + +export interface DataSessionListInstance { + _version: V1; + _solution: DataSessionSolution; + _uri: string; + + + + + /** + * Streams DataSessionInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataSessionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: DataSessionInstance, done: (err?: Error) => void) => void): void; + each(params: DataSessionListInstanceEachOptions, callback?: (item: DataSessionInstance, done: (err?: Error) => void) => void): void; + /** + * Streams DataSessionInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataSessionListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: DataSessionInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: DataSessionListInstanceEachOptions, callback?: (item: DataSessionInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of DataSessionInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: DataSessionPage) => any): Promise<DataSessionPage>; + /** + * Retrieve a single target page of DataSessionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<DataSessionPage>) => any): Promise<ApiResponse<DataSessionPage>>; + /** + * Lists DataSessionInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataSessionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: DataSessionInstance[]) => any): Promise<DataSessionInstance[]>; + list(params: DataSessionListInstanceOptions, callback?: (error: Error | null, items: DataSessionInstance[]) => any): Promise<DataSessionInstance[]>; + /** + * Lists DataSessionInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataSessionListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DataSessionInstance[]>) => any): Promise<ApiResponse<DataSessionInstance[]>>; + listWithHttpInfo(params: DataSessionListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<DataSessionInstance[]>) => any): Promise<ApiResponse<DataSessionInstance[]>>; + /** + * Retrieve a single page of DataSessionInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataSessionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: DataSessionPage) => any): Promise<DataSessionPage>; + page(params: DataSessionListInstancePageOptions, callback?: (error: Error | null, items: DataSessionPage) => any): Promise<DataSessionPage>; + /** + * Retrieve a single page of DataSessionInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { DataSessionListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<DataSessionPage>) => any): Promise<ApiResponse<DataSessionPage>>; + pageWithHttpInfo(params: DataSessionListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<DataSessionPage>) => any): Promise<ApiResponse<DataSessionPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function DataSessionListInstance(version: V1, simSid: string): DataSessionListInstance { + if (!isValidPathParam(simSid)) { + throw new Error('Parameter \'simSid\' is not valid.'); + } + + const instance = {} as DataSessionListInstance; + + instance._version = version; + instance._solution = { simSid, }; + instance._uri = `/Sims/${simSid}/DataSessions`; + + instance.page = function page(params?: DataSessionListInstancePageOptions | ((error: Error | null, items: DataSessionPage) => any), callback?: (error: Error | null, items: DataSessionPage) => any): Promise<DataSessionPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new DataSessionPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: DataSessionPage) => any): Promise<DataSessionPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new DataSessionPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: DataSessionListInstancePageOptions | ((error: Error | null, items: ApiResponse<DataSessionPage>) => any), callback?: (error: Error | null, items: ApiResponse<DataSessionPage>) => any): Promise<ApiResponse<DataSessionPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<DataSessionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DataSessionPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<DataSessionPage>) => any): Promise<ApiResponse<DataSessionPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<DataSessionPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new DataSessionPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface DataSessionPayload extends TwilioResponsePayload { + data_sessions: DataSessionResource[]; +} + +interface DataSessionResource { + sid: string; + sim_sid: string; + account_sid: string; + radio_link: string; + operator_mcc: string; + operator_mnc: string; + operator_country: string; + operator_name: string; + cell_id: string; + cell_location_estimate: any; + packets_uploaded: number; + packets_downloaded: number; + last_updated: Date; + start: Date; + end: Date; + imei: string; +} + +export class DataSessionInstance { + + constructor(protected _version: V1, payload: DataSessionResource, simSid: string) { + + this.sid = (payload.sid); + this.simSid = (payload.sim_sid); + this.accountSid = (payload.account_sid); + this.radioLink = (payload.radio_link); + this.operatorMcc = (payload.operator_mcc); + this.operatorMnc = (payload.operator_mnc); + this.operatorCountry = (payload.operator_country); + this.operatorName = (payload.operator_name); + this.cellId = (payload.cell_id); + this.cellLocationEstimate = (payload.cell_location_estimate); + this.packetsUploaded = deserialize.integer(payload.packets_uploaded); + this.packetsDownloaded = deserialize.integer(payload.packets_downloaded); + this.lastUpdated = deserialize.iso8601DateTime(payload.last_updated); + this.start = deserialize.iso8601DateTime(payload.start); + this.end = deserialize.iso8601DateTime(payload.end); + this.imei = (payload.imei); + + } + + /** + * The unique string that we created to identify the DataSession resource. + */ + sid: string; + /** + * The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that the Data Session is for. + */ + simSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DataSession resource. + */ + accountSid: string; + /** + * The generation of wireless technology that the device was using. + */ + radioLink: string; + /** + * The \'mobile country code\' is the unique ID of the home country where the Data Session took place. See: [MCC/MNC lookup](http://mcc-mnc.com/). + */ + operatorMcc: string; + /** + * The \'mobile network code\' is the unique ID specific to the mobile operator network where the Data Session took place. + */ + operatorMnc: string; + /** + * The three letter country code representing where the device\'s Data Session took place. This is determined by looking up the `operator_mcc`. + */ + operatorCountry: string; + /** + * The friendly name of the mobile operator network that the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource)-connected device is attached to. This is determined by looking up the `operator_mnc`. + */ + operatorName: string; + /** + * The unique ID of the cellular tower that the device was attached to at the moment when the Data Session was last updated. + */ + cellId: string; + /** + * An object that describes the estimated location in latitude and longitude where the device\'s Data Session took place. The location is derived from the `cell_id` when the Data Session was last updated. See [Cell Location Estimate Object](https://www.twilio.com/docs/iot/wireless/api/datasession-resource#cell-location-estimate-object). + */ + cellLocationEstimate: any; + /** + * The number of packets uploaded by the device between the `start` time and when the Data Session was last updated. + */ + packetsUploaded: number; + /** + * The number of packets downloaded by the device between the `start` time and when the Data Session was last updated. + */ + packetsDownloaded: number; + /** + * The date that the resource was last updated, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + lastUpdated: Date; + /** + * The date that the Data Session started, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + start: Date; + /** + * The date that the record ended, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + end: Date; + /** + * The \'international mobile equipment identity\' is the unique ID of the device using the SIM to connect. An IMEI is a 15-digit string: 14 digits for the device identifier plus a check digit calculated using the Luhn formula. + */ + imei: string; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + sid: this.sid, + simSid: this.simSid, + accountSid: this.accountSid, + radioLink: this.radioLink, + operatorMcc: this.operatorMcc, + operatorMnc: this.operatorMnc, + operatorCountry: this.operatorCountry, + operatorName: this.operatorName, + cellId: this.cellId, + cellLocationEstimate: this.cellLocationEstimate, + packetsUploaded: this.packetsUploaded, + packetsDownloaded: this.packetsDownloaded, + lastUpdated: this.lastUpdated, + start: this.start, + end: this.end, + imei: this.imei, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class DataSessionPage extends Page<V1, DataSessionPayload, DataSessionResource, DataSessionInstance> { +/** +* Initialize the DataSessionPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: DataSessionSolution) { + super(version, response, solution); + } + + /** + * Build an instance of DataSessionInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: DataSessionResource): DataSessionInstance { + + return new DataSessionInstance( + this._version, + payload, + this._solution.simSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/wireless/v1/sim/usageRecord.ts b/rest/wireless/v1/sim/usageRecord.ts new file mode 100644 index 000000000..684bdde36 --- /dev/null +++ b/rest/wireless/v1/sim/usageRecord.ts @@ -0,0 +1,447 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Wireless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../../base/Page"; +import Response from "../../../../http/response"; +import V1 from "../../V1"; +const deserialize = require("../../../../base/deserialize"); +const serialize = require("../../../../base/serialize"); +import { isValidPathParam } from "../../../../base/utility"; +import { ApiResponse } from "../../../../base/ApiResponse"; + + +/** + * How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + */ +export type UsageRecordGranularity = 'hourly'|'daily'|'all'; + + +/** + * Options to pass to each + */ +export interface UsageRecordListInstanceEachOptions { + /** Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. */ + "end"?: Date; + /** Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. */ + "start"?: Date; + /** How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. */ + "granularity"?: UsageRecordGranularity; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UsageRecordListInstanceOptions { + /** Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. */ + "end"?: Date; + /** Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. */ + "start"?: Date; + /** How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. */ + "granularity"?: UsageRecordGranularity; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UsageRecordListInstancePageOptions { + /** Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. */ + "end"?: Date; + /** Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. */ + "start"?: Date; + /** How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. */ + "granularity"?: UsageRecordGranularity; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface UsageRecordSolution { + simSid: string; +} + +export interface UsageRecordListInstance { + _version: V1; + _solution: UsageRecordSolution; + _uri: string; + + + + + /** + * Streams UsageRecordInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + each(params: UsageRecordListInstanceEachOptions, callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UsageRecordInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UsageRecordListInstanceEachOptions, callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UsageRecordInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage>; + /** + * Retrieve a single target page of UsageRecordInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>>; + /** + * Lists UsageRecordInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UsageRecordInstance[]) => any): Promise<UsageRecordInstance[]>; + list(params: UsageRecordListInstanceOptions, callback?: (error: Error | null, items: UsageRecordInstance[]) => any): Promise<UsageRecordInstance[]>; + /** + * Lists UsageRecordInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UsageRecordInstance[]>) => any): Promise<ApiResponse<UsageRecordInstance[]>>; + listWithHttpInfo(params: UsageRecordListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<UsageRecordInstance[]>) => any): Promise<ApiResponse<UsageRecordInstance[]>>; + /** + * Retrieve a single page of UsageRecordInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage>; + page(params: UsageRecordListInstancePageOptions, callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage>; + /** + * Retrieve a single page of UsageRecordInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>>; + pageWithHttpInfo(params: UsageRecordListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UsageRecordListInstance(version: V1, simSid: string): UsageRecordListInstance { + if (!isValidPathParam(simSid)) { + throw new Error('Parameter \'simSid\' is not valid.'); + } + + const instance = {} as UsageRecordListInstance; + + instance._version = version; + instance._solution = { simSid, }; + instance._uri = `/Sims/${simSid}/UsageRecords`; + + instance.page = function page(params?: UsageRecordListInstancePageOptions | ((error: Error | null, items: UsageRecordPage) => any), callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["end"] !== undefined) + data["End"] = serialize.iso8601DateTime(params["end"]); + if (params["start"] !== undefined) + data["Start"] = serialize.iso8601DateTime(params["start"]); + if (params["granularity"] !== undefined) + data["Granularity"] = params["granularity"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UsageRecordPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UsageRecordPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UsageRecordListInstancePageOptions | ((error: Error | null, items: ApiResponse<UsageRecordPage>) => any), callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["end"] !== undefined) + data["End"] = serialize.iso8601DateTime(params["end"]); + if (params["start"] !== undefined) + data["Start"] = serialize.iso8601DateTime(params["start"]); + if (params["granularity"] !== undefined) + data["Granularity"] = params["granularity"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<UsageRecordPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UsageRecordPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<UsageRecordPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UsageRecordPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface UsageRecordPayload extends TwilioResponsePayload { + usage_records: UsageRecordResource[]; +} + +interface UsageRecordResource { + sim_sid: string; + account_sid: string; + period: any; + commands: any; + data: any; +} + +export class UsageRecordInstance { + + constructor(protected _version: V1, payload: UsageRecordResource, simSid: string) { + + this.simSid = (payload.sim_sid); + this.accountSid = (payload.account_sid); + this.period = (payload.period); + this.commands = (payload.commands); + this.data = (payload.data); + + } + + /** + * The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that this Usage Record is for. + */ + simSid: string; + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resource. + */ + accountSid: string; + /** + * The time period for which the usage is reported. Contains `start` and `end` datetime values given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + period: any; + /** + * An object that describes the SIM\'s usage of Commands during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/iot/wireless/api/sim-usagerecord-resource#commands-usage-object). + */ + commands: any; + /** + * An object that describes the SIM\'s data usage during the specified period. See [Data Usage Object](https://www.twilio.com/docs/iot/wireless/api/sim-usagerecord-resource#data-usage-object). + */ + data: any; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + simSid: this.simSid, + accountSid: this.accountSid, + period: this.period, + commands: this.commands, + data: this.data, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class UsageRecordPage extends Page<V1, UsageRecordPayload, UsageRecordResource, UsageRecordInstance> { +/** +* Initialize the UsageRecordPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: UsageRecordSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UsageRecordInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UsageRecordResource): UsageRecordInstance { + + return new UsageRecordInstance( + this._version, + payload, + this._solution.simSid, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } + diff --git a/rest/wireless/v1/usageRecord.ts b/rest/wireless/v1/usageRecord.ts new file mode 100644 index 000000000..a18ee9f55 --- /dev/null +++ b/rest/wireless/v1/usageRecord.ts @@ -0,0 +1,434 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Wireless + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { inspect, InspectOptions } from "util"; + +import Page, { TwilioResponsePayload } from "../../../base/Page"; +import Response from "../../../http/response"; +import V1 from "../V1"; +const deserialize = require("../../../base/deserialize"); +const serialize = require("../../../base/serialize"); +import { isValidPathParam } from "../../../base/utility"; +import { ApiResponse } from "../../../base/ApiResponse"; + + +/** + * How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + */ +export type UsageRecordGranularity = 'hourly'|'daily'|'all'; + + +/** + * Options to pass to each + */ +export interface UsageRecordListInstanceEachOptions { + /** Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). */ + "end"?: Date; + /** Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). */ + "start"?: Date; + /** How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. */ + "granularity"?: UsageRecordGranularity; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Function to process each record. If this and a positional callback are passed, this one will be used */ + callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void; + /** Function to be called upon completion of streaming */ + done?: Function; + /** Upper limit for the number of records to return. each() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + +/** + * Options to pass to list + */ +export interface UsageRecordListInstanceOptions { + /** Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). */ + "end"?: Date; + /** Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). */ + "start"?: Date; + /** How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. */ + "granularity"?: UsageRecordGranularity; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit */ + limit?: number; +} + + +/** + * Options to pass to page + */ +export interface UsageRecordListInstancePageOptions { + /** Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). */ + "end"?: Date; + /** Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). */ + "start"?: Date; + /** How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. */ + "granularity"?: UsageRecordGranularity; + /** How many resources to return in each list page. The default is 50, and the maximum is 1000. */ + "pageSize"?: number; + /** Page Number, this value is simply for client state */ + pageNumber?: number; + /** PageToken provided by the API */ + pageToken?: string; +} + + + +export interface UsageRecordSolution { +} + +export interface UsageRecordListInstance { + _version: V1; + _solution: UsageRecordSolution; + _uri: string; + + + + + /** + * Streams UsageRecordInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + each(callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + each(params: UsageRecordListInstanceEachOptions, callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + /** + * Streams UsageRecordInstance records from the API with HTTP metadata captured per page. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. HTTP metadata (status code, headers) is captured for each page request. + * + * The results are passed into the callback function, so this operation is memory + * efficient. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceEachOptions } [params] - Options for request + * @param { function } [callback] - Function to process each record + */ + eachWithHttpInfo(callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + eachWithHttpInfo(params: UsageRecordListInstanceEachOptions, callback?: (item: UsageRecordInstance, done: (err?: Error) => void) => void): void; + /** + * Retrieve a single target page of UsageRecordInstance records from the API. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records + */ + getPage(targetUrl: string, callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage>; + /** + * Retrieve a single target page of UsageRecordInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * @param { string } [targetUrl] - API-generated URL for the requested results page + * @param { function } [callback] - Callback to handle list of records with metadata + */ + getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>>; + /** + * Lists UsageRecordInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + list(callback?: (error: Error | null, items: UsageRecordInstance[]) => any): Promise<UsageRecordInstance[]>; + list(params: UsageRecordListInstanceOptions, callback?: (error: Error | null, items: UsageRecordInstance[]) => any): Promise<UsageRecordInstance[]>; + /** + * Lists UsageRecordInstance records from the API as a list with HTTP metadata. + * + * Returns all records along with HTTP metadata from the first page fetched. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstanceOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + listWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UsageRecordInstance[]>) => any): Promise<ApiResponse<UsageRecordInstance[]>>; + listWithHttpInfo(params: UsageRecordListInstanceOptions, callback?: (error: Error | null, items: ApiResponse<UsageRecordInstance[]>) => any): Promise<ApiResponse<UsageRecordInstance[]>>; + /** + * Retrieve a single page of UsageRecordInstance records from the API. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records + */ + page(callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage>; + page(params: UsageRecordListInstancePageOptions, callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage>; + /** + * Retrieve a single page of UsageRecordInstance records from the API with HTTP metadata. + * + * The request is executed immediately. + * + * If a function is passed as the first argument, it will be used as the callback + * function. + * + * @param { UsageRecordListInstancePageOptions } [params] - Options for request + * @param { function } [callback] - Callback to handle list of records with metadata + */ + pageWithHttpInfo(callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>>; + pageWithHttpInfo(params: UsageRecordListInstancePageOptions, callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>>; + + + /** + * Provide a user-friendly representation + */ + toJSON(): any; + [inspect.custom](_depth: any, options: InspectOptions): any; +} + +export function UsageRecordListInstance(version: V1): UsageRecordListInstance { + const instance = {} as UsageRecordListInstance; + + instance._version = version; + instance._solution = { }; + instance._uri = `/UsageRecords`; + + instance.page = function page(params?: UsageRecordListInstancePageOptions | ((error: Error | null, items: UsageRecordPage) => any), callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["end"] !== undefined) + data["End"] = serialize.iso8601DateTime(params["end"]); + if (params["start"] !== undefined) + data["Start"] = serialize.iso8601DateTime(params["start"]); + if (params["granularity"] !== undefined) + data["Granularity"] = params["granularity"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version, + operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}); + + + operationPromise = operationPromise.then(payload => new UsageRecordPage(operationVersion, payload, instance._solution)); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + + + instance.list = instance._version.list; + + + instance.getPage = function getPage(targetUrl: string, callback?: (error: Error | null, items: UsageRecordPage) => any): Promise<UsageRecordPage> { + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + let pagePromise = operationPromise.then(payload => new UsageRecordPage(instance._version, payload, instance._solution)); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.pageWithHttpInfo = function pageWithHttpInfo(params?: UsageRecordListInstancePageOptions | ((error: Error | null, items: ApiResponse<UsageRecordPage>) => any), callback?: (error: Error | null, items: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>> { + if (params instanceof Function) { + callback = params; + params = {}; + } else { + params = params || {}; + } + + let data: any = {}; + + if (params["end"] !== undefined) + data["End"] = serialize.iso8601DateTime(params["end"]); + if (params["start"] !== undefined) + data["Start"] = serialize.iso8601DateTime(params["start"]); + if (params["granularity"] !== undefined) + data["Granularity"] = params["granularity"]; + if (params["pageSize"] !== undefined) + data["PageSize"] = params["pageSize"]; + + + + + if (params.pageNumber !== undefined) data["Page"] = params.pageNumber; + if (params.pageToken !== undefined) data["PageToken"] = params.pageToken; + + + const headers: any = {}; + headers["Accept"] = "application/json" + + let operationVersion = version; + + // For page operations, use page() directly as it already returns { statusCode, body, headers } + // IMPORTANT: Pass full response to Page constructor, not response.body + let operationPromise = operationVersion.page({ uri: instance._uri, method: "get", params: data, headers}).then((response) : ApiResponse<UsageRecordPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UsageRecordPage(operationVersion, response, instance._solution) + })); + + operationPromise = instance._version.setPromiseCallback(operationPromise,callback); + return operationPromise; + + } + instance.each = instance._version.each; + instance.eachWithHttpInfo = instance._version.eachWithHttpInfo; + + instance.list = instance._version.list; + instance.listWithHttpInfo = instance._version.listWithHttpInfo; + + + instance.getPageWithHttpInfo = function getPageWithHttpInfo(targetUrl: string, callback?: (error: Error | null, items?: ApiResponse<UsageRecordPage>) => any): Promise<ApiResponse<UsageRecordPage>> { + // Use request() directly as it already returns { statusCode, body, headers } + const operationPromise = instance._version._domain.twilio.request({method: "get", uri: targetUrl}); + + let pagePromise = operationPromise.then((response): ApiResponse<UsageRecordPage> => ({ + statusCode: response.statusCode, + headers: response.headers, + body: new UsageRecordPage(instance._version, response, instance._solution) + })); + pagePromise = instance._version.setPromiseCallback(pagePromise, callback); + return pagePromise; + } + + + instance.toJSON = function toJSON() { + return instance._solution; + } + + instance[inspect.custom] = function inspectImpl(_depth: any, options: InspectOptions) { + return inspect(instance.toJSON(), options); + } + + return instance; +} + + interface UsageRecordPayload extends TwilioResponsePayload { + usage_records: UsageRecordResource[]; +} + +interface UsageRecordResource { + account_sid: string; + period: any; + commands: any; + data: any; +} + +export class UsageRecordInstance { + + constructor(protected _version: V1, payload: UsageRecordResource) { + + this.accountSid = (payload.account_sid); + this.period = (payload.period); + this.commands = (payload.commands); + this.data = (payload.data); + + } + + /** + * The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AccountUsageRecord resource. + */ + accountSid: string; + /** + * The time period for which usage is reported. Contains `start` and `end` properties that describe the period using GMT date-time values specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + */ + period: any; + /** + * An object that describes the aggregated Commands usage for all SIMs during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/iot/wireless/api/account-usagerecord-resource#commands-usage-object). + */ + commands: any; + /** + * An object that describes the aggregated Data usage for all SIMs over the period. See [Data Usage Object](https://www.twilio.com/docs/iot/wireless/api/account-usagerecord-resource#data-usage-object). + */ + data: any; + + /** + * Provide a user-friendly representation + * + * @returns Object + */ + toJSON() { + return { + accountSid: this.accountSid, + period: this.period, + commands: this.commands, + data: this.data, + }; + } + + [inspect.custom](_depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } +} + +export class UsageRecordPage extends Page<V1, UsageRecordPayload, UsageRecordResource, UsageRecordInstance> { +/** +* Initialize the UsageRecordPage +* +* @param version - Version of the resource +* @param response - Response from the API +* @param solution - Path solution +*/ +constructor(version: V1, response: Response<string>, solution: UsageRecordSolution) { + super(version, response, solution); + } + + /** + * Build an instance of UsageRecordInstance + * + * @param payload - Payload response from the API + */ + getInstance(payload: UsageRecordResource): UsageRecordInstance { + + return new UsageRecordInstance( + this._version, + payload, + ); + } + + [inspect.custom](depth: any, options: InspectOptions) { + return inspect(this.toJSON(), options); + } + } +